Completed
Pull Request — master (#892)
by Jared
02:40
created
lib/timber-core.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -32,9 +32,9 @@
 block discarded – undo
32 32
      * @return mixed
33 33
      */
34 34
     function __get( $field ) {
35
-    	if ( property_exists($this, $field) ) {
36
-    		return $this->$field;
37
-    	}
35
+        if ( property_exists($this, $field) ) {
36
+            return $this->$field;
37
+        }
38 38
         if ( method_exists($this, 'meta') && $meta_value = $this->meta( $field ) ) {
39 39
             return $this->$field = $meta_value;
40 40
         }
Please login to merge, or discard this patch.
lib/timber-image-helper.php 1 patch
Indentation   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -15,514 +15,514 @@
 block discarded – undo
15 15
  */
16 16
 class TimberImageHelper {
17 17
 
18
-	const BASE_UPLOADS = 1;
19
-	const BASE_CONTENT = 2;
18
+    const BASE_UPLOADS = 1;
19
+    const BASE_CONTENT = 2;
20 20
 
21
-	public static function init() {
22
-		self::add_constants();
23
-		self::add_actions();
24
-		self::add_filters();
25
-	}
21
+    public static function init() {
22
+        self::add_constants();
23
+        self::add_actions();
24
+        self::add_filters();
25
+    }
26 26
 
27
-	/**
28
-	 * Generates a new image with the specified dimensions.
29
-	 * New dimensions are achieved by cropping to maintain ratio.
30
-	 *
31
-	 * @api
32
-	 * @param string  		$src an URL (absolute or relative) to the original image
33
-	 * @param int|string	$w target width(int) or WordPress image size (WP-set or user-defined).
34
-	 * @param int     		$h target height (ignored if $w is WP image size). If not set, will ignore and resize based on $w only.
35
-	 * @param string  		$crop your choices are 'default', 'center', 'top', 'bottom', 'left', 'right'
36
-	 * @param bool    		$force
37
-	 * @example
38
-	 * ```twig
39
-	 * <img src="{{ image.src | resize(300, 200, 'top') }}" />
40
-	 * ```
41
-	 * ```html
42
-	 * <img src="http://example.org/wp-content/uploads/pic-300x200-c-top.jpg" />
43
-	 * ```
44
-	 * @return string (ex: )
45
-	 */
46
-	public static function resize( $src, $w, $h = 0, $crop = 'default', $force = false ) {
47
-		if ( !is_numeric($w) && is_string($w) ) {
48
-			if ( $sizes = self::find_wp_dimensions($w) ) {
49
-				$w = $sizes['w'];
50
-				$h = $sizes['h'];
51
-			} else {
52
-				return $src;
53
-			}
54
-		}
55
-		$op = new TimberImageOperationResize($w, $h, $crop);
56
-		return self::_operate($src, $op, $force);
57
-	}
27
+    /**
28
+     * Generates a new image with the specified dimensions.
29
+     * New dimensions are achieved by cropping to maintain ratio.
30
+     *
31
+     * @api
32
+     * @param string  		$src an URL (absolute or relative) to the original image
33
+     * @param int|string	$w target width(int) or WordPress image size (WP-set or user-defined).
34
+     * @param int     		$h target height (ignored if $w is WP image size). If not set, will ignore and resize based on $w only.
35
+     * @param string  		$crop your choices are 'default', 'center', 'top', 'bottom', 'left', 'right'
36
+     * @param bool    		$force
37
+     * @example
38
+     * ```twig
39
+     * <img src="{{ image.src | resize(300, 200, 'top') }}" />
40
+     * ```
41
+     * ```html
42
+     * <img src="http://example.org/wp-content/uploads/pic-300x200-c-top.jpg" />
43
+     * ```
44
+     * @return string (ex: )
45
+     */
46
+    public static function resize( $src, $w, $h = 0, $crop = 'default', $force = false ) {
47
+        if ( !is_numeric($w) && is_string($w) ) {
48
+            if ( $sizes = self::find_wp_dimensions($w) ) {
49
+                $w = $sizes['w'];
50
+                $h = $sizes['h'];
51
+            } else {
52
+                return $src;
53
+            }
54
+        }
55
+        $op = new TimberImageOperationResize($w, $h, $crop);
56
+        return self::_operate($src, $op, $force);
57
+    }
58 58
 
59
-	/**
60
-	 * Find the sizes of an image based on a defined image size
61
-	 * @param  string $size the image size to search for
62
-	 *                      can be WordPress-defined ("medium")
63
-	 *                      or user-defined ("my-awesome-size")
64
-	 * @return false|array {
65
-	 *     @type int w
66
-	 *     @type int h
67
-	 * }
68
-	 */
69
-	private static function find_wp_dimensions( $size ) {
70
-		global $_wp_additional_image_sizes;
71
-		if ( isset($_wp_additional_image_sizes[$size]) ) {
72
-			$w = $_wp_additional_image_sizes[$size]['width'];
73
-			$h = $_wp_additional_image_sizes[$size]['height'];
74
-		} else if ( in_array($size, array('thumbnail', 'medium', 'large')) ) {
75
-			$w = get_option($size.'_size_w');
76
-			$h = get_option($size.'_size_h');
77
-		}
78
-		if ( isset($w) && isset($h) && ($w || $h) ) {
79
-			return array('w' => $w, 'h' => $h);
80
-		}
81
-		return false;
82
-	}
59
+    /**
60
+     * Find the sizes of an image based on a defined image size
61
+     * @param  string $size the image size to search for
62
+     *                      can be WordPress-defined ("medium")
63
+     *                      or user-defined ("my-awesome-size")
64
+     * @return false|array {
65
+     *     @type int w
66
+     *     @type int h
67
+     * }
68
+     */
69
+    private static function find_wp_dimensions( $size ) {
70
+        global $_wp_additional_image_sizes;
71
+        if ( isset($_wp_additional_image_sizes[$size]) ) {
72
+            $w = $_wp_additional_image_sizes[$size]['width'];
73
+            $h = $_wp_additional_image_sizes[$size]['height'];
74
+        } else if ( in_array($size, array('thumbnail', 'medium', 'large')) ) {
75
+            $w = get_option($size.'_size_w');
76
+            $h = get_option($size.'_size_h');
77
+        }
78
+        if ( isset($w) && isset($h) && ($w || $h) ) {
79
+            return array('w' => $w, 'h' => $h);
80
+        }
81
+        return false;
82
+    }
83 83
 
84
-	/**
85
-	 * Generates a new image with increased size, for display on Retina screens.
86
-	 *
87
-	 * @param string  $src
88
-	 * @param float   $multiplier
89
-	 * @param boolean $force
90
-	 *
91
-	 * @return string url to the new image
92
-	 */
93
-	public static function retina_resize( $src, $multiplier = 2, $force = false ) {
94
-		$op = new TimberImageOperationRetina($multiplier);
95
-		return self::_operate($src, $op, $force);
96
-	}
84
+    /**
85
+     * Generates a new image with increased size, for display on Retina screens.
86
+     *
87
+     * @param string  $src
88
+     * @param float   $multiplier
89
+     * @param boolean $force
90
+     *
91
+     * @return string url to the new image
92
+     */
93
+    public static function retina_resize( $src, $multiplier = 2, $force = false ) {
94
+        $op = new TimberImageOperationRetina($multiplier);
95
+        return self::_operate($src, $op, $force);
96
+    }
97 97
 
98
-	/**
99
-	 * checks to see if the given file is an aimated gif
100
-	 * @param  string  $file local filepath to a file, not a URL
101
-	 * @return boolean true if it's an animated gif, false if not
102
-	 */
103
-	public static function is_animated_gif( $file ) {
104
-		if ( strpos(strtolower($file), '.gif') == -1 ) {
105
-			//doesn't have .gif, bail
106
-			return false;
107
-		}
108
-		//its a gif so test
109
-		if( !($fh = @fopen($file, 'rb')) ) {
110
-		  	return false;
111
-		}
112
-		$count = 0;
113
-		//an animated gif contains multiple "frames", with each frame having a
114
-		//header made up of:
115
-		// * a static 4-byte sequence (\x00\x21\xF9\x04)
116
-		// * 4 variable bytes
117
-		// * a static 2-byte sequence (\x00\x2C)
98
+    /**
99
+     * checks to see if the given file is an aimated gif
100
+     * @param  string  $file local filepath to a file, not a URL
101
+     * @return boolean true if it's an animated gif, false if not
102
+     */
103
+    public static function is_animated_gif( $file ) {
104
+        if ( strpos(strtolower($file), '.gif') == -1 ) {
105
+            //doesn't have .gif, bail
106
+            return false;
107
+        }
108
+        //its a gif so test
109
+        if( !($fh = @fopen($file, 'rb')) ) {
110
+                return false;
111
+        }
112
+        $count = 0;
113
+        //an animated gif contains multiple "frames", with each frame having a
114
+        //header made up of:
115
+        // * a static 4-byte sequence (\x00\x21\xF9\x04)
116
+        // * 4 variable bytes
117
+        // * a static 2-byte sequence (\x00\x2C)
118 118
 
119
-		// We read through the file til we reach the end of the file, or we've found
120
-		// at least 2 frame headers
121
-		while(!feof($fh) && $count < 2) {
122
-			$chunk = fread($fh, 1024 * 100); //read 100kb at a time
123
-			$count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00[\x2C\x21]#s', $chunk, $matches);
124
-	    }
119
+        // We read through the file til we reach the end of the file, or we've found
120
+        // at least 2 frame headers
121
+        while(!feof($fh) && $count < 2) {
122
+            $chunk = fread($fh, 1024 * 100); //read 100kb at a time
123
+            $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00[\x2C\x21]#s', $chunk, $matches);
124
+        }
125 125
 
126
-	    fclose($fh);
127
-	    return $count > 1;
128
-	}
126
+        fclose($fh);
127
+        return $count > 1;
128
+    }
129 129
 
130
-	/**
131
-	 * Generate a new image with the specified dimensions.
132
-	 * New dimensions are achieved by adding colored bands to maintain ratio.
133
-	 *
134
-	 * @param string  $src
135
-	 * @param int     $w
136
-	 * @param int     $h
137
-	 * @param string  $color
138
-	 * @param bool    $force
139
-	 * @return mixed|null|string
140
-	 */
141
-	public static function letterbox( $src, $w, $h, $color = '#000000', $force = false ) {
142
-		$op = new TimberImageOperationLetterbox($w, $h, $color);
143
-		return self::_operate($src, $op, $force);
144
-	}
130
+    /**
131
+     * Generate a new image with the specified dimensions.
132
+     * New dimensions are achieved by adding colored bands to maintain ratio.
133
+     *
134
+     * @param string  $src
135
+     * @param int     $w
136
+     * @param int     $h
137
+     * @param string  $color
138
+     * @param bool    $force
139
+     * @return mixed|null|string
140
+     */
141
+    public static function letterbox( $src, $w, $h, $color = '#000000', $force = false ) {
142
+        $op = new TimberImageOperationLetterbox($w, $h, $color);
143
+        return self::_operate($src, $op, $force);
144
+    }
145 145
 
146
-	/**
147
-	 * Generates a new image by converting the source GIF or PNG into JPG
148
-	 *
149
-	 * @param string  $src   a url or path to the image (http://example.org/wp-content/uploads/2014/image.jpg) or (/wp-content/uploads/2014/image.jpg)
150
-	 * @param string  $bghex
151
-	 * @return string
152
-	 */
153
-	public static function img_to_jpg( $src, $bghex = '#FFFFFF', $force = false ) {
154
-		$op = new TimberImageOperationToJpg($bghex);
155
-		return self::_operate($src, $op, $force);
156
-	}
146
+    /**
147
+     * Generates a new image by converting the source GIF or PNG into JPG
148
+     *
149
+     * @param string  $src   a url or path to the image (http://example.org/wp-content/uploads/2014/image.jpg) or (/wp-content/uploads/2014/image.jpg)
150
+     * @param string  $bghex
151
+     * @return string
152
+     */
153
+    public static function img_to_jpg( $src, $bghex = '#FFFFFF', $force = false ) {
154
+        $op = new TimberImageOperationToJpg($bghex);
155
+        return self::_operate($src, $op, $force);
156
+    }
157 157
 
158
-	/**
159
-	 * Deletes all resized versions of an image when the source is deleted
160
-	 */
161
-	protected static function add_actions() {
162
-		add_action( 'delete_attachment', function ( $post_id ) {
163
-			$post = get_post( $post_id );
164
-			$image_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/jpg' );
165
-			if ( in_array( $post->post_mime_type, $image_types ) ) {
166
-				$attachment = new TimberImage( $post_id );
167
-				if ( $attachment->file_loc ) {
168
-					TimberImageHelper::delete_generated_files( $attachment->file_loc );
169
-				}
170
-			}
171
-		} );
172
-	}
158
+    /**
159
+     * Deletes all resized versions of an image when the source is deleted
160
+     */
161
+    protected static function add_actions() {
162
+        add_action( 'delete_attachment', function ( $post_id ) {
163
+            $post = get_post( $post_id );
164
+            $image_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/jpg' );
165
+            if ( in_array( $post->post_mime_type, $image_types ) ) {
166
+                $attachment = new TimberImage( $post_id );
167
+                if ( $attachment->file_loc ) {
168
+                    TimberImageHelper::delete_generated_files( $attachment->file_loc );
169
+                }
170
+            }
171
+        } );
172
+    }
173 173
 
174
-	/**
175
-	 * Adds a constant defining the path to the content directory relative to the site
176
-	 * for example /wp-content or /content
177
-	 */
178
-	protected static function add_constants() {
179
-		if ( !defined( 'WP_CONTENT_SUBDIR' ) ) {
180
-			$wp_content_path = str_replace( home_url(), '', WP_CONTENT_URL );
181
-			define( 'WP_CONTENT_SUBDIR', $wp_content_path );
182
-		}
183
-	}
174
+    /**
175
+     * Adds a constant defining the path to the content directory relative to the site
176
+     * for example /wp-content or /content
177
+     */
178
+    protected static function add_constants() {
179
+        if ( !defined( 'WP_CONTENT_SUBDIR' ) ) {
180
+            $wp_content_path = str_replace( home_url(), '', WP_CONTENT_URL );
181
+            define( 'WP_CONTENT_SUBDIR', $wp_content_path );
182
+        }
183
+    }
184 184
 
185
-	/**
186
-	 * adds a 'relative' key to wp_upload_dir() result.
187
-	 * It will contain the relative url to upload dir.
188
-	 * @return void
189
-	 */
190
-	static function add_filters() {
191
-		add_filter( 'upload_dir', function ( $arr ) {
192
-			$arr['relative'] = str_replace( home_url(), '', $arr['baseurl'] );
193
-			return $arr;
194
-		} );
195
-	}
185
+    /**
186
+     * adds a 'relative' key to wp_upload_dir() result.
187
+     * It will contain the relative url to upload dir.
188
+     * @return void
189
+     */
190
+    static function add_filters() {
191
+        add_filter( 'upload_dir', function ( $arr ) {
192
+            $arr['relative'] = str_replace( home_url(), '', $arr['baseurl'] );
193
+            return $arr;
194
+        } );
195
+    }
196 196
 
197
-	//-- end of public methods --//
198
-	/**
199
-	 * Deletes the auto-generated files for resize and letterboxing created by Timber
200
-	 * @param string  $local_file   ex: /var/www/wp-content/uploads/2015/my-pic.jpg
201
-	 *	                            or: http://example.org/wp-content/uploads/2015/my-pic.jpg
202
-	 */
203
-	static function delete_generated_files( $local_file ) {
204
-		if (TimberURLHelper::is_absolute( $local_file ) ) {
205
-			$local_file = TimberURLHelper::url_to_file_system( $local_file );
206
-		}
207
-		$info = pathinfo( $local_file );
208
-		$dir = $info['dirname'];
209
-		$ext = $info['extension'];
210
-		$filename = $info['filename'];
211
-		self::process_delete_generated_files( $filename, $ext, $dir, '-[0-9999999]*', '-[0-9]*x[0-9]*-c-[a-z]*.' );
212
-		self::process_delete_generated_files( $filename, $ext, $dir, '-lbox-[0-9999999]*', '-lbox-[0-9]*x[0-9]*-[a-zA-Z0-9]*.' );
213
-	}
197
+    //-- end of public methods --//
198
+    /**
199
+     * Deletes the auto-generated files for resize and letterboxing created by Timber
200
+     * @param string  $local_file   ex: /var/www/wp-content/uploads/2015/my-pic.jpg
201
+     *	                            or: http://example.org/wp-content/uploads/2015/my-pic.jpg
202
+     */
203
+    static function delete_generated_files( $local_file ) {
204
+        if (TimberURLHelper::is_absolute( $local_file ) ) {
205
+            $local_file = TimberURLHelper::url_to_file_system( $local_file );
206
+        }
207
+        $info = pathinfo( $local_file );
208
+        $dir = $info['dirname'];
209
+        $ext = $info['extension'];
210
+        $filename = $info['filename'];
211
+        self::process_delete_generated_files( $filename, $ext, $dir, '-[0-9999999]*', '-[0-9]*x[0-9]*-c-[a-z]*.' );
212
+        self::process_delete_generated_files( $filename, $ext, $dir, '-lbox-[0-9999999]*', '-lbox-[0-9]*x[0-9]*-[a-zA-Z0-9]*.' );
213
+    }
214 214
 
215
-	/**
216
-	 * Deletes resized versions of the supplied file name.
217
-	 * So if passed a value like my-pic.jpg, this function will delete my-pic-500x200-c-left.jpg, my-pic-400x400-c-default.jpg, etc.
218
-	 *
219
-	 * keeping these here so I know what the hell we're matching
220
-	 * $match = preg_match("/\/srv\/www\/wordpress-develop\/src\/wp-content\/uploads\/2014\/05\/$filename-[0-9]*x[0-9]*-c-[a-z]*.jpg/", $found_file);
221
-	 * $match = preg_match("/\/srv\/www\/wordpress-develop\/src\/wp-content\/uploads\/2014\/05\/arch-[0-9]*x[0-9]*-c-[a-z]*.jpg/", $filename);
222
-	 *
223
-	 * @param string 	$filename   ex: my-pic
224
-	 * @param string 	$ext ex: jpg
225
-	 * @param string 	$dir var/www/wp-content/uploads/2015/
226
-	 * @param string 	$search_pattern pattern of files to pluck from
227
-	 * @param string 	$match_pattern pattern of files to go forth and delete
228
-	 */
229
-	protected static function process_delete_generated_files( $filename, $ext, $dir, $search_pattern, $match_pattern ) {
230
-		$searcher = '/' . $filename . $search_pattern;
231
-		foreach ( glob( $dir . $searcher ) as $found_file ) {
232
-			$regexdir = str_replace( '/', '\/', $dir );
233
-			$pattern = '/' . ( $regexdir ) . '\/' . $filename . $match_pattern . $ext . '/';
234
-			$match = preg_match( $pattern, $found_file );
235
-			if ( $match ) {
236
-				unlink( $found_file );
237
-			}
238
-		}
239
-	}
215
+    /**
216
+     * Deletes resized versions of the supplied file name.
217
+     * So if passed a value like my-pic.jpg, this function will delete my-pic-500x200-c-left.jpg, my-pic-400x400-c-default.jpg, etc.
218
+     *
219
+     * keeping these here so I know what the hell we're matching
220
+     * $match = preg_match("/\/srv\/www\/wordpress-develop\/src\/wp-content\/uploads\/2014\/05\/$filename-[0-9]*x[0-9]*-c-[a-z]*.jpg/", $found_file);
221
+     * $match = preg_match("/\/srv\/www\/wordpress-develop\/src\/wp-content\/uploads\/2014\/05\/arch-[0-9]*x[0-9]*-c-[a-z]*.jpg/", $filename);
222
+     *
223
+     * @param string 	$filename   ex: my-pic
224
+     * @param string 	$ext ex: jpg
225
+     * @param string 	$dir var/www/wp-content/uploads/2015/
226
+     * @param string 	$search_pattern pattern of files to pluck from
227
+     * @param string 	$match_pattern pattern of files to go forth and delete
228
+     */
229
+    protected static function process_delete_generated_files( $filename, $ext, $dir, $search_pattern, $match_pattern ) {
230
+        $searcher = '/' . $filename . $search_pattern;
231
+        foreach ( glob( $dir . $searcher ) as $found_file ) {
232
+            $regexdir = str_replace( '/', '\/', $dir );
233
+            $pattern = '/' . ( $regexdir ) . '\/' . $filename . $match_pattern . $ext . '/';
234
+            $match = preg_match( $pattern, $found_file );
235
+            if ( $match ) {
236
+                unlink( $found_file );
237
+            }
238
+        }
239
+    }
240 240
 
241 241
 
242
-	/**
243
-	 * Determines the filepath corresponding to a given URL
244
-	 *
245
-	 * @param string  $url
246
-	 * @return string
247
-	 */
248
-	public static function get_server_location( $url ) {
249
-		// if we're already an absolute dir, just return
250
-		if ( 0 === strpos( $url, ABSPATH ) ) {
251
-			return $url;
252
-		}
253
-		// otherwise, analyze URL then build mapping path
254
-		$au = self::analyze_url($url);
255
-		$result = self::_get_file_path($au['base'], $au['subdir'], $au['basename']);
256
-		return $result;
257
-	}
242
+    /**
243
+     * Determines the filepath corresponding to a given URL
244
+     *
245
+     * @param string  $url
246
+     * @return string
247
+     */
248
+    public static function get_server_location( $url ) {
249
+        // if we're already an absolute dir, just return
250
+        if ( 0 === strpos( $url, ABSPATH ) ) {
251
+            return $url;
252
+        }
253
+        // otherwise, analyze URL then build mapping path
254
+        $au = self::analyze_url($url);
255
+        $result = self::_get_file_path($au['base'], $au['subdir'], $au['basename']);
256
+        return $result;
257
+    }
258 258
 
259
-	/**
260
-	 * Determines the filepath where a given external file will be stored.
261
-	 *
262
-	 * @param string  $file
263
-	 * @return string
264
-	 */
265
-	public static function get_sideloaded_file_loc( $file ) {
266
-		$upload = wp_upload_dir();
267
-		$dir = $upload['path'];
268
-		$filename = $file;
269
-		$file = parse_url( $file );
270
-		$path_parts = pathinfo( $file['path'] );
271
-		$basename = md5( $filename );
272
-		$ext = 'jpg';
273
-		if ( isset( $path_parts['extension'] ) ) {
274
-			$ext = $path_parts['extension'];
275
-		}
276
-		return $dir . '/' . $basename . '.' . $ext;
277
-	}
259
+    /**
260
+     * Determines the filepath where a given external file will be stored.
261
+     *
262
+     * @param string  $file
263
+     * @return string
264
+     */
265
+    public static function get_sideloaded_file_loc( $file ) {
266
+        $upload = wp_upload_dir();
267
+        $dir = $upload['path'];
268
+        $filename = $file;
269
+        $file = parse_url( $file );
270
+        $path_parts = pathinfo( $file['path'] );
271
+        $basename = md5( $filename );
272
+        $ext = 'jpg';
273
+        if ( isset( $path_parts['extension'] ) ) {
274
+            $ext = $path_parts['extension'];
275
+        }
276
+        return $dir . '/' . $basename . '.' . $ext;
277
+    }
278 278
 
279
-	/**
280
-	 * downloads an external image to the server and stores it on the server
281
-	 *
282
-	 * @param string  $file the URL to the original file
283
-	 * @return string the URL to the downloaded file
284
-	 */
285
-	public static function sideload_image( $file ) {
286
-		$loc = self::get_sideloaded_file_loc( $file );
287
-		if ( file_exists( $loc ) ) {
288
-			return TimberURLHelper::preslashit( TimberURLHelper::get_rel_path( $loc ) );
289
-		}
290
-		// Download file to temp location
291
-		if ( !function_exists( 'download_url' ) ) {
292
-			require_once ABSPATH . '/wp-admin/includes/file.php';
293
-		}
294
-		$tmp = download_url( $file );
295
-		preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
296
-		$file_array = array();
297
-		$file_array['name'] = basename( $matches[0] );
298
-		$file_array['tmp_name'] = $tmp;
299
-		// If error storing temporarily, unlink
300
-		if ( is_wp_error( $tmp ) ) {
301
-			@unlink( $file_array['tmp_name'] );
302
-			$file_array['tmp_name'] = '';
303
-		}
304
-		// do the validation and storage stuff
305
-		$locinfo = pathinfo( $loc );
306
-		$file = wp_upload_bits( $locinfo['basename'], null, file_get_contents( $file_array['tmp_name'] ) );
307
-		return $file['url'];
308
-	}
279
+    /**
280
+     * downloads an external image to the server and stores it on the server
281
+     *
282
+     * @param string  $file the URL to the original file
283
+     * @return string the URL to the downloaded file
284
+     */
285
+    public static function sideload_image( $file ) {
286
+        $loc = self::get_sideloaded_file_loc( $file );
287
+        if ( file_exists( $loc ) ) {
288
+            return TimberURLHelper::preslashit( TimberURLHelper::get_rel_path( $loc ) );
289
+        }
290
+        // Download file to temp location
291
+        if ( !function_exists( 'download_url' ) ) {
292
+            require_once ABSPATH . '/wp-admin/includes/file.php';
293
+        }
294
+        $tmp = download_url( $file );
295
+        preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
296
+        $file_array = array();
297
+        $file_array['name'] = basename( $matches[0] );
298
+        $file_array['tmp_name'] = $tmp;
299
+        // If error storing temporarily, unlink
300
+        if ( is_wp_error( $tmp ) ) {
301
+            @unlink( $file_array['tmp_name'] );
302
+            $file_array['tmp_name'] = '';
303
+        }
304
+        // do the validation and storage stuff
305
+        $locinfo = pathinfo( $loc );
306
+        $file = wp_upload_bits( $locinfo['basename'], null, file_get_contents( $file_array['tmp_name'] ) );
307
+        return $file['url'];
308
+    }
309 309
 
310
-	/**
311
-	 * Takes in an URL and breaks it into components,
312
-	 * that will then be used in the different steps of image processing.
313
-	 * The image is expected to be either part of a theme, plugin, or an upload.
314
-	 *
315
-	 * @param  string $url an URL (absolute or relative) pointing to an image
316
-	 * @return array       an array (see keys in code below)
317
-	 */
318
-	private static function analyze_url($url) {
319
-		$result = array(
320
-			'url' => $url, // the initial url
321
-			'absolute' => TimberURLHelper::is_absolute($url), // is the url absolute or relative (to home_url)
322
-			'base' => 0, // is the image in uploads dir, or in content dir (theme or plugin)
323
-			'subdir' => '', // the path between base (uploads or content) and file
324
-			'filename' => '', // the filename, without extension
325
-			'extension' => '', // the file extension
326
-			'basename' => '', // full file name
327
-		);
328
-		$upload_dir = wp_upload_dir();
329
-		$tmp = $url;
330
-		if ( 0 === strpos($tmp, ABSPATH) ) { // we've been given a dir, not an url
331
-			$result['absolute'] = true;
332
-			if ( 0 === strpos($tmp, $upload_dir['basedir']) ) {
333
-				$result['base']= self::BASE_UPLOADS; // upload based
334
-				$tmp = str_replace($upload_dir['basedir'], '', $tmp);
335
-			}
336
-			if ( 0 === strpos($tmp, WP_CONTENT_DIR) ) {
337
-				$result['base']= self::BASE_CONTENT; // content based
338
-				$tmp = str_replace(WP_CONTENT_DIR, '', $tmp);
339
-			}
340
-		} else {
341
-			if (!$result['absolute']) {
342
-				$tmp = home_url().$tmp;
343
-			}
344
-			if (0 === strpos($tmp, $upload_dir['baseurl'])) {
345
-				$result['base']= self::BASE_UPLOADS; // upload based
346
-				$tmp = str_replace($upload_dir['baseurl'], '', $tmp);
347
-			}
348
-			if (0 === strpos($tmp, content_url())) {
349
-				$result['base']= self::BASE_CONTENT; // content-based
350
-				$tmp = str_replace(content_url(), '', $tmp);
351
-			}
352
-		}
353
-		$parts = pathinfo($tmp);
354
-		$result['subdir'] = $parts['dirname'];
355
-		$result['filename'] = $parts['filename'];
356
-		$result['extension'] = $parts['extension'];
357
-		$result['basename'] = $parts['basename'];
358
-		// todo filename
359
-		return $result;
360
-	}
310
+    /**
311
+     * Takes in an URL and breaks it into components,
312
+     * that will then be used in the different steps of image processing.
313
+     * The image is expected to be either part of a theme, plugin, or an upload.
314
+     *
315
+     * @param  string $url an URL (absolute or relative) pointing to an image
316
+     * @return array       an array (see keys in code below)
317
+     */
318
+    private static function analyze_url($url) {
319
+        $result = array(
320
+            'url' => $url, // the initial url
321
+            'absolute' => TimberURLHelper::is_absolute($url), // is the url absolute or relative (to home_url)
322
+            'base' => 0, // is the image in uploads dir, or in content dir (theme or plugin)
323
+            'subdir' => '', // the path between base (uploads or content) and file
324
+            'filename' => '', // the filename, without extension
325
+            'extension' => '', // the file extension
326
+            'basename' => '', // full file name
327
+        );
328
+        $upload_dir = wp_upload_dir();
329
+        $tmp = $url;
330
+        if ( 0 === strpos($tmp, ABSPATH) ) { // we've been given a dir, not an url
331
+            $result['absolute'] = true;
332
+            if ( 0 === strpos($tmp, $upload_dir['basedir']) ) {
333
+                $result['base']= self::BASE_UPLOADS; // upload based
334
+                $tmp = str_replace($upload_dir['basedir'], '', $tmp);
335
+            }
336
+            if ( 0 === strpos($tmp, WP_CONTENT_DIR) ) {
337
+                $result['base']= self::BASE_CONTENT; // content based
338
+                $tmp = str_replace(WP_CONTENT_DIR, '', $tmp);
339
+            }
340
+        } else {
341
+            if (!$result['absolute']) {
342
+                $tmp = home_url().$tmp;
343
+            }
344
+            if (0 === strpos($tmp, $upload_dir['baseurl'])) {
345
+                $result['base']= self::BASE_UPLOADS; // upload based
346
+                $tmp = str_replace($upload_dir['baseurl'], '', $tmp);
347
+            }
348
+            if (0 === strpos($tmp, content_url())) {
349
+                $result['base']= self::BASE_CONTENT; // content-based
350
+                $tmp = str_replace(content_url(), '', $tmp);
351
+            }
352
+        }
353
+        $parts = pathinfo($tmp);
354
+        $result['subdir'] = $parts['dirname'];
355
+        $result['filename'] = $parts['filename'];
356
+        $result['extension'] = $parts['extension'];
357
+        $result['basename'] = $parts['basename'];
358
+        // todo filename
359
+        return $result;
360
+    }
361 361
 
362
-	/**
363
-	 * Builds the public URL of a file based on its different components
364
-	 *
365
-	 * @param  int    $base     one of self::BASE_UPLOADS, self::BASE_CONTENT to indicate if file is an upload or a content (theme or plugin)
366
-	 * @param  string $subdir   subdirectory in which file is stored, relative to $base root folder
367
-	 * @param  string $filename file name, including extension (but no path)
368
-	 * @param  bool   $absolute should the returned URL be absolute (include protocol+host), or relative
369
-	 * @return string           the URL
370
-	 */
371
-	private static function _get_file_url($base, $subdir, $filename, $absolute) {
372
-		$url = '';
373
-		if( self::BASE_UPLOADS == $base ) {
374
-			$upload_dir = wp_upload_dir();
375
-			$url = $upload_dir['baseurl'];
376
-		}
377
-		if( self::BASE_CONTENT == $base ) {
378
-			$url = content_url();
379
-		}
380
-		if(!empty($subdir)) {
381
-			$url .= $subdir;
382
-		}
383
-		$url .= '/'.$filename;
384
-		if(!$absolute) {
385
-			$url = str_replace(home_url(), '', $url);
386
-		}
387
-		// $url = TimberURLHelper::remove_double_slashes( $url);
388
-		return $url;
389
-	}
362
+    /**
363
+     * Builds the public URL of a file based on its different components
364
+     *
365
+     * @param  int    $base     one of self::BASE_UPLOADS, self::BASE_CONTENT to indicate if file is an upload or a content (theme or plugin)
366
+     * @param  string $subdir   subdirectory in which file is stored, relative to $base root folder
367
+     * @param  string $filename file name, including extension (but no path)
368
+     * @param  bool   $absolute should the returned URL be absolute (include protocol+host), or relative
369
+     * @return string           the URL
370
+     */
371
+    private static function _get_file_url($base, $subdir, $filename, $absolute) {
372
+        $url = '';
373
+        if( self::BASE_UPLOADS == $base ) {
374
+            $upload_dir = wp_upload_dir();
375
+            $url = $upload_dir['baseurl'];
376
+        }
377
+        if( self::BASE_CONTENT == $base ) {
378
+            $url = content_url();
379
+        }
380
+        if(!empty($subdir)) {
381
+            $url .= $subdir;
382
+        }
383
+        $url .= '/'.$filename;
384
+        if(!$absolute) {
385
+            $url = str_replace(home_url(), '', $url);
386
+        }
387
+        // $url = TimberURLHelper::remove_double_slashes( $url);
388
+        return $url;
389
+    }
390 390
 
391
-	/**
392
-	 * Builds the absolute file system location of a file based on its different components
393
-	 *
394
-	 * @param  int    $base     one of self::BASE_UPLOADS, self::BASE_CONTENT to indicate if file is an upload or a content (theme or plugin)
395
-	 * @param  string $subdir   subdirectory in which file is stored, relative to $base root folder
396
-	 * @param  string $filename file name, including extension (but no path)
397
-	 * @return string           the file location
398
-	 */
399
-	private static function _get_file_path($base, $subdir, $filename) {
400
-		$path = '';
401
-		if(self::BASE_UPLOADS == $base) {
402
-			$upload_dir = wp_upload_dir();
403
-			$path = $upload_dir['basedir'];
404
-		}
405
-		if(self::BASE_CONTENT == $base) {
406
-			$path = WP_CONTENT_DIR;
407
-		}
408
-		if(!empty($subdir)) {
409
-			$path .= $subdir;
410
-		}
411
-		$path .= '/'.$filename;
412
-		return $path;
413
-	}
391
+    /**
392
+     * Builds the absolute file system location of a file based on its different components
393
+     *
394
+     * @param  int    $base     one of self::BASE_UPLOADS, self::BASE_CONTENT to indicate if file is an upload or a content (theme or plugin)
395
+     * @param  string $subdir   subdirectory in which file is stored, relative to $base root folder
396
+     * @param  string $filename file name, including extension (but no path)
397
+     * @return string           the file location
398
+     */
399
+    private static function _get_file_path($base, $subdir, $filename) {
400
+        $path = '';
401
+        if(self::BASE_UPLOADS == $base) {
402
+            $upload_dir = wp_upload_dir();
403
+            $path = $upload_dir['basedir'];
404
+        }
405
+        if(self::BASE_CONTENT == $base) {
406
+            $path = WP_CONTENT_DIR;
407
+        }
408
+        if(!empty($subdir)) {
409
+            $path .= $subdir;
410
+        }
411
+        $path .= '/'.$filename;
412
+        return $path;
413
+    }
414 414
 
415 415
 
416
-	/**
417
-	 * Main method that applies operation to src image:
418
-	 * 1. break down supplied URL into components
419
-	 * 2. use components to determine result file and URL
420
-	 * 3. check if a result file already exists
421
-	 * 4. otherwise, delegate to supplied TimberImageOperation
422
-	 *
423
-	 * @param  string  $src   an URL (absolute or relative) to an image
424
-	 * @param  object  $op    object of class TimberImageOperation
425
-	 * @param  boolean $force if true, remove any already existing result file and forces file generation
426
-	 * @return string         URL to the new image - or the source one if error
427
-	 *
428
-	 */
429
-	private static function _operate( $src, $op, $force = false ) {
430
-		if ( empty( $src ) ) {
431
-			return '';
432
-		}
433
-		$external = false;
416
+    /**
417
+     * Main method that applies operation to src image:
418
+     * 1. break down supplied URL into components
419
+     * 2. use components to determine result file and URL
420
+     * 3. check if a result file already exists
421
+     * 4. otherwise, delegate to supplied TimberImageOperation
422
+     *
423
+     * @param  string  $src   an URL (absolute or relative) to an image
424
+     * @param  object  $op    object of class TimberImageOperation
425
+     * @param  boolean $force if true, remove any already existing result file and forces file generation
426
+     * @return string         URL to the new image - or the source one if error
427
+     *
428
+     */
429
+    private static function _operate( $src, $op, $force = false ) {
430
+        if ( empty( $src ) ) {
431
+            return '';
432
+        }
433
+        $external = false;
434 434
 
435
-		// if external image, load it first
436
-		if ( TimberURLHelper::is_external_content( $src ) ) {
437
-			$src = self::sideload_image( $src );
438
-			$external = true;
439
-		}
440
-		// break down URL into components
441
-		$au = self::analyze_url($src);
442
-		// build URL and filenames
443
-		$new_url = self::_get_file_url(
444
-			$au['base'],
445
-			$au['subdir'],
446
-			$op->filename($au['filename'], $au['extension']),
447
-			$au['absolute']
448
-		);
449
-		$new_server_path = self::_get_file_path(
450
-			$au['base'],
451
-			$au['subdir'],
452
-			$op->filename($au['filename'], $au['extension'])
453
-		);
454
-		$old_server_path = self::_get_file_path(
455
-			$au['base'],
456
-			$au['subdir'],
457
-			$au['basename']
458
-		);
459
-		// if already exists...
460
-		if ( file_exists( $new_server_path ) ) {
461
-			if ( $force ) {
462
-				// Force operation - warning: will regenerate the image on every pageload, use for testing purposes only!
463
-				unlink( $new_server_path );
464
-			} else {
465
-				// return existing file (caching)
466
-				return $new_url;
467
-			}
468
-		}
469
-		// otherwise generate result file
470
-		if($op->run($old_server_path, $new_server_path)) {
471
-			if( get_class( $op ) === 'TimberImageOperationResize' && $external ) {
472
-				$new_url = strtolower( $new_url );
473
-			}
474
-			return $new_url;
475
-		} else {
476
-			// in case of error, we return source file itself
477
-			return $src;
478
-		}
479
-	}
435
+        // if external image, load it first
436
+        if ( TimberURLHelper::is_external_content( $src ) ) {
437
+            $src = self::sideload_image( $src );
438
+            $external = true;
439
+        }
440
+        // break down URL into components
441
+        $au = self::analyze_url($src);
442
+        // build URL and filenames
443
+        $new_url = self::_get_file_url(
444
+            $au['base'],
445
+            $au['subdir'],
446
+            $op->filename($au['filename'], $au['extension']),
447
+            $au['absolute']
448
+        );
449
+        $new_server_path = self::_get_file_path(
450
+            $au['base'],
451
+            $au['subdir'],
452
+            $op->filename($au['filename'], $au['extension'])
453
+        );
454
+        $old_server_path = self::_get_file_path(
455
+            $au['base'],
456
+            $au['subdir'],
457
+            $au['basename']
458
+        );
459
+        // if already exists...
460
+        if ( file_exists( $new_server_path ) ) {
461
+            if ( $force ) {
462
+                // Force operation - warning: will regenerate the image on every pageload, use for testing purposes only!
463
+                unlink( $new_server_path );
464
+            } else {
465
+                // return existing file (caching)
466
+                return $new_url;
467
+            }
468
+        }
469
+        // otherwise generate result file
470
+        if($op->run($old_server_path, $new_server_path)) {
471
+            if( get_class( $op ) === 'TimberImageOperationResize' && $external ) {
472
+                $new_url = strtolower( $new_url );
473
+            }
474
+            return $new_url;
475
+        } else {
476
+            // in case of error, we return source file itself
477
+            return $src;
478
+        }
479
+    }
480 480
 
481 481
 
482 482
 // -- the below methods are just used for unit testing the URL generation code
483 483
 //
484
-	static function get_letterbox_file_url($url, $w, $h, $color) {
485
-		$au = self::analyze_url($url);
486
-		$op = new TimberImageOperationLetterbox($w, $h, $color);
487
-		$new_url = self::_get_file_url(
488
-			$au['base'],
489
-			$au['subdir'],
490
-			$op->filename($au['filename'], $au['extension']),
491
-			$au['absolute']
492
-		);
493
-		return $new_url;
494
-	}
495
-	public static function get_letterbox_file_path($url, $w, $h, $color ) {
496
-		$au = self::analyze_url($url);
497
-		$op = new TimberImageOperationLetterbox($w, $h, $color);
498
-		$new_path = self::_get_file_path(
499
-			$au['base'],
500
-			$au['subdir'],
501
-			$op->filename($au['filename'], $au['extension'])
502
-		);
503
-		return $new_path;
504
-	}
505
-	static function get_resize_file_url($url, $w, $h, $crop) {
506
-		$au = self::analyze_url($url);
507
-		$op = new TimberImageOperationResize($w, $h, $crop);
508
-		$new_url = self::_get_file_url(
509
-			$au['base'],
510
-			$au['subdir'],
511
-			$op->filename($au['filename'], $au['extension']),
512
-			$au['absolute']
513
-		);
514
-		return $new_url;
515
-	}
516
-	static function get_resize_file_path($url, $w, $h, $crop) {
517
-		$au = self::analyze_url($url);
518
-		$op = new TimberImageOperationResize($w, $h, $crop);
519
-		$new_path = self::_get_file_path(
520
-			$au['base'],
521
-			$au['subdir'],
522
-			$op->filename($au['filename'], $au['extension'])
523
-		);
524
-		return $new_path;
525
-	}
484
+    static function get_letterbox_file_url($url, $w, $h, $color) {
485
+        $au = self::analyze_url($url);
486
+        $op = new TimberImageOperationLetterbox($w, $h, $color);
487
+        $new_url = self::_get_file_url(
488
+            $au['base'],
489
+            $au['subdir'],
490
+            $op->filename($au['filename'], $au['extension']),
491
+            $au['absolute']
492
+        );
493
+        return $new_url;
494
+    }
495
+    public static function get_letterbox_file_path($url, $w, $h, $color ) {
496
+        $au = self::analyze_url($url);
497
+        $op = new TimberImageOperationLetterbox($w, $h, $color);
498
+        $new_path = self::_get_file_path(
499
+            $au['base'],
500
+            $au['subdir'],
501
+            $op->filename($au['filename'], $au['extension'])
502
+        );
503
+        return $new_path;
504
+    }
505
+    static function get_resize_file_url($url, $w, $h, $crop) {
506
+        $au = self::analyze_url($url);
507
+        $op = new TimberImageOperationResize($w, $h, $crop);
508
+        $new_url = self::_get_file_url(
509
+            $au['base'],
510
+            $au['subdir'],
511
+            $op->filename($au['filename'], $au['extension']),
512
+            $au['absolute']
513
+        );
514
+        return $new_url;
515
+    }
516
+    static function get_resize_file_path($url, $w, $h, $crop) {
517
+        $au = self::analyze_url($url);
518
+        $op = new TimberImageOperationResize($w, $h, $crop);
519
+        $new_path = self::_get_file_path(
520
+            $au['base'],
521
+            $au['subdir'],
522
+            $op->filename($au['filename'], $au['extension'])
523
+        );
524
+        return $new_path;
525
+    }
526 526
 
527 527
 
528 528
 }
Please login to merge, or discard this patch.
lib/timber-twig.php 1 patch
Indentation   +341 added lines, -341 removed lines patch added patch discarded remove patch
@@ -2,346 +2,346 @@
 block discarded – undo
2 2
 
3 3
 class TimberTwig {
4 4
 
5
-	public static $dir_name;
6
-
7
-	/**
8
-	 * @codeCoverageIgnore
9
-	 */
10
-	public static function init() {
11
-		new TimberTwig();
12
-	}
13
-
14
-	/**
15
-	 * @codeCoverageIgnore
16
-	 */
17
-	function __construct() {
18
-		add_action( 'timber/twig/filters', array( $this, 'add_timber_filters_deprecated' ) );
19
-		add_action( 'timber/twig/filters', array( $this, 'add_timber_filters' ) );
20
-	}
21
-
22
-	/**
23
-	 * These are all deprecated and will be removed in 0.21.0
24
-	 *
25
-	 * @param Twig_Environment $twig
26
-	 * @deprecated since 0.20.7
27
-	 * @return Twig_Environment
28
-	 */
29
-	function add_timber_filters_deprecated( $twig ) {
30
-		$twig->addFilter( new Twig_SimpleFilter( 'get_src_from_attachment_id', 'twig_get_src_from_attachment_id' ) );
31
-		$twig->addFilter( new Twig_SimpleFilter( 'wp_body_class', array( $this, 'body_class' ) ) );
32
-		$twig->addFilter( new Twig_SimpleFilter( 'twitterify', array( 'TimberHelper', 'twitterify' ) ) );
33
-		$twig->addFilter( new Twig_SimpleFilter( 'twitterfy', array( 'TimberHelper', 'twitterify' ) ) );
34
-		$twig->addFilter( new Twig_SimpleFilter( 'string', function($arr, $glue = ' '){
35
-			return twig_join_filter($arr, $glue);
36
-		} ) );
37
-		return $twig;
38
-	}
39
-
40
-	/**
41
-	 *
42
-	 *
43
-	 * @param Twig_Environment $twig
44
-	 * @return Twig_Environment
45
-	 */
46
-	function add_timber_filters( $twig ) {
47
-		/* image filters */
48
-		$twig->addFilter( new Twig_SimpleFilter( 'resize', array( 'TimberImageHelper', 'resize' ) ) );
49
-		$twig->addFilter( new Twig_SimpleFilter( 'retina', array( 'TimberImageHelper', 'retina_resize' ) ) );
50
-		$twig->addFilter( new Twig_SimpleFilter( 'letterbox', array( 'TimberImageHelper', 'letterbox' ) ) );
51
-		$twig->addFilter( new Twig_SimpleFilter( 'tojpg', array( 'TimberImageHelper', 'img_to_jpg' ) ) );
52
-
53
-		/* debugging filters */
54
-		$twig->addFilter( new Twig_SimpleFilter( 'docs', 'twig_object_docs' ) );
55
-		$twig->addFilter( new Twig_SimpleFilter( 'get_class',  'get_class' ) );
56
-		$twig->addFilter( new Twig_SimpleFilter( 'get_type', 'get_type' ) );
57
-		$twig->addFilter( new Twig_SimpleFilter( 'print_r', function( $arr ) {
58
-					return print_r( $arr, true );
59
-				} ) );
60
-		$twig->addFilter( new Twig_SimpleFilter( 'print_a', function( $arr ) {
61
-					return '<pre>' . self::object_docs( $arr, true ) . '</pre>';
62
-				} ) );
63
-
64
-		/* other filters */
65
-		$twig->addFilter( new Twig_SimpleFilter( 'stripshortcodes', 'strip_shortcodes' ) );
66
-		$twig->addFilter( new Twig_SimpleFilter( 'array', array( $this, 'to_array' ) ) );
67
-		$twig->addFilter( new Twig_SimpleFilter( 'excerpt', 'wp_trim_words' ) );
68
-		$twig->addFilter( new Twig_SimpleFilter( 'function', array( $this, 'exec_function' ) ) );
69
-		$twig->addFilter( new Twig_SimpleFilter( 'pretags', array( $this, 'twig_pretags' ) ) );
70
-		$twig->addFilter( new Twig_SimpleFilter( 'sanitize', 'sanitize_title' ) );
71
-		$twig->addFilter( new Twig_SimpleFilter( 'shortcodes', 'do_shortcode' ) );
72
-		$twig->addFilter( new Twig_SimpleFilter( 'time_ago', array( $this, 'time_ago' ) ) );
73
-		$twig->addFilter( new Twig_SimpleFilter( 'wpautop', 'wpautop' ) );
74
-		$twig->addFilter( new Twig_SimpleFilter( 'list', array( $this, 'add_list_separators' ) ) );
75
-
76
-		$twig->addFilter( new Twig_SimpleFilter( 'relative', function ( $link ) {
77
-					return TimberURLHelper::get_rel_url( $link, true );
78
-				} ) );
79
-
80
-		$twig->addFilter( new Twig_SimpleFilter( 'date', array( $this, 'intl_date' ) ) );
81
-
82
-		$twig->addFilter( new Twig_SimpleFilter( 'truncate', function ( $text, $len ) {
83
-					return TimberHelper::trim_words( $text, $len );
84
-				} ) );
85
-
86
-		/* actions and filters */
87
-		$twig->addFunction( new Twig_SimpleFunction( 'action', function ( $context ) {
88
-					$args = func_get_args();
89
-					array_shift( $args );
90
-					$args[] = $context;
91
-					call_user_func_array( 'do_action', $args );
92
-				}, array( 'needs_context' => true ) ) );
93
-
94
-		$twig->addFilter( new Twig_SimpleFilter( 'apply_filters', function () {
95
-					$args = func_get_args();
96
-					$tag = current( array_splice( $args, 1, 1 ) );
97
-
98
-					return apply_filters_ref_array( $tag, $args );
99
-				} ) );
100
-		$twig->addFunction( new Twig_SimpleFunction( 'function', array( &$this, 'exec_function' ) ) );
101
-		$twig->addFunction( new Twig_SimpleFunction( 'fn', array( &$this, 'exec_function' ) ) );
102
-
103
-		$twig->addFunction( new Twig_SimpleFunction( 'shortcode', 'do_shortcode' ) );
104
-
105
-		/* TimberObjects */
106
-		$twig->addFunction( new Twig_SimpleFunction( 'TimberPost', function ( $pid, $PostClass = 'TimberPost' ) {
107
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
108
-						foreach ( $pid as &$p ) {
109
-							$p = new $PostClass( $p );
110
-						}
111
-						return $pid;
112
-					}
113
-					return new $PostClass( $pid );
114
-				} ) );
115
-		$twig->addFunction( new Twig_SimpleFunction( 'TimberImage', function ( $pid, $ImageClass = 'TimberImage' ) {
116
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
117
-						foreach ( $pid as &$p ) {
118
-							$p = new $ImageClass( $p );
119
-						}
120
-						return $pid;
121
-					}
122
-					return new $ImageClass( $pid );
123
-				} ) );
124
-		$twig->addFunction( new Twig_SimpleFunction( 'TimberTerm', function ( $pid, $TermClass = 'TimberTerm' ) {
125
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
126
-						foreach ( $pid as &$p ) {
127
-							$p = new $TermClass( $p );
128
-						}
129
-						return $pid;
130
-					}
131
-					return new $TermClass( $pid );
132
-				} ) );
133
-		$twig->addFunction( new Twig_SimpleFunction( 'TimberUser', function ( $pid, $UserClass = 'TimberUser' ) {
134
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
135
-						foreach ( $pid as &$p ) {
136
-							$p = new $UserClass( $p );
137
-						}
138
-						return $pid;
139
-					}
140
-					return new $UserClass( $pid );
141
-				} ) );
142
-
143
-		/* TimberObjects Alias */
144
-		$twig->addFunction( new Twig_SimpleFunction( 'Post', function ( $pid, $PostClass = 'TimberPost' ) {
145
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
146
-						foreach ( $pid as &$p ) {
147
-							$p = new $PostClass( $p );
148
-						}
149
-						return $pid;
150
-					}
151
-					return new $PostClass( $pid );
152
-				} ) );
153
-		$twig->addFunction( new Twig_SimpleFunction( 'Image', function ( $pid, $ImageClass = 'TimberImage' ) {
154
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
155
-						foreach ( $pid as &$p ) {
156
-							$p = new $ImageClass( $p );
157
-						}
158
-						return $pid;
159
-					}
160
-					return new $ImageClass( $pid );
161
-				} ) );
162
-		$twig->addFunction( new Twig_SimpleFunction( 'Term', function ( $pid, $TermClass = 'TimberTerm' ) {
163
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
164
-						foreach ( $pid as &$p ) {
165
-							$p = new $TermClass( $p );
166
-						}
167
-						return $pid;
168
-					}
169
-					return new $TermClass( $pid );
170
-				} ) );
171
-		$twig->addFunction( new Twig_SimpleFunction( 'User', function ( $pid, $UserClass = 'TimberUser' ) {
172
-					if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
173
-						foreach ( $pid as &$p ) {
174
-							$p = new $UserClass( $p );
175
-						}
176
-						return $pid;
177
-					}
178
-					return new $UserClass( $pid );
179
-				} ) );
180
-
181
-		/* bloginfo and translate */
182
-		$twig->addFunction( 'bloginfo', new Twig_SimpleFunction( 'bloginfo', function ( $show = '', $filter = 'raw' ) {
183
-					return get_bloginfo( $show, $filter );
184
-				} ) );
185
-		$twig->addFunction( '__', new Twig_SimpleFunction( '__', function ( $text, $domain = 'default' ) {
186
-					return __( $text, $domain );
187
-				} ) );
188
-		/* get_twig is deprecated, use timber/twig */
189
-		$twig = apply_filters( 'get_twig', $twig );
190
-		$twig = apply_filters( 'timber/twig', $twig );
191
-		return $twig;
192
-	}
193
-
194
-	/**
195
-	 *
196
-	 *
197
-	 * @param mixed   $arr
198
-	 * @return array
199
-	 */
200
-	function to_array( $arr ) {
201
-		if ( is_array( $arr ) ) {
202
-			return $arr;
203
-		}
204
-		$arr = array( $arr );
205
-		return $arr;
206
-	}
207
-
208
-	/**
209
-	 *
210
-	 *
211
-	 * @param string  $function_name
212
-	 * @return mixed
213
-	 */
214
-	function exec_function( $function_name ) {
215
-		$args = func_get_args();
216
-		array_shift( $args );
217
-		if ( is_string($function_name) ) {
218
-			$function_name = trim( $function_name );
219
-		}
220
-		return call_user_func_array( $function_name, ( $args ) );
221
-	}
222
-
223
-	/**
224
-	 *
225
-	 *
226
-	 * @param string  $content
227
-	 * @return string
228
-	 */
229
-	function twig_pretags( $content ) {
230
-		return preg_replace_callback( '|<pre.*>(.*)</pre|isU', array( &$this, 'convert_pre_entities' ), $content );
231
-	}
232
-
233
-	/**
234
-	 *
235
-	 *
236
-	 * @param array   $matches
237
-	 * @return string
238
-	 */
239
-	function convert_pre_entities( $matches ) {
240
-		return str_replace( $matches[1], htmlentities( $matches[1] ), $matches[0] );
241
-	}
242
-
243
-	/**
244
-	 * @param mixed   $body_classes
245
-	 * @deprecated 0.20.7
246
-	 * @return string
247
-	 */
248
-	function body_class( $body_classes ) {
249
-		ob_start();
250
-		if ( is_array( $body_classes ) ) {
251
-			$body_classes = explode( ' ', $body_classes );
252
-		}
253
-		body_class( $body_classes );
254
-		$return = ob_get_contents();
255
-		ob_end_clean();
256
-		return $return;
257
-	}
258
-
259
-	/**
260
-	 *
261
-	 *
262
-	 * @param string  $date
263
-	 * @param string  $format (optional)
264
-	 * @return string
265
-	 */
266
-	function intl_date( $date, $format = null ) {
267
-		if ( $format === null ) {
268
-			$format = get_option( 'date_format' );
269
-		}
270
-
271
-		if ( $date instanceof DateTime ) {
272
-			$timestamp = $date->getTimestamp() + $date->getOffset();
273
-		} else if (is_numeric( $date ) && strtotime( $date ) === false ) {
274
-			$timestamp = intval( $date );
275
-		} else {
276
-			$timestamp = strtotime( $date );
277
-		}
278
-
279
-		return date_i18n( $format, $timestamp );
280
-	}
281
-
282
-	//debug
283
-
284
-	/**
285
-	 *
286
-	 *
287
-	 * @param mixed   $obj
288
-	 * @param bool    $methods
289
-	 * @deprecated since 0.20.7
290
-	 * @return string
291
-	 */
292
-	function object_docs( $obj, $methods = true ) {
293
-		$class = get_class( $obj );
294
-		$properties = (array)$obj;
295
-		if ( $methods ) {
296
-			/** @var array $methods */
297
-			$methods = $obj->get_method_values();
298
-		}
299
-		$rets = array_merge( $properties, $methods );
300
-		ksort( $rets );
301
-		$str = print_r( $rets, true );
302
-		$str = str_replace( 'Array', $class . ' Object', $str );
303
-		return $str;
304
-	}
305
-
306
-	/**
307
-	 * @param int|string $from
308
-	 * @param int|string $to
309
-	 * @param string $format_past
310
-	 * @param string $format_future
311
-	 * @return string
312
-	 */
313
-	function time_ago( $from, $to = null, $format_past = '%s ago', $format_future = '%s from now' ) {
314
-		$to = $to === null ? time() : $to;
315
-		$to = is_int( $to ) ? $to : strtotime( $to );
316
-		$from = is_int( $from ) ? $from : strtotime( $from );
317
-
318
-		if ( $from < $to ) {
319
-			return sprintf( $format_past, human_time_diff( $from, $to ) );
320
-		} else {
321
-			return sprintf( $format_future, human_time_diff( $to, $from ) );
322
-		}
323
-	}
324
-
325
-	/**
326
-	 * @param array $arr
327
-	 * @param string $first_delimiter
328
-	 * @param string $second_delimiter
329
-	 * @return string
330
-	 */
331
-	function add_list_separators( $arr, $first_delimiter = ',', $second_delimiter = 'and' ) {
332
-		$length = count( $arr );
333
-		$list = '';
334
-		foreach( $arr as $index => $item ) {
335
-			if ( $index < $length - 2 ) {
336
-				$delimiter = $first_delimiter.' ';
337
-			} elseif ( $index == $length - 2 ) {
338
-				$delimiter = ' '.$second_delimiter.' ';
339
-			} else {
340
-				$delimiter = '';
341
-			}
342
-			$list = $list.$item.$delimiter;
343
-		}
344
-		return $list;
345
-	}
5
+    public static $dir_name;
6
+
7
+    /**
8
+     * @codeCoverageIgnore
9
+     */
10
+    public static function init() {
11
+        new TimberTwig();
12
+    }
13
+
14
+    /**
15
+     * @codeCoverageIgnore
16
+     */
17
+    function __construct() {
18
+        add_action( 'timber/twig/filters', array( $this, 'add_timber_filters_deprecated' ) );
19
+        add_action( 'timber/twig/filters', array( $this, 'add_timber_filters' ) );
20
+    }
21
+
22
+    /**
23
+     * These are all deprecated and will be removed in 0.21.0
24
+     *
25
+     * @param Twig_Environment $twig
26
+     * @deprecated since 0.20.7
27
+     * @return Twig_Environment
28
+     */
29
+    function add_timber_filters_deprecated( $twig ) {
30
+        $twig->addFilter( new Twig_SimpleFilter( 'get_src_from_attachment_id', 'twig_get_src_from_attachment_id' ) );
31
+        $twig->addFilter( new Twig_SimpleFilter( 'wp_body_class', array( $this, 'body_class' ) ) );
32
+        $twig->addFilter( new Twig_SimpleFilter( 'twitterify', array( 'TimberHelper', 'twitterify' ) ) );
33
+        $twig->addFilter( new Twig_SimpleFilter( 'twitterfy', array( 'TimberHelper', 'twitterify' ) ) );
34
+        $twig->addFilter( new Twig_SimpleFilter( 'string', function($arr, $glue = ' '){
35
+            return twig_join_filter($arr, $glue);
36
+        } ) );
37
+        return $twig;
38
+    }
39
+
40
+    /**
41
+     *
42
+     *
43
+     * @param Twig_Environment $twig
44
+     * @return Twig_Environment
45
+     */
46
+    function add_timber_filters( $twig ) {
47
+        /* image filters */
48
+        $twig->addFilter( new Twig_SimpleFilter( 'resize', array( 'TimberImageHelper', 'resize' ) ) );
49
+        $twig->addFilter( new Twig_SimpleFilter( 'retina', array( 'TimberImageHelper', 'retina_resize' ) ) );
50
+        $twig->addFilter( new Twig_SimpleFilter( 'letterbox', array( 'TimberImageHelper', 'letterbox' ) ) );
51
+        $twig->addFilter( new Twig_SimpleFilter( 'tojpg', array( 'TimberImageHelper', 'img_to_jpg' ) ) );
52
+
53
+        /* debugging filters */
54
+        $twig->addFilter( new Twig_SimpleFilter( 'docs', 'twig_object_docs' ) );
55
+        $twig->addFilter( new Twig_SimpleFilter( 'get_class',  'get_class' ) );
56
+        $twig->addFilter( new Twig_SimpleFilter( 'get_type', 'get_type' ) );
57
+        $twig->addFilter( new Twig_SimpleFilter( 'print_r', function( $arr ) {
58
+                    return print_r( $arr, true );
59
+                } ) );
60
+        $twig->addFilter( new Twig_SimpleFilter( 'print_a', function( $arr ) {
61
+                    return '<pre>' . self::object_docs( $arr, true ) . '</pre>';
62
+                } ) );
63
+
64
+        /* other filters */
65
+        $twig->addFilter( new Twig_SimpleFilter( 'stripshortcodes', 'strip_shortcodes' ) );
66
+        $twig->addFilter( new Twig_SimpleFilter( 'array', array( $this, 'to_array' ) ) );
67
+        $twig->addFilter( new Twig_SimpleFilter( 'excerpt', 'wp_trim_words' ) );
68
+        $twig->addFilter( new Twig_SimpleFilter( 'function', array( $this, 'exec_function' ) ) );
69
+        $twig->addFilter( new Twig_SimpleFilter( 'pretags', array( $this, 'twig_pretags' ) ) );
70
+        $twig->addFilter( new Twig_SimpleFilter( 'sanitize', 'sanitize_title' ) );
71
+        $twig->addFilter( new Twig_SimpleFilter( 'shortcodes', 'do_shortcode' ) );
72
+        $twig->addFilter( new Twig_SimpleFilter( 'time_ago', array( $this, 'time_ago' ) ) );
73
+        $twig->addFilter( new Twig_SimpleFilter( 'wpautop', 'wpautop' ) );
74
+        $twig->addFilter( new Twig_SimpleFilter( 'list', array( $this, 'add_list_separators' ) ) );
75
+
76
+        $twig->addFilter( new Twig_SimpleFilter( 'relative', function ( $link ) {
77
+                    return TimberURLHelper::get_rel_url( $link, true );
78
+                } ) );
79
+
80
+        $twig->addFilter( new Twig_SimpleFilter( 'date', array( $this, 'intl_date' ) ) );
81
+
82
+        $twig->addFilter( new Twig_SimpleFilter( 'truncate', function ( $text, $len ) {
83
+                    return TimberHelper::trim_words( $text, $len );
84
+                } ) );
85
+
86
+        /* actions and filters */
87
+        $twig->addFunction( new Twig_SimpleFunction( 'action', function ( $context ) {
88
+                    $args = func_get_args();
89
+                    array_shift( $args );
90
+                    $args[] = $context;
91
+                    call_user_func_array( 'do_action', $args );
92
+                }, array( 'needs_context' => true ) ) );
93
+
94
+        $twig->addFilter( new Twig_SimpleFilter( 'apply_filters', function () {
95
+                    $args = func_get_args();
96
+                    $tag = current( array_splice( $args, 1, 1 ) );
97
+
98
+                    return apply_filters_ref_array( $tag, $args );
99
+                } ) );
100
+        $twig->addFunction( new Twig_SimpleFunction( 'function', array( &$this, 'exec_function' ) ) );
101
+        $twig->addFunction( new Twig_SimpleFunction( 'fn', array( &$this, 'exec_function' ) ) );
102
+
103
+        $twig->addFunction( new Twig_SimpleFunction( 'shortcode', 'do_shortcode' ) );
104
+
105
+        /* TimberObjects */
106
+        $twig->addFunction( new Twig_SimpleFunction( 'TimberPost', function ( $pid, $PostClass = 'TimberPost' ) {
107
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
108
+                        foreach ( $pid as &$p ) {
109
+                            $p = new $PostClass( $p );
110
+                        }
111
+                        return $pid;
112
+                    }
113
+                    return new $PostClass( $pid );
114
+                } ) );
115
+        $twig->addFunction( new Twig_SimpleFunction( 'TimberImage', function ( $pid, $ImageClass = 'TimberImage' ) {
116
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
117
+                        foreach ( $pid as &$p ) {
118
+                            $p = new $ImageClass( $p );
119
+                        }
120
+                        return $pid;
121
+                    }
122
+                    return new $ImageClass( $pid );
123
+                } ) );
124
+        $twig->addFunction( new Twig_SimpleFunction( 'TimberTerm', function ( $pid, $TermClass = 'TimberTerm' ) {
125
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
126
+                        foreach ( $pid as &$p ) {
127
+                            $p = new $TermClass( $p );
128
+                        }
129
+                        return $pid;
130
+                    }
131
+                    return new $TermClass( $pid );
132
+                } ) );
133
+        $twig->addFunction( new Twig_SimpleFunction( 'TimberUser', function ( $pid, $UserClass = 'TimberUser' ) {
134
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
135
+                        foreach ( $pid as &$p ) {
136
+                            $p = new $UserClass( $p );
137
+                        }
138
+                        return $pid;
139
+                    }
140
+                    return new $UserClass( $pid );
141
+                } ) );
142
+
143
+        /* TimberObjects Alias */
144
+        $twig->addFunction( new Twig_SimpleFunction( 'Post', function ( $pid, $PostClass = 'TimberPost' ) {
145
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
146
+                        foreach ( $pid as &$p ) {
147
+                            $p = new $PostClass( $p );
148
+                        }
149
+                        return $pid;
150
+                    }
151
+                    return new $PostClass( $pid );
152
+                } ) );
153
+        $twig->addFunction( new Twig_SimpleFunction( 'Image', function ( $pid, $ImageClass = 'TimberImage' ) {
154
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
155
+                        foreach ( $pid as &$p ) {
156
+                            $p = new $ImageClass( $p );
157
+                        }
158
+                        return $pid;
159
+                    }
160
+                    return new $ImageClass( $pid );
161
+                } ) );
162
+        $twig->addFunction( new Twig_SimpleFunction( 'Term', function ( $pid, $TermClass = 'TimberTerm' ) {
163
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
164
+                        foreach ( $pid as &$p ) {
165
+                            $p = new $TermClass( $p );
166
+                        }
167
+                        return $pid;
168
+                    }
169
+                    return new $TermClass( $pid );
170
+                } ) );
171
+        $twig->addFunction( new Twig_SimpleFunction( 'User', function ( $pid, $UserClass = 'TimberUser' ) {
172
+                    if ( is_array( $pid ) && !TimberHelper::is_array_assoc( $pid ) ) {
173
+                        foreach ( $pid as &$p ) {
174
+                            $p = new $UserClass( $p );
175
+                        }
176
+                        return $pid;
177
+                    }
178
+                    return new $UserClass( $pid );
179
+                } ) );
180
+
181
+        /* bloginfo and translate */
182
+        $twig->addFunction( 'bloginfo', new Twig_SimpleFunction( 'bloginfo', function ( $show = '', $filter = 'raw' ) {
183
+                    return get_bloginfo( $show, $filter );
184
+                } ) );
185
+        $twig->addFunction( '__', new Twig_SimpleFunction( '__', function ( $text, $domain = 'default' ) {
186
+                    return __( $text, $domain );
187
+                } ) );
188
+        /* get_twig is deprecated, use timber/twig */
189
+        $twig = apply_filters( 'get_twig', $twig );
190
+        $twig = apply_filters( 'timber/twig', $twig );
191
+        return $twig;
192
+    }
193
+
194
+    /**
195
+     *
196
+     *
197
+     * @param mixed   $arr
198
+     * @return array
199
+     */
200
+    function to_array( $arr ) {
201
+        if ( is_array( $arr ) ) {
202
+            return $arr;
203
+        }
204
+        $arr = array( $arr );
205
+        return $arr;
206
+    }
207
+
208
+    /**
209
+     *
210
+     *
211
+     * @param string  $function_name
212
+     * @return mixed
213
+     */
214
+    function exec_function( $function_name ) {
215
+        $args = func_get_args();
216
+        array_shift( $args );
217
+        if ( is_string($function_name) ) {
218
+            $function_name = trim( $function_name );
219
+        }
220
+        return call_user_func_array( $function_name, ( $args ) );
221
+    }
222
+
223
+    /**
224
+     *
225
+     *
226
+     * @param string  $content
227
+     * @return string
228
+     */
229
+    function twig_pretags( $content ) {
230
+        return preg_replace_callback( '|<pre.*>(.*)</pre|isU', array( &$this, 'convert_pre_entities' ), $content );
231
+    }
232
+
233
+    /**
234
+     *
235
+     *
236
+     * @param array   $matches
237
+     * @return string
238
+     */
239
+    function convert_pre_entities( $matches ) {
240
+        return str_replace( $matches[1], htmlentities( $matches[1] ), $matches[0] );
241
+    }
242
+
243
+    /**
244
+     * @param mixed   $body_classes
245
+     * @deprecated 0.20.7
246
+     * @return string
247
+     */
248
+    function body_class( $body_classes ) {
249
+        ob_start();
250
+        if ( is_array( $body_classes ) ) {
251
+            $body_classes = explode( ' ', $body_classes );
252
+        }
253
+        body_class( $body_classes );
254
+        $return = ob_get_contents();
255
+        ob_end_clean();
256
+        return $return;
257
+    }
258
+
259
+    /**
260
+     *
261
+     *
262
+     * @param string  $date
263
+     * @param string  $format (optional)
264
+     * @return string
265
+     */
266
+    function intl_date( $date, $format = null ) {
267
+        if ( $format === null ) {
268
+            $format = get_option( 'date_format' );
269
+        }
270
+
271
+        if ( $date instanceof DateTime ) {
272
+            $timestamp = $date->getTimestamp() + $date->getOffset();
273
+        } else if (is_numeric( $date ) && strtotime( $date ) === false ) {
274
+            $timestamp = intval( $date );
275
+        } else {
276
+            $timestamp = strtotime( $date );
277
+        }
278
+
279
+        return date_i18n( $format, $timestamp );
280
+    }
281
+
282
+    //debug
283
+
284
+    /**
285
+     *
286
+     *
287
+     * @param mixed   $obj
288
+     * @param bool    $methods
289
+     * @deprecated since 0.20.7
290
+     * @return string
291
+     */
292
+    function object_docs( $obj, $methods = true ) {
293
+        $class = get_class( $obj );
294
+        $properties = (array)$obj;
295
+        if ( $methods ) {
296
+            /** @var array $methods */
297
+            $methods = $obj->get_method_values();
298
+        }
299
+        $rets = array_merge( $properties, $methods );
300
+        ksort( $rets );
301
+        $str = print_r( $rets, true );
302
+        $str = str_replace( 'Array', $class . ' Object', $str );
303
+        return $str;
304
+    }
305
+
306
+    /**
307
+     * @param int|string $from
308
+     * @param int|string $to
309
+     * @param string $format_past
310
+     * @param string $format_future
311
+     * @return string
312
+     */
313
+    function time_ago( $from, $to = null, $format_past = '%s ago', $format_future = '%s from now' ) {
314
+        $to = $to === null ? time() : $to;
315
+        $to = is_int( $to ) ? $to : strtotime( $to );
316
+        $from = is_int( $from ) ? $from : strtotime( $from );
317
+
318
+        if ( $from < $to ) {
319
+            return sprintf( $format_past, human_time_diff( $from, $to ) );
320
+        } else {
321
+            return sprintf( $format_future, human_time_diff( $to, $from ) );
322
+        }
323
+    }
324
+
325
+    /**
326
+     * @param array $arr
327
+     * @param string $first_delimiter
328
+     * @param string $second_delimiter
329
+     * @return string
330
+     */
331
+    function add_list_separators( $arr, $first_delimiter = ',', $second_delimiter = 'and' ) {
332
+        $length = count( $arr );
333
+        $list = '';
334
+        foreach( $arr as $index => $item ) {
335
+            if ( $index < $length - 2 ) {
336
+                $delimiter = $first_delimiter.' ';
337
+            } elseif ( $index == $length - 2 ) {
338
+                $delimiter = ' '.$second_delimiter.' ';
339
+            } else {
340
+                $delimiter = '';
341
+            }
342
+            $list = $list.$item.$delimiter;
343
+        }
344
+        return $list;
345
+    }
346 346
 
