PluginProbe
Code Snippets / 3.8.1
Code Snippets v3.8.1
3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 3.0.1 All 64 releases
code-snippets / php / class-snippet.php

class-snippet.php in Code Snippets 3.8.1, at php/class-snippet.php

467 lines 13.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Code_Snippets;
4
5 use DateTime;
6 use DateTimeZone;
7 use Exception;
8
9 /**
10 * A snippet object.
11 *
12 * @since 2.4.0
13 * @package Code_Snippets
14 *
15 * @property int $id The database ID.
16 * @property string $name The snippet title.
17 * @property string $desc The formatted description.
18 * @property string $code The executable code.
19 * @property array<string> $tags An array of the tags.
20 * @property string $scope The scope name.
21 * @property int $condition_id ID of the condition this snippet is linked to.
22 * @property int $priority Execution priority.
23 * @property bool $active The active status.
24 * @property bool $network true if is multisite-wide snippet, false if site-wide.
25 * @property bool $shared_network Whether the snippet is a shared network snippet.
26 * @property string $modified The date and time when the snippet data was most recently saved to the database.
27 * @property array{string,int}|null $code_error Code error encountered when last testing snippet code.
28 * @property int $revision Revision or version number of snippet.
29 * @property string $cloud_id Cloud ID and ownership status of snippet.
30 *
31 * @property-read string $display_name The snippet name if it exists or a placeholder if it does not.
32 * @property-read string $tags_list The tags in string list format.
33 * @property-read string $scope_icon The dashicon used to represent the current scope.
34 * @property-read string $scope_name Human-readable description of the snippet type.
35 * @property-read string $type The type of snippet.
36 * @property-read string $lang The language that the snippet code is written in.
37 * @property-read int $modified_timestamp The last modification date in Unix timestamp format.
38 * @property-read DateTime $modified_local The last modification date in the local timezone.
39 * @property-read boolean $is_pro Whether the snippet type is pro-only.
40 */
41 class Snippet extends Data_Item {
42
43 /**
44 * MySQL datetime format (YYYY-MM-DD hh:mm:ss).
45 */
46 public const DATE_FORMAT = 'Y-m-d H:i:s';
47
48 /**
49 * Default value used for a datetime variable.
50 */
51 public const DEFAULT_DATE = '0000-00-00 00:00:00';
52
53 /**
54 * Constructor function.
55 *
56 * @param array<string, mixed>|object $initial_data Initial snippet data.
57 */
58 public function __construct( $initial_data = null ) {
59 $default_values = array(
60 'id' => 0,
61 'name' => '',
62 'desc' => '',
63 'code' => '',
64 'tags' => array(),
65 'scope' => 'global',
66 'condition_id' => 0,
67 'active' => false,
68 'priority' => 10,
69 'network' => null,
70 'shared_network' => null,
71 'modified' => null,
72 'code_error' => null,
73 'revision' => 1,
74 'cloud_id' => '',
75 );
76
77 $field_aliases = array(
78 'description' => 'desc',
79 'language' => 'lang',
80 'conditionId' => 'condition_id',
81 );
82
83 parent::__construct( $default_values, $initial_data, $field_aliases );
84 }
85
86 /**
87 * Add a new tag
88 *
89 * @param string $tag Tag content to add to list.
90 */
91 public function add_tag( string $tag ) {
92 $this->fields['tags'][] = $tag;
93 }
94
95 /**
96 * Determine if the snippet is a condition.
97 *
98 * @return bool
99 */
100 public function is_condition(): bool {
101 return 'condition' === $this->scope;
102 }
103
104 /**
105 * Prepare a value before it is stored.
106 *
107 * @param mixed $value Value to prepare.
108 * @param string $field Field name.
109 *
110 * @return mixed Value in the correct format.
111 */
112 protected function prepare_field( $value, string $field ) {
113 switch ( $field ) {
114 case 'id':
115 case 'priority':
116 case 'condition_id':
117 return absint( $value );
118
119 case 'tags':
120 return code_snippets_build_tags_array( $value );
121
122 case 'active':
123 return ( is_bool( $value ) ? $value : (bool) $value ) && ! $this->is_condition();
124
125 default:
126 return $value;
127 }
128 }
129
130 /**
131 * Prepare the scope by ensuring that it is a valid choice
132 *
133 * @param int|string $scope The field as provided.
134 *
135 * @return string The field in the correct format.
136 */
137 protected function prepare_scope( $scope ) {
138 $scopes = self::get_all_scopes();
139
140 if ( in_array( $scope, $scopes, true ) ) {
141 return $scope;
142 }
143
144 if ( is_numeric( $scope ) && isset( $scopes[ $scope ] ) ) {
145 return $scopes[ $scope ];
146 }
147
148 return $this->fields['scope'];
149 }
150
151 /**
152 * If $network is anything other than true, set it to false
153 *
154 * @param bool $network The field as provided.
155 *
156 * @return bool The field in the correct format.
157 */
158 protected function prepare_network( bool $network ): bool {
159 if ( null === $network && function_exists( 'is_network_admin' ) ) {
160 return is_network_admin();
161 }
162
163 return true === $network;
164 }
165
166 /**
167 * Determine the type of code a given scope will produce.
168 *
169 * @param string $scope Scope name.
170 *
171 * @return string The snippet type – will be a filename extension.
172 */
173 public static function get_type_from_scope( string $scope ): string {
174 if ( '-css' === substr( $scope, -4 ) ) {
175 return 'css';
176 } elseif ( '-js' === substr( $scope, -3 ) ) {
177 return 'js';
178 } elseif ( 'content' === substr( $scope, -7 ) ) {
179 return 'html';
180 } elseif ( 'condition' === $scope ) {
181 return 'cond';
182 } else {
183 return 'php';
184 }
185 }
186
187 /**
188 * Determine the type of code this snippet is, based on its scope
189 *
190 * @return string The snippet type – will be a filename extension.
191 */
192 public function get_type(): string {
193 return self::get_type_from_scope( $this->scope );
194 }
195
196 /**
197 * Retrieve a list of all valid types.
198 *
199 * @return string[]
200 */
201 public static function get_types(): array {
202 return [ 'php', 'html', 'css', 'js', 'cond' ];
203 }
204
205 /**
206 * Determine the language that the snippet code is written in, based on the scope
207 *
208 * @return string The name of a language filename extension.
209 */
210 protected function get_lang(): string {
211 return 'cond' === $this->type ? 'json' : $this->type;
212 }
213
214 /**
215 * Prepare the modification field by ensuring it is in the correct format.
216 *
217 * @param DateTime|string $modified Snippet modification date.
218 *
219 * @return string
220 */
221 protected function prepare_modified( $modified ): ?string {
222
223 // If the supplied value is a DateTime object, convert it to string representation.
224 if ( $modified instanceof DateTime ) {
225 return $modified->format( self::DATE_FORMAT );
226 }
227
228 // If the supplied value is probably a timestamp, attempt to convert it to a string.
229 if ( is_numeric( $modified ) ) {
230 return gmdate( self::DATE_FORMAT, $modified );
231 }
232
233 // If the supplied value is a string, check it is not just the default value.
234 if ( is_string( $modified ) && self::DEFAULT_DATE !== $modified ) {
235 return $modified;
236 }
237
238 // Otherwise, discard the supplied value.
239 return null;
240 }
241
242 /**
243 * Update the last modification date to the current date and time.
244 *
245 * @return void
246 */
247 public function update_modified() {
248 $this->modified = gmdate( self::DATE_FORMAT );
249 }
250
251 /**
252 * Retrieve the snippet title if set or a placeholder title if not.
253 *
254 * @return string
255 */
256 protected function get_display_name(): string {
257 // translators: %s: snippet identifier.
258 return empty( $this->name ) ? sprintf( esc_html__( 'Snippet #%d', 'code-snippets' ), $this->id ) : $this->name;
259 }
260
261 /**
262 * Retrieve the tags in list format
263 *
264 * @return string The tags separated by a comma and a space.
265 */
266 protected function get_tags_list(): string {
267 return implode( ', ', $this->tags );
268 }
269
270 /**
271 * Retrieve a list of all available scopes
272 *
273 * @return array<string> List of scope names.
274 *
275 * @phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.ArrayItemNoNewLine
276 */
277 public static function get_all_scopes(): array {
278 return array(
279 'global', 'admin', 'front-end', 'single-use',
280 'content', 'head-content', 'footer-content',
281 'admin-css', 'site-css',
282 'site-head-js', 'site-footer-js',
283 'condition',
284 );
285 }
286
287 /**
288 * Retrieve a list of all scope icons
289 *
290 * @return array<string, string> Scope name keyed to the class name of a dashicon.
291 */
292 public static function get_scope_icons(): array {
293 return array(
294 'global' => 'admin-site',
295 'admin' => 'admin-tools',
296 'front-end' => 'admin-appearance',
297 'single-use' => 'clock',
298 'content' => 'shortcode',
299 'head-content' => 'editor-code',
300 'footer-content' => 'editor-code',
301 'admin-css' => 'dashboard',
302 'site-css' => 'admin-customizer',
303 'site-head-js' => 'media-code',
304 'site-footer-js' => 'media-code',
305 'condition' => 'randomize',
306 );
307 }
308
309 /**
310 * Retrieve the string representation of the scope
311 *
312 * @return string The name of the scope.
313 */
314 protected function get_scope_name(): string {
315 switch ( $this->scope ) {
316 case 'global':
317 return __( 'Global function', 'code-snippets' );
318 case 'admin':
319 return __( 'Admin function', 'code-snippets' );
320 case 'front-end':
321 return __( 'Front-end function', 'code-snippets' );
322 case 'single-use':
323 return __( 'Single-use function', 'code-snippets' );
324 case 'content':
325 return __( 'Content', 'code-snippets' );
326 case 'head-content':
327 return __( 'Head content', 'code-snippets' );
328 case 'footer-content':
329 return __( 'Footer content', 'code-snippets' );
330 case 'admin-css':
331 return __( 'Admin styles', 'code-snippets' );
332 case 'site-css':
333 return __( 'Front-end styles', 'code-snippets' );
334 case 'site-head-js':
335 return __( 'Head scripts', 'code-snippets' );
336 case 'site-footer-js':
337 return __( 'Footer scripts', 'code-snippets' );
338 }
339
340 return '';
341 }
342
343 /**
344 * Retrieve the icon used for the current scope
345 *
346 * @return string A dashicon name.
347 */
348 protected function get_scope_icon(): string {
349 $icons = self::get_scope_icons();
350
351 return $icons[ $this->scope ];
352 }
353
354 /**
355 * Determine if the snippet is a shared network snippet
356 *
357 * @return bool Whether the snippet is a shared network snippet.
358 */
359 protected function get_shared_network(): bool {
360 if ( isset( $this->fields['shared_network'] ) ) {
361 return $this->fields['shared_network'];
362 }
363
364 if ( ! is_multisite() || ! $this->fields['network'] ) {
365 $this->fields['shared_network'] = false;
366 } else {
367 $shared_network_snippets = get_site_option( 'shared_network_snippets', array() );
368 $this->fields['shared_network'] = in_array( $this->fields['id'], $shared_network_snippets, true );
369 }
370
371 return $this->fields['shared_network'];
372 }
373
374 /**
375 * Retrieve the snippet modification date as a timestamp.
376 *
377 * @return integer Timestamp value.
378 */
379 protected function get_modified_timestamp(): int {
380 $datetime = DateTime::createFromFormat( self::DATE_FORMAT, $this->modified, new DateTimeZone( 'UTC' ) );
381
382 return $datetime ? $datetime->getTimestamp() : 0;
383 }
384
385 /**
386 * Retrieve the modification time in the local timezone.
387 *
388 * @return DateTime
389 */
390 protected function get_modified_local(): DateTime {
391 $datetime = DateTime::createFromFormat( self::DATE_FORMAT, $this->modified, new DateTimeZone( 'UTC' ) );
392
393 if ( function_exists( 'wp_timezone' ) ) {
394 $timezone = wp_timezone();
395 } else {
396 $timezone = get_option( 'timezone_string' );
397
398 // Calculate the timezone manually if it is not available.
399 if ( ! $timezone ) {
400 $offset = (float) get_option( 'gmt_offset' );
401 $hours = (int) $offset;
402 $minutes = ( $offset - $hours ) * 60;
403
404 $sign = ( $offset < 0 ) ? '-' : '+';
405 $timezone = sprintf( '%s%02d:%02d', $sign, abs( $hours ), abs( $minutes ) );
406 }
407
408 try {
409 $timezone = new DateTimeZone( $timezone );
410 } catch ( Exception $exception ) {
411 return $datetime;
412 }
413 }
414
415 $datetime->setTimezone( $timezone );
416 return $datetime;
417 }
418
419 /**
420 * Retrieve the last modified time, nicely formatted for readability.
421 *
422 * @param boolean $include_html Whether to include HTML in the output.
423 *
424 * @return string
425 */
426 public function format_modified( bool $include_html = true ): string {
427 if ( ! $this->modified ) {
428 return '';
429 }
430
431 $timestamp = $this->modified_timestamp;
432 $time_diff = time() - $timestamp;
433 $local_time = $this->modified_local;
434
435 if ( $time_diff >= 0 && $time_diff < YEAR_IN_SECONDS ) {
436 // translators: %s: Human-readable time difference.
437 $human_time = sprintf( __( '%s ago', 'code-snippets' ), human_time_diff( $timestamp ) );
438 } else {
439 $human_time = $local_time->format( __( 'Y/m/d', 'code-snippets' ) );
440 }
441
442 if ( ! $include_html ) {
443 return $human_time;
444 }
445
446 // translators: 1: date format, 2: time format.
447 $date_format = _x( '%1$s at %2$s', 'date and time format', 'code-snippets' );
448 $date_format = sprintf( $date_format, get_option( 'date_format' ), get_option( 'time_format' ) );
449
450 return sprintf( '<span title="%s">%s</span>', $local_time->format( $date_format ), $human_time );
451 }
452
453 /**
454 * Determine whether the current snippet type is pro-only.
455 */
456 private function get_is_pro(): bool {
457 return 'css' === $this->type || 'js' === $this->type || 'cond' === $this->type;
458 }
459
460 /**
461 * Increment the revision number by one.
462 */
463 public function increment_revision() {
464 ++$this->revision;
465 }
466 }
467