PageRenderTime 58ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/themes/grx-kanban/plugins/cmb2/includes/CMB2_Utils.php

https://gitlab.com/vitorhugoro1/grx-kanban
PHP | 415 lines | 214 code | 48 blank | 153 comment | 26 complexity | 0a21685e450a5d4a59f9fa67988ad4ab MD5 | raw file
  1. <?php
  2. /**
  3. * CMB2 Utilities
  4. *
  5. * @since 1.1.0
  6. *
  7. * @category WordPress_Plugin
  8. * @package CMB2
  9. * @author WebDevStudios
  10. * @license GPL-2.0+
  11. * @link http://webdevstudios.com
  12. */
  13. class CMB2_Utils {
  14. /**
  15. * The url which is used to load local resources.
  16. * @var string
  17. * @since 2.0.0
  18. */
  19. protected $url = '';
  20. /**
  21. * Utility method that attempts to get an attachment's ID by it's url
  22. * @since 1.0.0
  23. * @param string $img_url Attachment url
  24. * @return int|false Attachment ID or false
  25. */
  26. public function image_id_from_url( $img_url ) {
  27. $attachment_id = 0;
  28. $dir = wp_upload_dir();
  29. // Is URL in uploads directory?
  30. if ( false === strpos( $img_url, $dir['baseurl'] . '/' ) ) {
  31. return false;
  32. }
  33. $file = basename( $img_url );
  34. $query_args = array(
  35. 'post_type' => 'attachment',
  36. 'post_status' => 'inherit',
  37. 'fields' => 'ids',
  38. 'meta_query' => array(
  39. array(
  40. 'value' => $file,
  41. 'compare' => 'LIKE',
  42. 'key' => '_wp_attachment_metadata',
  43. ),
  44. )
  45. );
  46. $query = new WP_Query( $query_args );
  47. if ( $query->have_posts() ) {
  48. foreach ( $query->posts as $post_id ) {
  49. $meta = wp_get_attachment_metadata( $post_id );
  50. $original_file = basename( $meta['file'] );
  51. $cropped_image_files = isset( $meta['sizes'] ) ? wp_list_pluck( $meta['sizes'], 'file' ) : array();
  52. if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
  53. $attachment_id = $post_id;
  54. break;
  55. }
  56. }
  57. }
  58. return 0 === $attachment_id ? false : $attachment_id;
  59. }
  60. /**
  61. * Utility method that returns time string offset by timezone
  62. * @since 1.0.0
  63. * @param string $tzstring Time string
  64. * @return string Offset time string
  65. */
  66. public function timezone_offset( $tzstring ) {
  67. $tz_offset = 0;
  68. if ( ! empty( $tzstring ) && is_string( $tzstring ) ) {
  69. if ( 'UTC' === substr( $tzstring, 0, 3 ) ) {
  70. $tzstring = str_replace( array( ':15', ':30', ':45' ), array( '.25', '.5', '.75' ), $tzstring );
  71. return intval( floatval( substr( $tzstring, 3 ) ) * HOUR_IN_SECONDS );
  72. }
  73. try {
  74. $date_time_zone_selected = new DateTimeZone( $tzstring );
  75. $tz_offset = timezone_offset_get( $date_time_zone_selected, date_create() );
  76. } catch ( Exception $e ) {
  77. $this->log_if_debug( __METHOD__, __LINE__, $e->getMessage() );
  78. }
  79. }
  80. return $tz_offset;
  81. }
  82. /**
  83. * Utility method that returns a timezone string representing the default timezone for the site.
  84. *
  85. * Roughly copied from WordPress, as get_option('timezone_string') will return
  86. * an empty string if no value has been set on the options page.
  87. * A timezone string is required by the wp_timezone_choice() used by the
  88. * select_timezone field.
  89. *
  90. * @since 1.0.0
  91. * @return string Timezone string
  92. */
  93. public function timezone_string() {
  94. $current_offset = get_option( 'gmt_offset' );
  95. $tzstring = get_option( 'timezone_string' );
  96. // Remove old Etc mappings. Fallback to gmt_offset.
  97. if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) {
  98. $tzstring = '';
  99. }
  100. if ( empty( $tzstring ) ) { // Create a UTC+- zone if no timezone string exists
  101. if ( 0 == $current_offset ) {
  102. $tzstring = 'UTC+0';
  103. } elseif ( $current_offset < 0 ) {
  104. $tzstring = 'UTC' . $current_offset;
  105. } else {
  106. $tzstring = 'UTC+' . $current_offset;
  107. }
  108. }
  109. return $tzstring;
  110. }
  111. /**
  112. * Returns a timestamp, first checking if value already is a timestamp.
  113. * @since 2.0.0
  114. * @param string|int $string Possible timestamp string
  115. * @return int Time stamp
  116. */
  117. public function make_valid_time_stamp( $string ) {
  118. if ( ! $string ) {
  119. return 0;
  120. }
  121. return $this->is_valid_time_stamp( $string )
  122. ? (int) $string :
  123. strtotime( (string) $string );
  124. }
  125. /**
  126. * Determine if a value is a valid timestamp
  127. * @since 2.0.0
  128. * @param mixed $timestamp Value to check
  129. * @return boolean Whether value is a valid timestamp
  130. */
  131. public function is_valid_time_stamp( $timestamp ) {
  132. return (string) (int) $timestamp === (string) $timestamp
  133. && $timestamp <= PHP_INT_MAX
  134. && $timestamp >= ~PHP_INT_MAX;
  135. }
  136. /**
  137. * Checks if a value is 'empty'. Still accepts 0.
  138. * @since 2.0.0
  139. * @param mixed $value Value to check
  140. * @return bool True or false
  141. */
  142. public function isempty( $value ) {
  143. return null === $value || '' === $value || false === $value;
  144. }
  145. /**
  146. * Checks if a value is not 'empty'. 0 doesn't count as empty.
  147. * @since 2.2.2
  148. * @param mixed $value Value to check
  149. * @return bool True or false
  150. */
  151. public function notempty( $value ){
  152. return null !== $value && '' !== $value && false !== $value;
  153. }
  154. /**
  155. * Filters out empty values (not including 0).
  156. * @since 2.2.2
  157. * @param mixed $value Value to check
  158. * @return bool True or false
  159. */
  160. function filter_empty( $value ) {
  161. return array_filter( $value, array( $this, 'notempty' ) );
  162. }
  163. /**
  164. * Insert a single array item inside another array at a set position
  165. * @since 2.0.2
  166. * @param array &$array Array to modify. Is passed by reference, and no return is needed.
  167. * @param array $new New array to insert
  168. * @param int $position Position in the main array to insert the new array
  169. */
  170. public function array_insert( &$array, $new, $position ) {
  171. $before = array_slice( $array, 0, $position - 1 );
  172. $after = array_diff_key( $array, $before );
  173. $array = array_merge( $before, $new, $after );
  174. }
  175. /**
  176. * Defines the url which is used to load local resources.
  177. * This may need to be filtered for local Window installations.
  178. * If resources do not load, please check the wiki for details.
  179. * @since 1.0.1
  180. * @return string URL to CMB2 resources
  181. */
  182. public function url( $path = '' ) {
  183. if ( $this->url ) {
  184. return $this->url . $path;
  185. }
  186. $cmb2_url = self::get_url_from_dir( cmb2_dir() );
  187. /**
  188. * Filter the CMB location url
  189. *
  190. * @param string $cmb2_url Currently registered url
  191. */
  192. $this->url = trailingslashit( apply_filters( 'cmb2_meta_box_url', $cmb2_url, CMB2_VERSION ) );
  193. return $this->url . $path;
  194. }
  195. /**
  196. * Converts a system path to a URL
  197. * @since 2.2.2
  198. * @param string $dir Directory path to convert.
  199. * @return string Converted URL.
  200. */
  201. public static function get_url_from_dir( $dir ) {
  202. $dir = self::normalize_path( $dir );
  203. // Let's test if We are in the plugins or mu-plugins dir.
  204. $test_dir = trailingslashit( $dir ) . 'unneeded.php';
  205. if (
  206. 0 === strpos( $test_dir, self::normalize_path( WPMU_PLUGIN_DIR ) )
  207. || 0 === strpos( $test_dir, self::normalize_path( WP_PLUGIN_DIR ) )
  208. ) {
  209. // Ok, then use plugins_url, as it is more reliable.
  210. return trailingslashit( plugins_url( '', $test_dir ) );
  211. }
  212. // Ok, now let's test if we are in the theme dir.
  213. $theme_root = get_theme_root();
  214. if ( 0 === strpos( $dir, $theme_root ) ) {
  215. // Ok, then use get_theme_root_uri.
  216. return set_url_scheme( trailingslashit( str_replace( $theme_root, get_theme_root_uri(), $dir ) ) );
  217. }
  218. // Check to see if it's anywhere in the root directory
  219. $site_dir = ABSPATH;
  220. $site_url = trailingslashit( is_multisite() ? network_site_url() : site_url() );
  221. $url = str_replace(
  222. array( $site_dir, WP_PLUGIN_DIR ),
  223. array( $site_url, WP_PLUGIN_URL ),
  224. $dir
  225. );
  226. return set_url_scheme( $url );
  227. }
  228. /**
  229. * `wp_normalize_path` wrapper for back-compat. Normalize a filesystem path.
  230. *
  231. * On windows systems, replaces backslashes with forward slashes
  232. * and forces upper-case drive letters.
  233. * Allows for two leading slashes for Windows network shares, but
  234. * ensures that all other duplicate slashes are reduced to a single.
  235. *
  236. * @since 2.2.0
  237. *
  238. * @param string $path Path to normalize.
  239. * @return string Normalized path.
  240. */
  241. protected static function normalize_path( $path ) {
  242. if ( function_exists( 'wp_normalize_path' ) ) {
  243. return wp_normalize_path( $path );
  244. }
  245. // Replace newer WP's version of wp_normalize_path.
  246. $path = str_replace( '\\', '/', $path );
  247. $path = preg_replace( '|(?<=.)/+|', '/', $path );
  248. if ( ':' === substr( $path, 1, 1 ) ) {
  249. $path = ucfirst( $path );
  250. }
  251. return $path;
  252. }
  253. /**
  254. * Get timestamp from text date
  255. * @since 2.2.0
  256. * @param string $value Date value
  257. * @param string $date_format Expected date format
  258. * @return mixed Unix timestamp representing the date.
  259. */
  260. public function get_timestamp_from_value( $value, $date_format ) {
  261. $date_object = date_create_from_format( $date_format, $value );
  262. return $date_object ? $date_object->setTime( 0, 0, 0 )->getTimeStamp() : strtotime( $value );
  263. }
  264. /**
  265. * Takes a php date() format string and returns a string formatted to suit for the date/time pickers
  266. * It will work with only with the following subset ot date() options:
  267. *
  268. * d, j, z, m, n, y, and Y.
  269. *
  270. * A slight effort is made to deal with escaped characters.
  271. *
  272. * Other options are ignored, because they would either bring compatibility problems between PHP and JS, or
  273. * bring even more translation troubles.
  274. *
  275. * @since 2.2.0
  276. * @param string $format php date format
  277. * @return string reformatted string
  278. */
  279. public function php_to_js_dateformat( $format ) {
  280. // order is relevant here, since the replacement will be done sequentially.
  281. $supported_options = array(
  282. 'd' => 'dd', // Day, leading 0
  283. 'j' => 'd', // Day, no 0
  284. 'z' => 'o', // Day of the year, no leading zeroes,
  285. // 'D' => 'D', // Day name short, not sure how it'll work with translations
  286. // 'l' => 'DD', // Day name full, idem before
  287. 'm' => 'mm', // Month of the year, leading 0
  288. 'n' => 'm', // Month of the year, no leading 0
  289. // 'M' => 'M', // Month, Short name
  290. // 'F' => 'MM', // Month, full name,
  291. 'y' => 'y', // Year, two digit
  292. 'Y' => 'yy', // Year, full
  293. 'H' => 'HH', // Hour with leading 0 (24 hour)
  294. 'G' => 'H', // Hour with no leading 0 (24 hour)
  295. 'h' => 'hh', // Hour with leading 0 (12 hour)
  296. 'g' => 'h', // Hour with no leading 0 (12 hour),
  297. 'i' => 'mm', // Minute with leading 0,
  298. 's' => 'ss', // Second with leading 0,
  299. 'a' => 'tt', // am/pm
  300. 'A' => 'TT' // AM/PM
  301. );
  302. foreach ( $supported_options as $php => $js ) {
  303. // replaces every instance of a supported option, but skips escaped characters
  304. $format = preg_replace( "~(?<!\\\\)$php~", $js, $format );
  305. }
  306. $format = preg_replace_callback( '~(?:\\\.)+~', array( $this, 'wrap_escaped_chars' ), $format );
  307. return $format;
  308. }
  309. /**
  310. * Helper function for CMB_Utils->php_to_js_dateformat, because php 5.2 was retarded.
  311. * @since 2.2.0
  312. * @param $value Value to wrap/escape
  313. * @return string Modified value
  314. */
  315. public function wrap_escaped_chars( $value ) {
  316. return "&#39;" . str_replace( '\\', '', $value[0] ) . "&#39;";
  317. }
  318. /**
  319. * Send to debug.log if WP_DEBUG is defined and true
  320. *
  321. * @since 2.2.0
  322. *
  323. * @param string $function Function name
  324. * @param int $line Line number
  325. * @param mixed $msg Message to output
  326. * @param mixed $debug Variable to print_r
  327. */
  328. public function log_if_debug( $function, $line, $msg, $debug = null ) {
  329. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
  330. error_log( "In $function, $line:" . print_r( $msg, true ) . ( $debug ? print_r( $debug, true ) : '' ) );
  331. }
  332. }
  333. /**
  334. * Determine a file's extension
  335. * @since 1.0.0
  336. * @param string $file File url
  337. * @return string|false File extension or false
  338. */
  339. public function get_file_ext( $file ) {
  340. $parsed = @parse_url( $file, PHP_URL_PATH );
  341. return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false;
  342. }
  343. /**
  344. * Get the file name from a url
  345. * @since 2.0.0
  346. * @param string $value File url or path
  347. * @return string File name
  348. */
  349. public function get_file_name_from_path( $value ) {
  350. $parts = explode( '/', $value );
  351. return is_array( $parts ) ? end( $parts ) : $value;
  352. }
  353. /**
  354. * Check if WP version is at least $version.
  355. * @since 2.2.2
  356. * @param string $version WP version string to compare.
  357. * @return bool Result of comparison check.
  358. */
  359. public function wp_at_least( $version ) {
  360. global $wp_version;
  361. return version_compare( $wp_version, $version, '>=' );
  362. }
  363. }