347 347
 }
Please login to merge, or discard this patch.
lib/timber-admin.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -6,21 +6,21 @@
 block discarded – undo
6 6
         return add_filter( 'plugin_row_meta', array( __CLASS__, 'meta_links' ), 10, 2 );
7 7
     }
8 8
 
9
-	/**
10
-	 * @param array   $links
11
-	 * @param string  $file
12
-	 * @return array
13
-	 */
14
-	public static function meta_links( $links, $file ) {
15
-		if ( strstr( $file, '/timber.php' ) ) {
16
-			unset($links[2]);
17
-			$links[] = '<a href="/wp-admin/plugin-install.php?tab=plugin-information&amp;plugin=timber-library&amp;TB_iframe=true&amp;width=600&amp;height=550" class="thickbox" aria-label="More information about Timber" data-title="Timber">View details</a>';
18
-			$links[] = '<a href="http://upstatement.com/timber" target="_blank">Homepage</a>';
19
-			$links[] = '<a href="https://github.com/jarednova/timber/wiki" target="_blank">Documentation</a>';
20
-			$links[] = '<a href="https://github.com/jarednova/timber/wiki/getting-started" target="_blank">Starter Guide</a>';
21
-			return $links;
22
-		}
23
-		return $links;
24
-	}
9
+    /**
10
+     * @param array   $links
11
+     * @param string  $file
12
+     * @return array
13
+     */
14
+    public static function meta_links( $links, $file ) {
15
+        if ( strstr( $file, '/timber.php' ) ) {
16
+            unset($links[2]);
17
+            $links[] = '<a href="/wp-admin/plugin-install.php?tab=plugin-information&amp;plugin=timber-library&amp;TB_iframe=true&amp;width=600&amp;height=550" class="thickbox" aria-label="More information about Timber" data-title="Timber">View details</a>';
18
+            $links[] = '<a href="http://upstatement.com/timber" target="_blank">Homepage</a>';
19
+            $links[] = '<a href="https://github.com/jarednova/timber/wiki" target="_blank">Documentation</a>';
20
+            $links[] = '<a href="https://github.com/jarednova/timber/wiki/getting-started" target="_blank">Starter Guide</a>';
21
+            return $links;
22
+        }
23
+        return $links;
24
+    }
25 25
 
26 26
 }
Please login to merge, or discard this patch.
lib/timber-image.php 1 patch
Indentation   +483 added lines, -483 removed lines patch added patch discarded remove patch
@@ -39,488 +39,488 @@
 block discarded – undo
39 39
  */
40 40
 class TimberImage extends TimberPost implements TimberCoreInterface {
41 41
 
42
-	protected $_can_edit;
43
-	protected $_dimensions;
44
-	public $abs_url;
45
-	/**
46
-	 * @var string $object_type what does this class represent in WordPress terms?
47
-	 */
48
-	public $object_type = 'image';
49
-	/**
50
-	 * @var string $representation what does this class represent in WordPress terms?
51
-	 */
52
-	public static $representation = 'image';
53
-	/**
54
-	 * @var array of supported relative file types
55
-	 */
56
-	private $file_types = array('jpg', 'jpeg', 'png', 'svg', 'bmp', 'ico', 'gif', 'tiff', 'pdf');
57
-	/**
58
-	 * @api
59
-	 * @var string $file_loc the location of the image file in the filesystem (ex: `/var/www/htdocs/wp-content/uploads/2015/08/my-pic.jpg`)
60
-	 */
61
-	public $file_loc;
62
-	public $file;
63
-	/**
64
-	 * @api
65
-	 * @var integer the ID of the image (which is a WP_Post)
66
-	 */
67
-	public $id;
68
-	public $sizes = array();
69
-	/**
70
-	 * @api
71
-	 * @var string $caption the string stored in the WordPress database
72
-	 */
73
-	public $caption;
74
-	/**
75
-	 * @var $_wp_attached_file the file as stored in the WordPress database
76
-	 */
77
-	protected $_wp_attached_file;
78
-
79
-	/**
80
-	 * Creates a new TimberImage object
81
-	 * @example
82
-	 * ```php
83
-	 * // You can pass it an ID number
84
-	 * $myImage = new TimberImage(552);
85
-	 *
86
-	 * //Or send it a URL to an image
87
-	 * $myImage = new TimberImage('http://google.com/logo.jpg');
88
-	 * ```
89
-	 * @param int|string $iid
90
-	 */
91
-	public function __construct($iid) {
92
-		$this->init($iid);
93
-	}
94
-
95
-	/**
96
-	 * @return string the src of the file
97
-	 */
98
-	public function __toString() {
99
-		if ( $this->get_src() ) {
100
-			return $this->get_src();
101
-		}
102
-		return '';
103
-	}
104
-
105
-	/**
106
-	 * Get a PHP array with pathinfo() info from the file
107
-	 * @return array
108
-	 */
109
-	function get_pathinfo() {
110
-		return pathinfo($this->file);
111
-	}
112
-
113
-	/**
114
-	 * @internal
115
-	 * @param string $dim
116
-	 * @return array|int
117
-	 */
118
-	protected function get_dimensions($dim = null) {
119
-		if ( isset($this->_dimensions) ) {
120
-			return $this->get_dimensions_loaded($dim);
121
-		}
122
-		if ( file_exists($this->file_loc) && filesize($this->file_loc) ) {
123
-			list($width, $height) = getimagesize($this->file_loc);
124
-			$this->_dimensions = array();
125
-			$this->_dimensions[0] = $width;
126
-			$this->_dimensions[1] = $height;
127
-			return $this->get_dimensions_loaded($dim);
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * @internal
133
-	 * @param string|null $dim
134
-	 * @return array|int
135
-	 */
136
-	protected function get_dimensions_loaded($dim) {
137
-		if ( $dim === null ) {
138
-			return $this->_dimensions;
139
-		}
140
-		if ( $dim == 'w' || $dim == 'width' ) {
141
-			return $this->_dimensions[0];
142
-		}
143
-		if ( $dim == 'h' || $dim == 'height' ) {
144
-			return $this->_dimensions[1];
145
-		}
146
-		return null;
147
-	}
148
-
149
-	/**
150
-	 * @internal
151
-	 * @param  int $iid the id number of the image in the WP database
152
-	 */
153
-	protected function get_image_info( $iid ) {
154
-		$image_info = $iid;
155
-		if (is_numeric($iid)) {
156
-			$image_info = wp_get_attachment_metadata($iid);
157
-			if (!is_array($image_info)) {
158
-				$image_info = array();
159
-			}
160
-			$image_custom = get_post_custom($iid);
161
-			$basic = get_post($iid);
162
-			if ($basic) {
163
-				if (isset($basic->post_excerpt)) {
164
-					$this->caption = $basic->post_excerpt;
165
-				}
166
-				$image_custom = array_merge($image_custom, get_object_vars($basic));
167
-			}
168
-			return array_merge($image_info, $image_custom);
169
-		}
170
-		if (is_array($image_info) && isset($image_info['image'])) {
171
-			return $image_info['image'];
172
-		}
173
-		if (is_object($image_info)) {
174
-		   return get_object_vars($image_info);
175
-		}
176
-		return $iid;
177
-	}
178
-
179
-	/**
180
-	 * @internal
181
-	 * @param  string $url for evaluation
182
-	 * @return string with http/https corrected depending on what's appropriate for server
183
-	 */
184
-	protected static function _maybe_secure_url($url) {
185
-		if ( is_ssl() && strpos($url, 'https') !== 0 && strpos($url, 'http') === 0 ) {
186
-			$url = 'https' . substr($url, strlen('http'));
187
-		}
188
-		return $url;
189
-	}
190
-
191
-	public static function wp_upload_dir() {
192
-		static $wp_upload_dir = false;
193
-
194
-		if ( !$wp_upload_dir ) {
195
-			$wp_upload_dir = wp_upload_dir();
196
-		}
197
-
198
-		return $wp_upload_dir;
199
-	}
200
-
201
-	/**
202
-	 * @internal
203
-	 * @param int $iid
204
-	 */
205
-	function init( $iid = false ) {
206
-		if ( !is_numeric( $iid ) && is_string( $iid ) ) {
207
-			if (strstr($iid, '://')) {
208
-				$this->init_with_url($iid);
209
-				return;
210
-			}
211
-			if ( strstr($iid, ABSPATH) ) {
212
-				$this->init_with_file_path($iid);
213
-				return;
214
-			}
215
-
216
-			$relative = false;
217
-			$iid_lower = strtolower($iid);
218
-			foreach( $this->file_types as $type ) { if( strstr( $iid_lower, $type ) ) { $relative = true; break; } };
219
-			if ( $relative ) {
220
-				$this->init_with_relative_path( $iid );
221
-				return;
222
-			}
223
-		} else if ( $iid instanceof WP_Post ) {
224
-			$ref = new ReflectionClass($this);
225
-			$post = $ref->getParentClass()->newInstance($iid->ID);
226
-			if (isset($post->_thumbnail_id) && $post->_thumbnail_id) {
227
-				return $this->init((int) $post->_thumbnail_id);
228
-			}
229
-			return $this->init($iid->ID);
230
-		} else if ( $iid instanceof TimberPost ) {
231
-			/**
232
-			 * This will catch TimberPost and any post classes that extend TimberPost,
233
-			 * see http://php.net/manual/en/internals2.opcodes.instanceof.php#109108
234
-			 * and https://github.com/jarednova/timber/wiki/Extending-Timber
235
-			 */
236
-			$iid = (int) $iid->_thumbnail_id;
237
-		}
238
-
239
-		$image_info = $this->get_image_info($iid);
240
-
241
-		$this->import($image_info);
242
-		$basedir = self::wp_upload_dir();
243
-		$basedir = $basedir['basedir'];
244
-		if ( isset($this->file) ) {
245
-			$this->file_loc = $basedir . DIRECTORY_SEPARATOR . $this->file;
246
-		} else if ( isset($this->_wp_attached_file) ) {
247
-			$this->file = reset($this->_wp_attached_file);
248
-			$this->file_loc = $basedir . DIRECTORY_SEPARATOR . $this->file;
249
-		}
250
-		if ( isset($image_info['id']) ) {
251
-			$this->ID = $image_info['id'];
252
-		} else if ( is_numeric($iid) ) {
253
-			$this->ID = $iid;
254
-		}
255
-		if ( isset($this->ID) ) {
256
-			$custom = get_post_custom($this->ID);
257
-			foreach ($custom as $key => $value) {
258
-				$this->$key = $value[0];
259
-			}
260
-			$this->id = $this->ID;
261
-		} else {
262
-			if ( is_array($iid) || is_object($iid) ) {
263
-				TimberHelper::error_log('Not able to init in TimberImage with iid=');
264
-				TimberHelper::error_log($iid);
265
-			} else {
266
-				TimberHelper::error_log('Not able to init in TimberImage with iid=' . $iid);
267
-			}
268
-		}
269
-	}
270
-
271
-	/**
272
-	 * @internal
273
-	 * @param string $relative_path
274
-	 */
275
-	protected function init_with_relative_path( $relative_path ) {
276
-		$this->abs_url = home_url( $relative_path );
277
-		$file_path = TimberURLHelper::get_full_path( $relative_path );
278
-		$this->file_loc = $file_path;
279
-		$this->file = $file_path;
280
-	}
281
-
282
-	/**
283
-	 * @internal
284
-	 * @param string $file_path
285
-	 */
286
-	protected function init_with_file_path( $file_path ) {
287
-		$url = TimberURLHelper::file_system_to_url( $file_path );
288
-		$this->abs_url = $url;
289
-		$this->file_loc = $file_path;
290
-		$this->file = $file_path;
291
-	}
292
-
293
-	/**
294
-	 * @internal
295
-	 * @param string $url
296
-	 */
297
-	protected function init_with_url($url) {
298
-		$this->abs_url = $url;
299
-		if ( TimberURLHelper::is_local($url) ) {
300
-			$this->file = ABSPATH . TimberURLHelper::get_rel_url($url);
301
-			$this->file_loc = ABSPATH . TimberURLHelper::get_rel_url($url);
302
-		}
303
-	}
304
-
305
-	/**
306
-	 * @api
307
-	 * @example
308
-	 * ```twig
309
-	 * <img src="{{ image.src }}" alt="{{ image.alt }}" />
310
-	 * ```
311
-	 * ```html
312
-	 * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" alt="W3 Checker told me to add alt text, so I am" />
313
-	 * ```
314
-	 * @return string alt text stored in WordPress
315
-	 */
316
-	public function alt() {
317
-		$alt = trim(strip_tags(get_post_meta($this->ID, '_wp_attachment_image_alt', true)));
318
-		return $alt;
319
-	}
320
-
321
-	/**
322
-	 * @api
323
-	 * @example
324
-	 * ```twig
325
-	 * {% if post.thumbnail.aspect < 1 %}
326
-	 *     {# handle vertical image #}
327
-	 *     <img src="{{ post.thumbnail.src|resize(300, 500) }}" alt="A basketball player" />
328
-	 * {% else %}
329
-	 * 	   <img src="{{ post.thumbnail.src|resize(500) }}" alt="A sumo wrestler" />
330
-	 * {% endif %}
331
-	 * ```
332
-	 * @return float
333
-	 */
334
-	public function aspect() {
335
-		$w = intval($this->width());
336
-		$h = intval($this->height());
337
-		return $w / $h;
338
-	}
339
-
340
-	/**
341
-	 * @api
342
-	 * @example
343
-	 * ```twig
344
-	 * <img src="{{ image.src }}" height="{{ image.height }}" />
345
-	 * ```
346
-	 * ```html
347
-	 * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" height="900" />
348
-	 * ```
349
-	 * @return int
350
-	 */
351
-	public function height() {
352
-		return $this->get_dimensions('height');
353
-	}
354
-
355
-	/**
356
-	 * Returns the link to an image attachment's Permalink page (NOT the link for the image itself!!)
357
-	 * @api
358
-	 * @example
359
-	 * ```twig
360
-	 * <a href="{{ image.link }}"><img src="{{ image.src }} "/></a>
361
-	 * ```
362
-	 * ```html
363
-	 * <a href="http://example.org/my-cool-picture"><img src="http://example.org/wp-content/uploads/2015/whatever.jpg"/></a>
364
-	 * ```
365
-	 */
366
-	public function link() {
367
-		if ( strlen($this->abs_url) ) {
368
-			return $this->abs_url;
369
-		}
370
-		return get_permalink($this->ID);
371
-	}
372
-
373
-	/**
374
-	 * @api
375
-	 * @return bool|TimberPost
376
-	 */
377
-	public function parent() {
378
-		if ( !$this->post_parent ) {
379
-			return false;
380
-		}
381
-		return new $this->PostClass($this->post_parent);
382
-	}
383
-
384
-	/**
385
-	 * @api
386
-	 * @example
387
-	 * ```twig
388
-	 * <img src="{{ image.path }}" />
389
-	 * ```
390
-	 * ```html
391
-	 * <img src="/wp-content/uploads/2015/08/pic.jpg" />
392
-	 * ```
393
-	 * @return  string the /relative/path/to/the/file
394
-	 */
395
-	public function path() {
396
-		return TimberURLHelper::get_rel_path($this->src());
397
-	}
398
-
399
-	/**
400
-	 * @param string $size a size known to WordPress (like "medium")
401
-	 * @api
402
-	 * @example
403
-	 * ```twig
404
-	 * <h1>{{post.title}}</h1>
405
-	 * <img src="{{post.thumbnail.src}}" />
406
-	 * ```
407
-	 * ```html
408
-	 * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" />
409
-	 * ```
410
-	 * @return bool|string
411
-	 */
412
-	public function src($size = '') {
413
-		if ( isset($this->abs_url) ) {
414
-			return $this->_maybe_secure_url($this->abs_url);
415
-		}
416
-
417
-		if ( $size && is_string($size) && isset($this->sizes[$size]) ) {
418
-			$image = image_downsize($this->ID, $size);
419
-			return $this->_maybe_secure_url(reset($image));
420
-		}
421
-
422
-		if ( !isset($this->file) && isset($this->_wp_attached_file) ) {
423
-			$this->file = $this->_wp_attached_file;
424
-		}
425
-
426
-		if ( !isset($this->file) ) {
427
-			return false;
428
-		}
429
-
430
-		$dir = self::wp_upload_dir();
431
-		$base = $dir['baseurl'];
432
-
433
-		$src = trailingslashit($this->_maybe_secure_url($base)) . $this->file;
434
-		$src = apply_filters('timber/image/src', $src, $this->ID);
435
-		return apply_filters('timber_image_src', $src, $this->ID);
436
-	}
437
-
438
-	/**
439
-	 * @deprecated use src() instead
440
-	 * @return string
441
-	 */
442
-	function url() {
443
-		return $this->get_src();
444
-	}
445
-
446
-	/**
447
-	 * @api
448
-	 * @example
449
-	 * ```twig
450
-	 * <img src="{{ image.src }}" width="{{ image.width }}" />
451
-	 * ```
452
-	 * ```html
453
-	 * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" width="1600" />
454
-	 * ```
455
-	 * @return int
456
-	 */
457
-	public function width() {
458
-		return $this->get_dimensions('width');
459
-	}
460
-
461
-
462
-	/**
463
-	 * @deprecated 0.21.9 use TimberImage::width() instead
464
-	 * @internal
465
-	 * @return int
466
-	 */
467
-	function get_width() {
468
-		return $this->width();
469
-	}
470
-
471
-	/**
472
-	 * @deprecated 0.21.9 use TimberImage::height() instead
473
-	 * @internal
474
-	 * @return int
475
-	 */
476
-	function get_height() {
477
-		return $this->height();
478
-	}
479
-
480
-	/**
481
-	 * @deprecated 0.21.9 use TimberImage::src
482
-	 * @internal
483
-	 * @param string $size
484
-	 * @return bool|string
485
-	 */
486
-	function get_src( $size = '' ) {
487
-		return $this->src( $size );
488
-	}
489
-
490
-	/**
491
-	 * @deprecated 0.21.9 use TimberImage::path()
492
-	 * @internal
493
-	 * @return string
494
-	 */
495
-	function get_path() {
496
-		return $this->link();
497
-	}
498
-
499
-	/**
500
-	 * @deprecated use src() instead
501
-	 * @return string
502
-	 */
503
-	function get_url() {
504
-		return $this->get_src();
505
-	}
506
-
507
-	/**
508
-	 * @internal
509
-	 * @deprecated 0.21.8
510
-	 * @return bool|TimberPost
511
-	 */
512
-	function get_parent() {
513
-		return $this->parent();
514
-	}
515
-
516
-	/**
517
-	 * @internal
518
-	 * @deprecated 0.21.9
519
-	 * @see TimberImage::alt
520
-	 * @return string
521
-	 */
522
-	function get_alt() {
523
-		return $this->alt();
524
-	}
42
+    protected $_can_edit;
43
+    protected $_dimensions;
44
+    public $abs_url;
45
+    /**
46
+     * @var string $object_type what does this class represent in WordPress terms?
47
+     */
48
+    public $object_type = 'image';
49
+    /**
50
+     * @var string $representation what does this class represent in WordPress terms?
51
+     */
52
+    public static $representation = 'image';
53
+    /**
54
+     * @var array of supported relative file types
55
+     */
56
+    private $file_types = array('jpg', 'jpeg', 'png', 'svg', 'bmp', 'ico', 'gif', 'tiff', 'pdf');
57
+    /**
58
+     * @api
59
+     * @var string $file_loc the location of the image file in the filesystem (ex: `/var/www/htdocs/wp-content/uploads/2015/08/my-pic.jpg`)
60
+     */
61
+    public $file_loc;
62
+    public $file;
63
+    /**
64
+     * @api
65
+     * @var integer the ID of the image (which is a WP_Post)
66
+     */
67
+    public $id;
68
+    public $sizes = array();
69
+    /**
70
+     * @api
71
+     * @var string $caption the string stored in the WordPress database
72
+     */
73
+    public $caption;
74
+    /**
75
+     * @var $_wp_attached_file the file as stored in the WordPress database
76
+     */
77
+    protected $_wp_attached_file;
78
+
79
+    /**
80
+     * Creates a new TimberImage object
81
+     * @example
82
+     * ```php
83
+     * // You can pass it an ID number
84
+     * $myImage = new TimberImage(552);
85
+     *
86
+     * //Or send it a URL to an image
87
+     * $myImage = new TimberImage('http://google.com/logo.jpg');
88
+     * ```
89
+     * @param int|string $iid
90
+     */
91
+    public function __construct($iid) {
92
+        $this->init($iid);
93
+    }
94
+
95
+    /**
96
+     * @return string the src of the file
97
+     */
98
+    public function __toString() {
99
+        if ( $this->get_src() ) {
100
+            return $this->get_src();
101
+        }
102
+        return '';
103
+    }
104
+
105
+    /**
106
+     * Get a PHP array with pathinfo() info from the file
107
+     * @return array
108
+     */
109
+    function get_pathinfo() {
110
+        return pathinfo($this->file);
111
+    }
112
+
113
+    /**
114
+     * @internal
115
+     * @param string $dim
116
+     * @return array|int
117
+     */
118
+    protected function get_dimensions($dim = null) {
119
+        if ( isset($this->_dimensions) ) {
120
+            return $this->get_dimensions_loaded($dim);
121
+        }
122
+        if ( file_exists($this->file_loc) && filesize($this->file_loc) ) {
123
+            list($width, $height) = getimagesize($this->file_loc);
124
+            $this->_dimensions = array();
125
+            $this->_dimensions[0] = $width;
126
+            $this->_dimensions[1] = $height;
127
+            return $this->get_dimensions_loaded($dim);
128
+        }
129
+    }
130
+
131
+    /**
132
+     * @internal
133
+     * @param string|null $dim
134
+     * @return array|int
135
+     */
136
+    protected function get_dimensions_loaded($dim) {
137
+        if ( $dim === null ) {
138
+            return $this->_dimensions;
139
+        }
140
+        if ( $dim == 'w' || $dim == 'width' ) {
141
+            return $this->_dimensions[0];
142
+        }
143
+        if ( $dim == 'h' || $dim == 'height' ) {
144
+            return $this->_dimensions[1];
145
+        }
146
+        return null;
147
+    }
148
+
149
+    /**
150
+     * @internal
151
+     * @param  int $iid the id number of the image in the WP database
152
+     */
153
+    protected function get_image_info( $iid ) {
154
+        $image_info = $iid;
155
+        if (is_numeric($iid)) {
156
+            $image_info = wp_get_attachment_metadata($iid);
157
+            if (!is_array($image_info)) {
158
+                $image_info = array();
159
+            }
160
+            $image_custom = get_post_custom($iid);
161
+            $basic = get_post($iid);
162
+            if ($basic) {
163
+                if (isset($basic->post_excerpt)) {
164
+                    $this->caption = $basic->post_excerpt;
165
+                }
166
+                $image_custom = array_merge($image_custom, get_object_vars($basic));
167
+            }
168
+            return array_merge($image_info, $image_custom);
169
+        }
170
+        if (is_array($image_info) && isset($image_info['image'])) {
171
+            return $image_info['image'];
172
+        }
173
+        if (is_object($image_info)) {
174
+            return get_object_vars($image_info);
175
+        }
176
+        return $iid;
177
+    }
178
+
179
+    /**
180
+     * @internal
181
+     * @param  string $url for evaluation
182
+     * @return string with http/https corrected depending on what's appropriate for server
183
+     */
184
+    protected static function _maybe_secure_url($url) {
185
+        if ( is_ssl() && strpos($url, 'https') !== 0 && strpos($url, 'http') === 0 ) {
186
+            $url = 'https' . substr($url, strlen('http'));
187
+        }
188
+        return $url;
189
+    }
190
+
191
+    public static function wp_upload_dir() {
192
+        static $wp_upload_dir = false;
193
+
194
+        if ( !$wp_upload_dir ) {
195
+            $wp_upload_dir = wp_upload_dir();
196
+        }
197
+
198
+        return $wp_upload_dir;
199
+    }
200
+
201
+    /**
202
+     * @internal
203
+     * @param int $iid
204
+     */
205
+    function init( $iid = false ) {
206
+        if ( !is_numeric( $iid ) && is_string( $iid ) ) {
207
+            if (strstr($iid, '://')) {
208
+                $this->init_with_url($iid);
209
+                return;
210
+            }
211
+            if ( strstr($iid, ABSPATH) ) {
212
+                $this->init_with_file_path($iid);
213
+                return;
214
+            }
215
+
216
+            $relative = false;
217
+            $iid_lower = strtolower($iid);
218
+            foreach( $this->file_types as $type ) { if( strstr( $iid_lower, $type ) ) { $relative = true; break; } };
219
+            if ( $relative ) {
220
+                $this->init_with_relative_path( $iid );
221
+                return;
222
+            }
223
+        } else if ( $iid instanceof WP_Post ) {
224
+            $ref = new ReflectionClass($this);
225
+            $post = $ref->getParentClass()->newInstance($iid->ID);
226
+            if (isset($post->_thumbnail_id) && $post->_thumbnail_id) {
227
+                return $this->init((int) $post->_thumbnail_id);
228
+            }
229
+            return $this->init($iid->ID);
230
+        } else if ( $iid instanceof TimberPost ) {
231
+            /**
232
+             * This will catch TimberPost and any post classes that extend TimberPost,
233
+             * see http://php.net/manual/en/internals2.opcodes.instanceof.php#109108
234
+             * and https://github.com/jarednova/timber/wiki/Extending-Timber
235
+             */
236
+            $iid = (int) $iid->_thumbnail_id;
237
+        }
238
+
239
+        $image_info = $this->get_image_info($iid);
240
+
241
+        $this->import($image_info);
242
+        $basedir = self::wp_upload_dir();
243
+        $basedir = $basedir['basedir'];
244
+        if ( isset($this->file) ) {
245
+            $this->file_loc = $basedir . DIRECTORY_SEPARATOR . $this->file;
246
+        } else if ( isset($this->_wp_attached_file) ) {
247
+            $this->file = reset($this->_wp_attached_file);
248
+            $this->file_loc = $basedir . DIRECTORY_SEPARATOR . $this->file;
249
+        }
250
+        if ( isset($image_info['id']) ) {
251
+            $this->ID = $image_info['id'];
252
+        } else if ( is_numeric($iid) ) {
253
+            $this->ID = $iid;
254
+        }
255
+        if ( isset($this->ID) ) {
256
+            $custom = get_post_custom($this->ID);
257
+            foreach ($custom as $key => $value) {
258
+                $this->$key = $value[0];
259
+            }
260
+            $this->id = $this->ID;
261
+        } else {
262
+            if ( is_array($iid) || is_object($iid) ) {
263
+                TimberHelper::error_log('Not able to init in TimberImage with iid=');
264
+                TimberHelper::error_log($iid);
265
+            } else {
266
+                TimberHelper::error_log('Not able to init in TimberImage with iid=' . $iid);
267
+            }
268
+        }
269
+    }
270
+
271
+    /**
272
+     * @internal
273
+     * @param string $relative_path
274
+     */
275
+    protected function init_with_relative_path( $relative_path ) {
276
+        $this->abs_url = home_url( $relative_path );
277
+        $file_path = TimberURLHelper::get_full_path( $relative_path );
278
+        $this->file_loc = $file_path;
279
+        $this->file = $file_path;
280
+    }
281
+
282
+    /**
283
+     * @internal
284
+     * @param string $file_path
285
+     */
286
+    protected function init_with_file_path( $file_path ) {
287
+        $url = TimberURLHelper::file_system_to_url( $file_path );
288
+        $this->abs_url = $url;
289
+        $this->file_loc = $file_path;
290
+        $this->file = $file_path;
291
+    }
292
+
293
+    /**
294
+     * @internal
295
+     * @param string $url
296
+     */
297
+    protected function init_with_url($url) {
298
+        $this->abs_url = $url;
299
+        if ( TimberURLHelper::is_local($url) ) {
300
+            $this->file = ABSPATH . TimberURLHelper::get_rel_url($url);
301
+            $this->file_loc = ABSPATH . TimberURLHelper::get_rel_url($url);
302
+        }
303
+    }
304
+
305
+    /**
306
+     * @api
307
+     * @example
308
+     * ```twig
309
+     * <img src="{{ image.src }}" alt="{{ image.alt }}" />
310
+     * ```
311
+     * ```html
312
+     * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" alt="W3 Checker told me to add alt text, so I am" />
313
+     * ```
314
+     * @return string alt text stored in WordPress
315
+     */
316
+    public function alt() {
317
+        $alt = trim(strip_tags(get_post_meta($this->ID, '_wp_attachment_image_alt', true)));
318
+        return $alt;
319
+    }
320
+
321
+    /**
322
+     * @api
323
+     * @example
324
+     * ```twig
325
+     * {% if post.thumbnail.aspect < 1 %}
326
+     *     {# handle vertical image #}
327
+     *     <img src="{{ post.thumbnail.src|resize(300, 500) }}" alt="A basketball player" />
328
+     * {% else %}
329
+     * 	   <img src="{{ post.thumbnail.src|resize(500) }}" alt="A sumo wrestler" />
330
+     * {% endif %}
331
+     * ```
332
+     * @return float
333
+     */
334
+    public function aspect() {
335
+        $w = intval($this->width());
336
+        $h = intval($this->height());
337
+        return $w / $h;
338
+    }
339
+
340
+    /**
341
+     * @api
342
+     * @example
343
+     * ```twig
344
+     * <img src="{{ image.src }}" height="{{ image.height }}" />
345
+     * ```
346
+     * ```html
347
+     * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" height="900" />
348
+     * ```
349
+     * @return int
350
+     */
351
+    public function height() {
352
+        return $this->get_dimensions('height');
353
+    }
354
+
355
+    /**
356
+     * Returns the link to an image attachment's Permalink page (NOT the link for the image itself!!)
357
+     * @api
358
+     * @example
359
+     * ```twig
360
+     * <a href="{{ image.link }}"><img src="{{ image.src }} "/></a>
361
+     * ```
362
+     * ```html
363
+     * <a href="http://example.org/my-cool-picture"><img src="http://example.org/wp-content/uploads/2015/whatever.jpg"/></a>
364
+     * ```
365
+     */
366
+    public function link() {
367
+        if ( strlen($this->abs_url) ) {
368
+            return $this->abs_url;
369
+        }
370
+        return get_permalink($this->ID);
371
+    }
372
+
373
+    /**
374
+     * @api
375
+     * @return bool|TimberPost
376
+     */
377
+    public function parent() {
378
+        if ( !$this->post_parent ) {
379
+            return false;
380
+        }
381
+        return new $this->PostClass($this->post_parent);
382
+    }
383
+
384
+    /**
385
+     * @api
386
+     * @example
387
+     * ```twig
388
+     * <img src="{{ image.path }}" />
389
+     * ```
390
+     * ```html
391
+     * <img src="/wp-content/uploads/2015/08/pic.jpg" />
392
+     * ```
393
+     * @return  string the /relative/path/to/the/file
394
+     */
395
+    public function path() {
396
+        return TimberURLHelper::get_rel_path($this->src());
397
+    }
398
+
399
+    /**
400
+     * @param string $size a size known to WordPress (like "medium")
401
+     * @api
402
+     * @example
403
+     * ```twig
404
+     * <h1>{{post.title}}</h1>
405
+     * <img src="{{post.thumbnail.src}}" />
406
+     * ```
407
+     * ```html
408
+     * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" />
409
+     * ```
410
+     * @return bool|string
411
+     */
412
+    public function src($size = '') {
413
+        if ( isset($this->abs_url) ) {
414
+            return $this->_maybe_secure_url($this->abs_url);
415
+        }
416
+
417
+        if ( $size && is_string($size) && isset($this->sizes[$size]) ) {
418
+            $image = image_downsize($this->ID, $size);
419
+            return $this->_maybe_secure_url(reset($image));
420
+        }
421
+
422
+        if ( !isset($this->file) && isset($this->_wp_attached_file) ) {
423
+            $this->file = $this->_wp_attached_file;
424
+        }
425
+
426
+        if ( !isset($this->file) ) {
427
+            return false;
428
+        }
429
+
430
+        $dir = self::wp_upload_dir();
431
+        $base = $dir['baseurl'];
432
+
433
+        $src = trailingslashit($this->_maybe_secure_url($base)) . $this->file;
434
+        $src = apply_filters('timber/image/src', $src, $this->ID);
435
+        return apply_filters('timber_image_src', $src, $this->ID);
436
+    }
437
+
438
+    /**
439
+     * @deprecated use src() instead
440
+     * @return string
441
+     */
442
+    function url() {
443
+        return $this->get_src();
444
+    }
445
+
446
+    /**
447
+     * @api
448
+     * @example
449
+     * ```twig
450
+     * <img src="{{ image.src }}" width="{{ image.width }}" />
451
+     * ```
452
+     * ```html
453
+     * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" width="1600" />
454
+     * ```
455
+     * @return int
456
+     */
457
+    public function width() {
458
+        return $this->get_dimensions('width');
459
+    }
460
+
461
+
462
+    /**
463
+     * @deprecated 0.21.9 use TimberImage::width() instead
464
+     * @internal
465
+     * @return int
466
+     */
467
+    function get_width() {
468
+        return $this->width();
469
+    }
470
+
471
+    /**
472
+     * @deprecated 0.21.9 use TimberImage::height() instead
473
+     * @internal
474
+     * @return int
475
+     */
476
+    function get_height() {
477
+        return $this->height();
478
+    }
479
+
480
+    /**
481
+     * @deprecated 0.21.9 use TimberImage::src
482
+     * @internal
483
+     * @param string $size
484
+     * @return bool|string
485
+     */
486
+    function get_src( $size = '' ) {
487
+        return $this->src( $size );
488
+    }
489
+
490
+    /**
491
+     * @deprecated 0.21.9 use TimberImage::path()
492
+     * @internal
493
+     * @return string
494
+     */
495
+    function get_path() {
496
+        return $this->link();
497
+    }
498
+
499
+    /**
500
+     * @deprecated use src() instead
501
+     * @return string
502
+     */
503
+    function get_url() {
504
+        return $this->get_src();
505
+    }
506
+
507
+    /**
508
+     * @internal
509
+     * @deprecated 0.21.8
510
+     * @return bool|TimberPost
511
+     */
512
+    function get_parent() {
513
+        return $this->parent();
514
+    }
515
+
516
+    /**
517
+     * @internal
518
+     * @deprecated 0.21.9
519
+     * @see TimberImage::alt
520
+     * @return string
521
+     */
522
+    function get_alt() {
523
+        return $this->alt();
524
+    }
525 525
 
526 526
 }
Please login to merge, or discard this patch.
lib/timber-archives.php 1 patch
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -32,284 +32,284 @@
 block discarded – undo
32 32
  */
33 33
 class TimberArchives extends TimberCore {
34 34
 
35
-	public $base = '';
36
-	/**
37
-	 * @api
38
-	 * @var array the items of the archives to iterate through and markup for your page
39
-	 */
40
-	public $items;
35
+    public $base = '';
36
+    /**
37
+     * @api
38
+     * @var array the items of the archives to iterate through and markup for your page
39
+     */
40
+    public $items;
41 41
 
42
-	/**
43
-	 * @api
44
-	 * @param $args array of arguments {
45
-	 *     @type bool show_year => false
46
-	 *     @type string
47
-	 *     @type string type => 'monthly-nested'
48
-	 *     @type int limit => -1
49
-	 *     @type bool show_post_count => false
50
-	 *     @type string order => 'DESC'
51
-	 *     @type string post_type => 'post'
52
-	 *     @type bool show_year => false
53
-	 *     @type bool nested => false
54
-	 * }
55
-	 * @param string $base any additional paths that need to be prepended to the URLs that are generated, for example: "tags"
56
-	 */
57
-	function __construct( $args = null, $base = '' ) {
58
-		$this->init($args, $base);
59
-	}
42
+    /**
43
+     * @api
44
+     * @param $args array of arguments {
45
+     *     @type bool show_year => false
46
+     *     @type string
47
+     *     @type string type => 'monthly-nested'
48
+     *     @type int limit => -1
49
+     *     @type bool show_post_count => false
50
+     *     @type string order => 'DESC'
51
+     *     @type string post_type => 'post'
52
+     *     @type bool show_year => false
53
+     *     @type bool nested => false
54
+     * }
55
+     * @param string $base any additional paths that need to be prepended to the URLs that are generated, for example: "tags"
56
+     */
57
+    function __construct( $args = null, $base = '' ) {
58
+        $this->init($args, $base);
59
+    }
60 60
 
61
-	/**
62
-	 * @internal
63
-	 * @param array|string $args
64
-	 * @param string $base
65
-	 */
66
-	function init( $args = null, $base = '' ) {
67
-		$this->base = $base;
68
-		$this->items = $this->get_items($args);
69
-	}
61
+    /**
62
+     * @internal
63
+     * @param array|string $args
64
+     * @param string $base
65
+     */
66
+    function init( $args = null, $base = '' ) {
67
+        $this->base = $base;
68
+        $this->items = $this->get_items($args);
69
+    }
70 70
 
71
-	/**
72
-	 * @internal
73
-	 * @param string $url
74
-	 * @param string $text
75
-	 * @return mixed
76
-	 */
77
-	protected function get_archives_link( $url, $text ) {
78
-		$ret = array();
79
-		$ret['text'] = $ret['title'] = $ret['name'] = wptexturize($text);
80
-		$ret['url'] = $ret['link'] = esc_url(TimberURLHelper::prepend_to_url($url, $this->base));
81
-		return $ret;
82
-	}
71
+    /**
72
+     * @internal
73
+     * @param string $url
74
+     * @param string $text
75
+     * @return mixed
76
+     */
77
+    protected function get_archives_link( $url, $text ) {
78
+        $ret = array();
79
+        $ret['text'] = $ret['title'] = $ret['name'] = wptexturize($text);
80
+        $ret['url'] = $ret['link'] = esc_url(TimberURLHelper::prepend_to_url($url, $this->base));
81
+        return $ret;
82
+    }
83 83
 
84
-	/**
85
-	 * @internal
86
-	 * @param array $args
87
-	 * @param string $last_changed
88
-	 * @param string $join
89
-	 * @param string $where
90
-	 * @param string $order
91
-	 * @param string $limit
92
-	 * @return array
93
-	 */
94
-	protected function get_items_yearly( $args, $last_changed, $join, $where, $order, $limit ) {
95
-		global $wpdb;
96
-		$output = array();
97
-		$query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} $join $where GROUP BY YEAR(post_date) ORDER BY post_date $order $limit";
98
-		$key = md5($query);
99
-		$key = "wp_get_archives:$key:$last_changed";
100
-		if (!$results = wp_cache_get($key, 'posts')) {
101
-			$results = $wpdb->get_results($query);
102
-			wp_cache_set($key, $results, 'posts');
103
-		}
104
-		if ($results) {
105
-			foreach ( (array)$results as $result ) {
106
-				$url = get_year_link( $result->year );
107
-				$text = sprintf('%d', $result->year);
108
-				$output[] = $this->get_archives_link($url, $text);
109
-			}
110
-		}
111
-		return $output;
112
-	}
84
+    /**
85
+     * @internal
86
+     * @param array $args
87
+     * @param string $last_changed
88
+     * @param string $join
89
+     * @param string $where
90
+     * @param string $order
91
+     * @param string $limit
92
+     * @return array
93
+     */
94
+    protected function get_items_yearly( $args, $last_changed, $join, $where, $order, $limit ) {
95
+        global $wpdb;
96
+        $output = array();
97
+        $query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} $join $where GROUP BY YEAR(post_date) ORDER BY post_date $order $limit";
98
+        $key = md5($query);
99
+        $key = "wp_get_archives:$key:$last_changed";
100
+        if (!$results = wp_cache_get($key, 'posts')) {
101
+            $results = $wpdb->get_results($query);
102
+            wp_cache_set($key, $results, 'posts');
103
+        }
104
+        if ($results) {
105
+            foreach ( (array)$results as $result ) {
106
+                $url = get_year_link( $result->year );
107
+                $text = sprintf('%d', $result->year);
108
+                $output[] = $this->get_archives_link($url, $text);
109
+            }
110
+        }
111
+        return $output;
112
+    }
113 113
 
114
-	/**
115
-	 * @internal
116
-	 * @param array|string $args
117
-	 * @param string $last_changed
118
-	 * @param string $join
119
-	 * @param string $where
120
-	 * @param string $order
121
-	 * @param int $limit
122
-	 * @param bool $nested
123
-	 * @return array
124
-	 */
125
-	protected function get_items_monthly( $args, $last_changed, $join, $where, $order, $limit = 1000, $nested = true ) {
126
-		global $wpdb, $wp_locale;
127
-		$output = array();
128
-		$defaults = array(
129
-			'show_year' => false,
130
-		);
131
-		$r = wp_parse_args($args, $defaults);
114
+    /**
115
+     * @internal
116
+     * @param array|string $args
117
+     * @param string $last_changed
118
+     * @param string $join
119
+     * @param string $where
120
+     * @param string $order
121
+     * @param int $limit
122
+     * @param bool $nested
123
+     * @return array
124
+     */
125
+    protected function get_items_monthly( $args, $last_changed, $join, $where, $order, $limit = 1000, $nested = true ) {
126
+        global $wpdb, $wp_locale;
127
+        $output = array();
128
+        $defaults = array(
129
+            'show_year' => false,
130
+        );
131
+        $r = wp_parse_args($args, $defaults);
132 132
 
133
-		$show_year = $r['show_year'];
134
-		//will need to specify which year we're looking for
135
-		$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts "
136
-			. "FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) "
137
-			. "ORDER BY post_date $order $limit";
138
-		$key = md5($query);
139
-		$key = "wp_get_archives:$key:$last_changed";
140
-		if (!$results = wp_cache_get($key, 'posts')) {
141
-			$results = $wpdb->get_results($query);
142
-			wp_cache_set($key, $results, 'posts');
143
-		}
144
-		if ($results) {
145
-			foreach ((array)$results as $result) {
146
-				$url = get_month_link($result->year, $result->month);
147
-				if ($show_year && !$nested) {
148
-					$text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($result->month), $result->year);
149
-				} else {
150
-					$text = sprintf(__('%1$s'), $wp_locale->get_month($result->month));
151
-				}
152
-				if ($nested) {
153
-					$output[$result->year][] = $this->get_archives_link($url, $text);
154
-				} else {
155
-					$output[] = $this->get_archives_link($url, $text);
156
-				}
157
-			}
158
-		}
159
-		if ($nested) {
160
-			$out2 = array();
161
-			foreach ($output as $year => $months) {
162
-				$out2[] = array('name' => $year, 'children' => $months);
163
-			}
164
-			return $out2;
165
-		}
166
-		return $output;
167
-	}
133
+        $show_year = $r['show_year'];
134
+        //will need to specify which year we're looking for
135
+        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts "
136
+            . "FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) "
137
+            . "ORDER BY post_date $order $limit";
138
+        $key = md5($query);
139
+        $key = "wp_get_archives:$key:$last_changed";
140
+        if (!$results = wp_cache_get($key, 'posts')) {
141
+            $results = $wpdb->get_results($query);
142
+            wp_cache_set($key, $results, 'posts');
143
+        }
144
+        if ($results) {
145
+            foreach ((array)$results as $result) {
146
+                $url = get_month_link($result->year, $result->month);
147
+                if ($show_year && !$nested) {
148
+                    $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($result->month), $result->year);
149
+                } else {
150
+                    $text = sprintf(__('%1$s'), $wp_locale->get_month($result->month));
151
+                }
152
+                if ($nested) {
153
+                    $output[$result->year][] = $this->get_archives_link($url, $text);
154
+                } else {
155
+                    $output[] = $this->get_archives_link($url, $text);
156
+                }
157
+            }
158
+        }
159
+        if ($nested) {
160
+            $out2 = array();
161
+            foreach ($output as $year => $months) {
162
+                $out2[] = array('name' => $year, 'children' => $months);
163
+            }
164
+            return $out2;
165
+        }
166
+        return $output;
167
+    }
168 168
 
169
-	/**
170
-	 * @api
171
-	 * @param array|string $args
172
-	 * @return array|string
173
-	 */
174
-	function get_items( $args = null ) {
175
-		global $wpdb;
169
+    /**
170
+     * @api
171
+     * @param array|string $args
172
+     * @return array|string
173
+     */
174
+    function get_items( $args = null ) {
175
+        global $wpdb;
176 176
 
177
-		$defaults = array(
178
-			'type' => 'monthly-nested',
179
-			'limit' => '',
180
-			'show_post_count' => false,
181
-			'order' => 'DESC',
182
-			'post_type' => 'post',
183
-			'show_year' => false,
184
-			'nested' => false
185
-		);
177
+        $defaults = array(
178
+            'type' => 'monthly-nested',
179
+            'limit' => '',
180
+            'show_post_count' => false,
181
+            'order' => 'DESC',
182
+            'post_type' => 'post',
183
+            'show_year' => false,
184
+            'nested' => false
185
+        );
186 186
 
187
-		$args = wp_parse_args($args, $defaults);
188
-		$post_type = $args['post_type'];
189
-		$order = $args['order'];
190
-		$nested = $args['nested'];
191
-		$type = $args['type'];
192
-		$limit = '';
193
-		if ( $type == 'yearlymonthly' || $type == 'yearmonth' ) {
194
-			$type = 'monthly-nested';
195
-		}
196
-		if ( $type == 'monthly-nested' ) {
197
-			$nested = true;
198
-		}
187
+        $args = wp_parse_args($args, $defaults);
188
+        $post_type = $args['post_type'];
189
+        $order = $args['order'];
190
+        $nested = $args['nested'];
191
+        $type = $args['type'];
192
+        $limit = '';
193
+        if ( $type == 'yearlymonthly' || $type == 'yearmonth' ) {
194
+            $type = 'monthly-nested';
195
+        }
196
+        if ( $type == 'monthly-nested' ) {
197
+            $nested = true;
198
+        }
199 199
 
200
-		if ( !empty($args['limit']) ) {
201
-			$limit = absint($limit);
202
-			$limit = ' LIMIT ' . $limit;
203
-		}
200
+        if ( !empty($args['limit']) ) {
201
+            $limit = absint($limit);
202
+            $limit = ' LIMIT ' . $limit;
203
+        }
204 204
 
205
-		$order = strtoupper($order);
206
-		if ( $order !== 'ASC' ) {
207
-			$order = 'DESC';
208
-		}
205
+        $order = strtoupper($order);
206
+        if ( $order !== 'ASC' ) {
207
+            $order = 'DESC';
208
+        }
209 209
 
210
-		// this is what will separate dates on weekly archive links
211
-		$archive_week_separator = '&#8211;';
210
+        // this is what will separate dates on weekly archive links
211
+        $archive_week_separator = '&#8211;';
212 212
 
213
-		// over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
214
-		$archive_date_format_over_ride = 0;
213
+        // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
214
+        $archive_date_format_over_ride = 0;
215 215
 
216
-		// options for daily archive (only if you over-ride the general date format)
217
-		$archive_day_date_format = 'Y/m/d';
216
+        // options for daily archive (only if you over-ride the general date format)
217
+        $archive_day_date_format = 'Y/m/d';
218 218
 
219
-		// options for weekly archive (only if you over-ride the general date format)
220
-		$archive_week_start_date_format = 'Y/m/d';
221
-		$archive_week_end_date_format = 'Y/m/d';
219
+        // options for weekly archive (only if you over-ride the general date format)
220
+        $archive_week_start_date_format = 'Y/m/d';
221
+        $archive_week_end_date_format = 'Y/m/d';
222 222
 
223
-		if (!$archive_date_format_over_ride) {
224
-			$archive_day_date_format = get_option('date_format');
225
-			$archive_week_start_date_format = get_option('date_format');
226
-			$archive_week_end_date_format = get_option('date_format');
227
-		}
223
+        if (!$archive_date_format_over_ride) {
224
+            $archive_day_date_format = get_option('date_format');
225
+            $archive_week_start_date_format = get_option('date_format');
226
+            $archive_week_end_date_format = get_option('date_format');
227
+        }
228 228
 
229
-		$where = $wpdb->prepare('WHERE post_type = "%s" AND post_status = "publish"', $post_type);
230
-		$where = apply_filters('getarchives_where', $where, $args);
231
-		$join = apply_filters('getarchives_join', '', $args);
229
+        $where = $wpdb->prepare('WHERE post_type = "%s" AND post_status = "publish"', $post_type);
230
+        $where = apply_filters('getarchives_where', $where, $args);
231
+        $join = apply_filters('getarchives_join', '', $args);
232 232
 
233
-		$output = array();
234
-		$last_changed = wp_cache_get('last_changed', 'posts');
235
-		if (!$last_changed) {
236
-			$last_changed = microtime();
237
-			wp_cache_set('last_changed', $last_changed, 'posts');
238
-		}
239
-		if ( 'monthly' == $type ) {
240
-			$output = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit, $nested);
241
-		} elseif ( 'yearly' == $type ) {
242
-			$output = $this->get_items_yearly($args, $last_changed, $join, $where, $order, $limit);
243
-		} elseif ( 'monthly-nested' == $type ) {
244
-			$output = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit);
245
-		} elseif ( 'daily' == $type ) {
246
-			$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date $order $limit";
247
-			$key = md5($query);
248
-			$key = "wp_get_archives:$key:$last_changed";
249
-			if (!$results = wp_cache_get($key, 'posts')) {
250
-				$results = $wpdb->get_results($query);
251
-				$cache = array();
252
-				$cache[$key] = $results;
253
-				wp_cache_set($key, $results, 'posts');
254
-			}
255
-			if ( $results ) {
256
-				foreach ( (array)$results as $result ) {
257
-					$url = get_day_link($result->year, $result->month, $result->dayofmonth);
258
-					$date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $result->year, $result->month, $result->dayofmonth);
259
-					$text = mysql2date($archive_day_date_format, $date);
260
-					$output[] = $this->get_archives_link($url, $text);
261
-				}
262
-			}
263
-		} elseif ( 'weekly' == $type ) {
264
-			$week = _wp_mysql_week('`post_date`');
265
-			$query = "SELECT DISTINCT $week AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, "
266
-				. "count( `ID` ) AS `posts` FROM `$wpdb->posts` $join $where GROUP BY $week, YEAR( `post_date` ) ORDER BY `post_date` $order $limit";
267
-			$key = md5($query);
268
-			$key = "wp_get_archives:$key:$last_changed";
269
-			if (!$results = wp_cache_get($key, 'posts')) {
270
-				$results = $wpdb->get_results($query);
271
-				wp_cache_set($key, $results, 'posts');
272
-			}
273
-			$arc_w_last = '';
274
-			if ( $results ) {
275
-				foreach ( (array)$results as $result ) {
276
-					if ( $result->week != $arc_w_last ) {
277
-						$arc_year = $result->yr;
278
-						$arc_w_last = $result->week;
279
-						$arc_week = get_weekstartend($result->yyyymmdd, get_option('start_of_week'));
280
-						$arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
281
-						$arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
282
-						$url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $result->week);
283
-						$text = $arc_week_start . $archive_week_separator . $arc_week_end;
284
-						$output[] = $this->get_archives_link($url, $text);
285
-					}
286
-				}
287
-			}
288
-		} elseif ( 'postbypost' == $type || 'alpha' == $type ) {
289
-			$orderby = 'alpha' == $type ? 'post_title ASC ' : 'post_date DESC ';
290
-			$query = "SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit";
291
-			$key = md5($query);
292
-			$key = "wp_get_archives:$key:$last_changed";
293
-			if ( !$results = wp_cache_get($key, 'posts') ) {
294
-				$results = $wpdb->get_results($query);
295
-				wp_cache_set($key, $results, 'posts');
296
-			}
297
-			if ( $results ) {
298
-				foreach ( (array)$results as $result ) {
299
-					if ($result->post_date != '0000-00-00 00:00:00') {
300
-						$url = get_permalink($result);
301
-						if ($result->post_title) {
302
-							/** This filter is documented in wp-includes/post-template.php */
303
-							$text = strip_tags(apply_filters('the_title', $result->post_title, $result->ID));
304
-						} else {
305
-							$text = $result->ID;
306
-						}
307
-						$output[] = $this->get_archives_link($url, $text);
308
-					}
309
-				}
310
-			}
311
-		}
312
-		return $output;
313
-	}
233
+        $output = array();
234
+        $last_changed = wp_cache_get('last_changed', 'posts');
235
+        if (!$last_changed) {
236
+            $last_changed = microtime();
237
+            wp_cache_set('last_changed', $last_changed, 'posts');
238
+        }
239
+        if ( 'monthly' == $type ) {
240
+            $output = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit, $nested);
241
+        } elseif ( 'yearly' == $type ) {
242
+            $output = $this->get_items_yearly($args, $last_changed, $join, $where, $order, $limit);
243
+        } elseif ( 'monthly-nested' == $type ) {
244
+            $output = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit);
245
+        } elseif ( 'daily' == $type ) {
246
+            $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date $order $limit";
247
+            $key = md5($query);
248
+            $key = "wp_get_archives:$key:$last_changed";
249
+            if (!$results = wp_cache_get($key, 'posts')) {
250
+                $results = $wpdb->get_results($query);
251
+                $cache = array();
252
+                $cache[$key] = $results;
253
+                wp_cache_set($key, $results, 'posts');
254
+            }
255
+            if ( $results ) {
256
+                foreach ( (array)$results as $result ) {
257
+                    $url = get_day_link($result->year, $result->month, $result->dayofmonth);
258
+                    $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $result->year, $result->month, $result->dayofmonth);
259
+                    $text = mysql2date($archive_day_date_format, $date);
260
+                    $output[] = $this->get_archives_link($url, $text);
261
+                }
262
+            }
263
+        } elseif ( 'weekly' == $type ) {
264
+            $week = _wp_mysql_week('`post_date`');
265
+            $query = "SELECT DISTINCT $week AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, "
266
+                . "count( `ID` ) AS `posts` FROM `$wpdb->posts` $join $where GROUP BY $week, YEAR( `post_date` ) ORDER BY `post_date` $order $limit";
267
+            $key = md5($query);
268
+            $key = "wp_get_archives:$key:$last_changed";
269
+            if (!$results = wp_cache_get($key, 'posts')) {
270
+                $results = $wpdb->get_results($query);
271
+                wp_cache_set($key, $results, 'posts');
272
+            }
273
+            $arc_w_last = '';
274
+            if ( $results ) {
275
+                foreach ( (array)$results as $result ) {
276
+                    if ( $result->week != $arc_w_last ) {
277
+                        $arc_year = $result->yr;
278
+                        $arc_w_last = $result->week;
279
+                        $arc_week = get_weekstartend($result->yyyymmdd, get_option('start_of_week'));
280
+                        $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
281
+                        $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
282
+                        $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $result->week);
283
+                        $text = $arc_week_start . $archive_week_separator . $arc_week_end;
284
+                        $output[] = $this->get_archives_link($url, $text);
285
+                    }
286
+                }
287
+            }
288
+        } elseif ( 'postbypost' == $type || 'alpha' == $type ) {
289
+            $orderby = 'alpha' == $type ? 'post_title ASC ' : 'post_date DESC ';
290
+            $query = "SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit";
291
+            $key = md5($query);
292
+            $key = "wp_get_archives:$key:$last_changed";
293
+            if ( !$results = wp_cache_get($key, 'posts') ) {
294
+                $results = $wpdb->get_results($query);
295
+                wp_cache_set($key, $results, 'posts');
296
+            }
297
+            if ( $results ) {
298
+                foreach ( (array)$results as $result ) {
299
+                    if ($result->post_date != '0000-00-00 00:00:00') {
300
+                        $url = get_permalink($result);
301
+                        if ($result->post_title) {
302
+                            /** This filter is documented in wp-includes/post-template.php */
303
+                            $text = strip_tags(apply_filters('the_title', $result->post_title, $result->ID));
304
+                        } else {
305
+                            $text = $result->ID;
306
+                        }
307
+                        $output[] = $this->get_archives_link($url, $text);
308
+                    }
309
+                }
310
+            }
311
+        }
312
+        return $output;
313
+    }
314 314
 
315 315
 }
Please login to merge, or discard this patch.
lib/integrations/wpcli-timber.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 if (!class_exists('WP_CLI_Command')) {
3
-	return;
3
+    return;
4 4
 }
5 5
 
6 6
 class Timber_WP_CLI_Command extends WP_CLI_Command {
Please login to merge, or discard this patch.
lib/timber-routes.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -2,32 +2,32 @@
 block discarded – undo
2 2
 
3 3
 class TimberRoutes {
4 4
 
5
-	/**
6
-	 * @deprecated since 0.21.1 use Upstatement/routes instead
7
-	 */
8
-	public static function init( $timber ) {
9
-		// Install ourselves in Timber
10
-		$timber->routes = new TimberRoutes();
11
-	}
5
+    /**
6
+     * @deprecated since 0.21.1 use Upstatement/routes instead
7
+     */
8
+    public static function init( $timber ) {
9
+        // Install ourselves in Timber
10
+        $timber->routes = new TimberRoutes();
11
+    }
12 12
 
13
-	/**
14
-	 * @param string $route
15
-	 * @param callable $callback
16
-	 * @deprecated since 0.21.1 use Upstatement/routes instead
17
-	 */
18
-	public static function add_route($route, $callback, $args = array()) {
19
-		Routes::map($route, $callback, $args);
20
-	}
13
+    /**
14
+     * @param string $route
15
+     * @param callable $callback
16
+     * @deprecated since 0.21.1 use Upstatement/routes instead
17
+     */
18
+    public static function add_route($route, $callback, $args = array()) {
19
+        Routes::map($route, $callback, $args);
20
+    }
21 21
 
22
-	/**
23
-	 * @param array $template
24
-	 * @param mixed $query
25
-	 * @param int $status_code
26
-	 * @param bool $tparams
27
-	 * @return bool
28
-	 * @deprecated since 0.21.1 use Upstatement/routes instead
29
-	 */
30
-	public static function load_view($template, $query = false, $status_code = 200, $tparams = false) {
31
-		Routes::load($template, $tparams, $query, $status_code);
32
-	}
22
+    /**
23
+     * @param array $template
24
+     * @param mixed $query
25
+     * @param int $status_code
26
+     * @param bool $tparams
27
+     * @return bool
28
+     * @deprecated since 0.21.1 use Upstatement/routes instead
29
+     */
30
+    public static function load_view($template, $query = false, $status_code = 200, $tparams = false) {
31
+        Routes::load($template, $tparams, $query, $status_code);
32
+    }
33 33
 }
Please login to merge, or discard this patch.
lib/timber-comment.php 1 patch
Indentation   +327 added lines, -327 removed lines patch added patch discarded remove patch
@@ -21,360 +21,360 @@
 block discarded – undo
21 21
  */
22 22
 class TimberComment extends TimberCore implements TimberCoreInterface {
23 23
 
24
-	public $PostClass = 'TimberPost';
25
-	public $object_type = 'comment';
24
+    public $PostClass = 'TimberPost';
25
+    public $object_type = 'comment';
26 26
 
27
-	public static $representation = 'comment';
27
+    public static $representation = 'comment';
28 28
 
29
-	public $ID;
30
-	public $id;
31
-	public $comment_author_email;
32
-	public $comment_content;
33
-	public $comment_date;
34
-	public $comment_ID;
35
-	public $user_id;
36
-	public $comment_author;
29
+    public $ID;
30
+    public $id;
31
+    public $comment_author_email;
32
+    public $comment_content;
33
+    public $comment_date;
34
+    public $comment_ID;
35
+    public $user_id;
36
+    public $comment_author;
37 37
 
38
-	public $children = array();
38
+    public $children = array();
39 39
 
40
-	/**
41
-	 * @param int $cid
42
-	 */
43
-	function __construct($cid) {
44
-		$this->init($cid);
45
-	}
40
+    /**
41
+     * @param int $cid
42
+     */
43
+    function __construct($cid) {
44
+        $this->init($cid);
45
+    }
46 46
 
47
-	function __toString() {
48
-		return $this->content();
49
-	}
47
+    function __toString() {
48
+        return $this->content();
49
+    }
50 50
 
51
-	/**
52
-	 * @internal
53
-	 * @param integer $cid
54
-	 */
55
-	function init($cid) {
56
-		$comment_data = $cid;
57
-		if (is_integer($cid)) {
58
-			$comment_data = get_comment($cid);
59
-		}
60
-		$this->import($comment_data);
61
-		$this->ID = $this->comment_ID;
62
-		$this->id = $this->comment_ID;
63
-		$comment_meta_data = $this->get_meta_fields($this->ID);
64
-		$this->import($comment_meta_data);
65
-	}
51
+    /**
52
+     * @internal
53
+     * @param integer $cid
54
+     */
55
+    function init($cid) {
56
+        $comment_data = $cid;
57
+        if (is_integer($cid)) {
58
+            $comment_data = get_comment($cid);
59
+        }
60
+        $this->import($comment_data);
61
+        $this->ID = $this->comment_ID;
62
+        $this->id = $this->comment_ID;
63
+        $comment_meta_data = $this->get_meta_fields($this->ID);
64
+        $this->import($comment_meta_data);
65
+    }
66 66
 
67
-	/**
68
-	 * @api
69
-	 * @example
70
-	 * ```twig
71
-	 * <h3>Comments by...</h3>
72
-	 * <ol>
73
-	 * {% for comment in post.comments %}
74
-	 * 	<li>{{comment.author.name}}, who is a {{comment.author.role}}</li>
75
-	 * {% endfor %}
76
-	 * </ol>
77
-	 * ```
78
-	 * ```html
79
-	 * <h3>Comments by...</h3>
80
-	 * <ol>
81
-	 * 	<li>Jared Novack, who is a contributor</li>
82
-	 * 	<li>Katie Ricci, who is a subscriber</li>
83
-	 * 	<li>Rebecca Pearl, who is a author</li>
84
-	 * </ol>
85
-	 * ```
86
-	 * @return TimberUser
87
-	 */
88
-	public function author() {
89
-		if ($this->user_id) {
90
-			return new TimberUser($this->user_id);
91
-		} else {
92
-			$author = new TimberUser(0);
93
-			if (isset($this->comment_author) && $this->comment_author) {
94
-				$author->name = $this->comment_author;
95
-			} else {
96
-				$author->name = 'Anonymous';
97
-			}
98
-		}
99
-		return $author;
100
-	}
67
+    /**
68
+     * @api
69
+     * @example
70
+     * ```twig
71
+     * <h3>Comments by...</h3>
72
+     * <ol>
73
+     * {% for comment in post.comments %}
74
+     * 	<li>{{comment.author.name}}, who is a {{comment.author.role}}</li>
75
+     * {% endfor %}
76
+     * </ol>
77
+     * ```
78
+     * ```html
79
+     * <h3>Comments by...</h3>
80
+     * <ol>
81
+     * 	<li>Jared Novack, who is a contributor</li>
82
+     * 	<li>Katie Ricci, who is a subscriber</li>
83
+     * 	<li>Rebecca Pearl, who is a author</li>
84
+     * </ol>
85
+     * ```
86
+     * @return TimberUser
87
+     */
88
+    public function author() {
89
+        if ($this->user_id) {
90
+            return new TimberUser($this->user_id);
91
+        } else {
92
+            $author = new TimberUser(0);
93
+            if (isset($this->comment_author) && $this->comment_author) {
94
+                $author->name = $this->comment_author;
95
+            } else {
96
+                $author->name = 'Anonymous';
97
+            }
98
+        }
99
+        return $author;
100
+    }
101 101
 
102
-	/**
103
-	 * Fetches the Gravatar
104
-	 * @api
105
-	 * @example
106
-	 * ```twig
107
-	 * <img src="{{comment.avatar(36,template_uri~"/img/dude.jpg")}}" alt="Image of {{comment.author.name}}" />
108
-	 * ```
109
-	 * ```html
110
-	 * <img src="http://gravatar.com/i/sfsfsdfasdfsfa.jpg" alt="Image of Katherine Rich" />
111
-	 * ```
112
-	 * @param int $size
113
-	 * @param string $default
114
-	 * @return bool|mixed|string
115
-	 */
116
-	public function avatar($size = 92, $default = '') {
117
-		if (!get_option('show_avatars')) {
118
-			return false;
119
-		}
120
-		if (!is_numeric($size)) {
121
-			$size = '92';
122
-		}
102
+    /**
103
+     * Fetches the Gravatar
104
+     * @api
105
+     * @example
106
+     * ```twig
107
+     * <img src="{{comment.avatar(36,template_uri~"/img/dude.jpg")}}" alt="Image of {{comment.author.name}}" />
108
+     * ```
109
+     * ```html
110
+     * <img src="http://gravatar.com/i/sfsfsdfasdfsfa.jpg" alt="Image of Katherine Rich" />
111
+     * ```
112
+     * @param int $size
113
+     * @param string $default
114
+     * @return bool|mixed|string
115
+     */
116
+    public function avatar($size = 92, $default = '') {
117
+        if (!get_option('show_avatars')) {
118
+            return false;
119
+        }
120
+        if (!is_numeric($size)) {
121
+            $size = '92';
122
+        }
123 123
 
124
-		$email = $this->avatar_email();
125
-		$email_hash = '';
126
-		if (!empty($email)) {
127
-			$email_hash = md5(strtolower(trim($email)));
128
-		}
129
-		$host = $this->avatar_host($email_hash);
130
-		$default = $this->avatar_default($default, $email, $size, $host);
131
-		if (!empty($email)) {
132
-			$avatar = $this->avatar_out($default, $host, $email_hash, $size);
133
-		} else {
134
-			$avatar = $default;
135
-		}
136
-		return $avatar;
137
-	}
124
+        $email = $this->avatar_email();
125
+        $email_hash = '';
126
+        if (!empty($email)) {
127
+            $email_hash = md5(strtolower(trim($email)));
128
+        }
129
+        $host = $this->avatar_host($email_hash);
130
+        $default = $this->avatar_default($default, $email, $size, $host);
131
+        if (!empty($email)) {
132
+            $avatar = $this->avatar_out($default, $host, $email_hash, $size);
133
+        } else {
134
+            $avatar = $default;
135
+        }
136
+        return $avatar;
137
+    }
138 138
 
139
-	/**
140
-	 * @api
141
-	 * @return string
142
-	 */
143
-	public function content() {
144
-		return apply_filters('get_comment_text ', $this->comment_content);
145
-	}
139
+    /**
140
+     * @api
141
+     * @return string
142
+     */
143
+    public function content() {
144
+        return apply_filters('get_comment_text ', $this->comment_content);
145
+    }
146 146
 
147
-	/**
148
-	 * @api
149
-	 * @example
150
-	 * ```twig
151
-	 * {% if comment.approved %}
152
-	 * 	Your comment is good
153
-	 * {% else %}
154
-	 * 	Do you kiss your mother with that mouth?
155
-	 * {% endif %}
156
-	 * ```
157
-	 * @return boolean
158
-	 */
159
-	public function approved() {
160
-		return $this->comment_approved;
161
-	}
147
+    /**
148
+     * @api
149
+     * @example
150
+     * ```twig
151
+     * {% if comment.approved %}
152
+     * 	Your comment is good
153
+     * {% else %}
154
+     * 	Do you kiss your mother with that mouth?
155
+     * {% endif %}
156
+     * ```
157
+     * @return boolean
158
+     */
159
+    public function approved() {
160
+        return $this->comment_approved;
161
+    }
162 162
 
163
-	/**
164
-	 * @api
165
-	 * @example
166
-	 * ```twig
167
-	 * {% for comment in post.comments %}
168
-	 * <article class="comment">
169
-	 *   <p class="date">Posted on {{ comment.date }}:</p>
170
-	 *   <p class="comment">{{ comment.content }}</p>
171
-	 * </article>
172
-	 * {% endfor %}
173
-	 * ```
174
-	 * ```html
175
-	 * <article class="comment">
176
-	 *   <p class="date">Posted on September 28, 2015:</p>
177
-	 *   <p class="comment">Happy Birthday!</p>
178
-	 * </article>
179
-	 * ```
180
-	 * @return string
181
-	 */
182
-	public function date( $date_format = '' ) {
183
-		$df = $date_format ? $date_format : get_option('date_format');
184
-		$the_date = (string)mysql2date($df, $this->comment_date);
185
-		return apply_filters('get_comment_date ', $the_date, $df);
186
-	}
163
+    /**
164
+     * @api
165
+     * @example
166
+     * ```twig
167
+     * {% for comment in post.comments %}
168
+     * <article class="comment">
169
+     *   <p class="date">Posted on {{ comment.date }}:</p>
170
+     *   <p class="comment">{{ comment.content }}</p>
171
+     * </article>
172
+     * {% endfor %}
173
+     * ```
174
+     * ```html
175
+     * <article class="comment">
176
+     *   <p class="date">Posted on September 28, 2015:</p>
177
+     *   <p class="comment">Happy Birthday!</p>
178
+     * </article>
179
+     * ```
180
+     * @return string
181
+     */
182
+    public function date( $date_format = '' ) {
183
+        $df = $date_format ? $date_format : get_option('date_format');
184
+        $the_date = (string)mysql2date($df, $this->comment_date);
185
+        return apply_filters('get_comment_date ', $the_date, $df);
186
+    }
187 187
 
188
-	/**
189
-	 * @api
190
-	 * @example
191
-	 * ```twig
192
-	 * {% for comment in post.comments %}
193
-	 * <article class="comment">
194
-	 *   <p class="date">Posted on {{ comment.date }} at {{comment.time}}:</p>
195
-	 *   <p class="comment">{{ comment.content }}</p>
196
-	 * </article>
197
-	 * {% endfor %}
198
-	 * ```
199
-	 * ```html
200
-	 * <article class="comment">
201
-	 *   <p class="date">Posted on September 28, 2015 at 12:45 am:</p>
202
-	 *   <p class="comment">Happy Birthday!</p>
203
-	 * </article>
204
-	 * ```
205
-	 * @return string
206
-	 */
207
-	public function time( $time_format = '' ) {
208
-		$tf = $time_format ? $time_format : get_option('time_format');
209
-		$the_time = (string)mysql2date($tf, $this->comment_date);
210
-		return apply_filters('get_comment_time', $the_time, $tf);
211
-	}
188
+    /**
189
+     * @api
190
+     * @example
191
+     * ```twig
192
+     * {% for comment in post.comments %}
193
+     * <article class="comment">
194
+     *   <p class="date">Posted on {{ comment.date }} at {{comment.time}}:</p>
195
+     *   <p class="comment">{{ comment.content }}</p>
196
+     * </article>
197
+     * {% endfor %}
198
+     * ```
199
+     * ```html
200
+     * <article class="comment">
201
+     *   <p class="date">Posted on September 28, 2015 at 12:45 am:</p>
202
+     *   <p class="comment">Happy Birthday!</p>
203
+     * </article>
204
+     * ```
205
+     * @return string
206
+     */
207
+    public function time( $time_format = '' ) {
208
+        $tf = $time_format ? $time_format : get_option('time_format');
209
+        $the_time = (string)mysql2date($tf, $this->comment_date);
210
+        return apply_filters('get_comment_time', $the_time, $tf);
211
+    }
212 212
 
213
-	/**
214
-	 * @param string $field_name
215
-	 * @return mixed
216
-	 */
217
-	public function meta($field_name) {
218
-		return $this->get_meta_field($field_name);
219
-	}
213
+    /**
214
+     * @param string $field_name
215
+     * @return mixed
216
+     */
217
+    public function meta($field_name) {
218
+        return $this->get_meta_field($field_name);
219
+    }
220 220
 
221
-	/**
222
-	 * @api
223
-	 * @return bool
224
-	 */
225
-	public function is_child() {
226
-		return $this->comment_parent > 0;
227
-	}
221
+    /**
222
+     * @api
223
+     * @return bool
224
+     */
225
+    public function is_child() {
226
+        return $this->comment_parent > 0;
227
+    }
228 228
 
229
-	/**
230
-	 * @internal
231
-	 * @param int $comment_id
232
-	 * @return mixed
233
-	 */
234
-	protected function get_meta_fields($comment_id = null) {
235
-		if ($comment_id === null) {
236
-			$comment_id = $this->ID;
237
-		}
238
-		//Could not find a WP function to fetch all comment meta data, so I made one.
239
-		apply_filters('timber_comment_get_meta_pre', array(), $comment_id);
240
-		$comment_metas = get_comment_meta($comment_id);
241
-		foreach ($comment_metas as &$cm) {
242
-			if (is_array($cm) && count($cm) == 1) {
243
-				$cm = $cm[0];
244
-			}
245
-		}
246
-		$comment_metas = apply_filters('timber_comment_get_meta', $comment_metas, $comment_id);
247
-		return $comment_metas;
248
-	}
229
+    /**
230
+     * @internal
231
+     * @param int $comment_id
232
+     * @return mixed
233
+     */
234
+    protected function get_meta_fields($comment_id = null) {
235
+        if ($comment_id === null) {
236
+            $comment_id = $this->ID;
237
+        }
238
+        //Could not find a WP function to fetch all comment meta data, so I made one.
239
+        apply_filters('timber_comment_get_meta_pre', array(), $comment_id);
240
+        $comment_metas = get_comment_meta($comment_id);
241
+        foreach ($comment_metas as &$cm) {
242
+            if (is_array($cm) && count($cm) == 1) {
243
+                $cm = $cm[0];
244
+            }
245
+        }
246
+        $comment_metas = apply_filters('timber_comment_get_meta', $comment_metas, $comment_id);
247
+        return $comment_metas;
248
+    }
249 249
 
250
-	/**
251
-	 * @internal
252
-	 * @param string $field_name
253
-	 * @return mixed
254
-	 */
255
-	protected function get_meta_field($field_name) {
256
-		$value = apply_filters('timber_comment_get_meta_field_pre', null, $this->ID, $field_name, $this);
257
-		if ($value === null) {
258
-			$value = get_comment_meta($this->ID, $field_name, true);
259
-		}
260
-		$value = apply_filters('timber_comment_get_meta_field', $value, $this->ID, $field_name, $this);
261
-		return $value;
262
-	}
250
+    /**
251
+     * @internal
252
+     * @param string $field_name
253
+     * @return mixed
254
+     */
255
+    protected function get_meta_field($field_name) {
256
+        $value = apply_filters('timber_comment_get_meta_field_pre', null, $this->ID, $field_name, $this);
257
+        if ($value === null) {
258
+            $value = get_comment_meta($this->ID, $field_name, true);
259
+        }
260
+        $value = apply_filters('timber_comment_get_meta_field', $value, $this->ID, $field_name, $this);
261
+        return $value;
262
+    }
263 263
 
264
-	/**
265
-	 * Enqueue the WP threaded comments javascript,
266
-	 * and fetch the reply link for various comments.
267
-	 * @api
268
-	 * @return string
269
-	 */
270
-	public function reply_link( $reply_text = 'Reply' ) {
271
-		if ( is_singular() && comments_open() && get_option('thread_comments') ) {
272
-			wp_enqueue_script( 'comment-reply' );
273
-		}
264
+    /**
265
+     * Enqueue the WP threaded comments javascript,
266
+     * and fetch the reply link for various comments.
267
+     * @api
268
+     * @return string
269
+     */
270
+    public function reply_link( $reply_text = 'Reply' ) {
271
+        if ( is_singular() && comments_open() && get_option('thread_comments') ) {
272
+            wp_enqueue_script( 'comment-reply' );
273
+        }
274 274
 
275
-		// Get the comments depth option from the admin panel
276
-		$max_depth = get_option('thread_comments_depth');
275
+        // Get the comments depth option from the admin panel
276
+        $max_depth = get_option('thread_comments_depth');
277 277
 
278
-		// Default args
279
-		$args = array(
280
-			'add_below' => 'comment',
281
-			'respond_id' => 'respond',
282
-			'reply_text' => $reply_text,
283
-			'depth' => 1,
284
-			'max_depth' => $max_depth,
285
-		);
278
+        // Default args
279
+        $args = array(
280
+            'add_below' => 'comment',
281
+            'respond_id' => 'respond',
282
+            'reply_text' => $reply_text,
283
+            'depth' => 1,
284
+            'max_depth' => $max_depth,
285
+        );
286 286
 
287
-		return get_comment_reply_link( $args, $this->ID, $this->post_id );
288
-	}
287
+        return get_comment_reply_link( $args, $this->ID, $this->post_id );
288
+    }
289 289
 
290
-	/* AVATAR Stuff
290
+    /* AVATAR Stuff
291 291
 	======================= */
292 292
 
293
-	/**
294
-	 * @internal
295
-	 * @return string
296
-	 */
297
-	protected function avatar_email() {
298
-		$id = (int)$this->user_id;
299
-		$user = get_userdata($id);
300
-		if ($user) {
301
-			$email = $user->user_email;
302
-		} else {
303
-			$email = $this->comment_author_email;
304
-		}
305
-		return $email;
306
-	}
293
+    /**
294
+     * @internal
295
+     * @return string
296
+     */
297
+    protected function avatar_email() {
298
+        $id = (int)$this->user_id;
299
+        $user = get_userdata($id);
300
+        if ($user) {
301
+            $email = $user->user_email;
302
+        } else {
303
+            $email = $this->comment_author_email;
304
+        }
305
+        return $email;
306
+    }
307 307
 
308
-	/**
309
-	 * @internal
310
-	 * @param string $email_hash
311
-	 * @return string
312
-	 */
313
-	protected function avatar_host($email_hash) {
314
-		if (is_ssl()) {
315
-			$host = 'https://secure.gravatar.com';
316
-		} else {
317
-			if (!empty($email_hash)) {
318
-				$host = sprintf("http://%d.gravatar.com", (hexdec($email_hash[0]) % 2));
319
-			} else {
320
-				$host = 'http://0.gravatar.com';
321
-			}
322
-		}
323
-		return $host;
324
-	}
308
+    /**
309
+     * @internal
310
+     * @param string $email_hash
311
+     * @return string
312
+     */
313
+    protected function avatar_host($email_hash) {
314
+        if (is_ssl()) {
315
+            $host = 'https://secure.gravatar.com';
316
+        } else {
317
+            if (!empty($email_hash)) {
318
+                $host = sprintf("http://%d.gravatar.com", (hexdec($email_hash[0]) % 2));
319
+            } else {
320
+                $host = 'http://0.gravatar.com';
321
+            }
322
+        }
323
+        return $host;
324
+    }
325 325
 
326
-	/**
327
-	 * @internal
328
-	 * @todo  what if it's relative?
329
-	 * @param string $default
330
-	 * @param string $email
331
-	 * @param string $size
332
-	 * @param string $host
333
-	 * @return string
334
-	 */
335
-	protected function avatar_default($default, $email, $size, $host) {
336
-		if (substr($default, 0, 1) == '/') {
337
-			$default = home_url() . $default;
338
-		}
326
+    /**
327
+     * @internal
328
+     * @todo  what if it's relative?
329
+     * @param string $default
330
+     * @param string $email
331
+     * @param string $size
332
+     * @param string $host
333
+     * @return string
334
+     */
335
+    protected function avatar_default($default, $email, $size, $host) {
336
+        if (substr($default, 0, 1) == '/') {
337
+            $default = home_url() . $default;
338
+        }
339 339
 
340
-		if (empty($default)) {
341
-			$avatar_default = get_option('avatar_default');
342
-			if (empty($avatar_default)) {
343
-				$default = 'mystery';
344
-			} else {
345
-				$default = $avatar_default;
346
-			}
347
-		}
348
-		if ('mystery' == $default) {
349
-			$default = $host . '/avatar/ad516503a11cd5ca435acc9bb6523536?s=' . $size;
350
-			// ad516503a11cd5ca435acc9bb6523536 == md5('[email protected]')
351
-		} else if ('blank' == $default) {
352
-			$default = $email ? 'blank' : includes_url('images/blank.gif');
353
-		} else if (!empty($email) && 'gravatar_default' == $default) {
354
-			$default = '';
355
-		} else if ('gravatar_default' == $default) {
356
-			$default = $host . '/avatar/?s=' . $size;
357
-		} else if (empty($email) && !strstr($default, 'http://')) {
358
-			$default = $host . '/avatar/?d=' . $default . '&amp;s=' . $size;
359
-		}
360
-		return $default;
361
-	}
340
+        if (empty($default)) {
341
+            $avatar_default = get_option('avatar_default');
342
+            if (empty($avatar_default)) {
343
+                $default = 'mystery';
344
+            } else {
345
+                $default = $avatar_default;
346
+            }
347
+        }
348
+        if ('mystery' == $default) {
349
+            $default = $host . '/avatar/ad516503a11cd5ca435acc9bb6523536?s=' . $size;
350
+            // ad516503a11cd5ca435acc9bb6523536 == md5('[email protected]')
351
+        } else if ('blank' == $default) {
352
+            $default = $email ? 'blank' : includes_url('images/blank.gif');
353
+        } else if (!empty($email) && 'gravatar_default' == $default) {
354
+            $default = '';
355
+        } else if ('gravatar_default' == $default) {
356
+            $default = $host . '/avatar/?s=' . $size;
357
+        } else if (empty($email) && !strstr($default, 'http://')) {
358
+            $default = $host . '/avatar/?d=' . $default . '&amp;s=' . $size;
359
+        }
360
+        return $default;
361
+    }
362 362
 
363
-	/**
364
-	 * @internal
365
-	 * @param string $default
366
-	 * @param string $host
367
-	 * @param string $email_hash
368
-	 * @param string $size
369
-	 * @return mixed
370
-	 */
371
-	protected function avatar_out($default, $host, $email_hash, $size) {
372
-		$out = $host . '/avatar/' . $email_hash . '?s=' . $size . '&amp;d=' . urlencode($default);
373
-		$rating = get_option('avatar_rating');
374
-		if (!empty($rating)) {
375
-			$out .= '&amp;r=' . $rating;
376
-		}
377
-		return str_replace('&#038;', '&amp;', esc_url($out));
378
-	}
363
+    /**
364
+     * @internal
365
+     * @param string $default
366
+     * @param string $host
367
+     * @param string $email_hash
368
+     * @param string $size
369
+     * @return mixed
370
+     */
371
+    protected function avatar_out($default, $host, $email_hash, $size) {
372
+        $out = $host . '/avatar/' . $email_hash . '?s=' . $size . '&amp;d=' . urlencode($default);
373
+        $rating = get_option('avatar_rating');
374
+        if (!empty($rating)) {
375
+            $out .= '&amp;r=' . $rating;
376
+        }
377
+        return str_replace('&#038;', '&amp;', esc_url($out));
378
+    }
379 379
 
380 380
 }
Please login to merge, or discard this patch.