PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/types/embedded/includes/fields/image.php

https://bitbucket.org/cisash/fananeen
PHP | 1057 lines | 768 code | 98 blank | 191 comment | 174 complexity | 918bfa0196111097c7c18c82e0792224 MD5 | raw file
  1. <?php
  2. add_filter('wpcf_fields_type_image_value_get', 'wpcf_fields_image_value_filter');
  3. add_filter('wpcf_fields_type_image_value_save', 'wpcf_fields_image_value_filter');
  4. add_filter('upload_dir', 'wpcf_fields_image_uploads_realpath');
  5. /**
  6. * Register data (called automatically).
  7. * @return type
  8. */
  9. function wpcf_fields_image() {
  10. return array(
  11. 'id' => 'wpcf-image',
  12. 'title' => __('Image', 'wpcf'),
  13. 'description' => __('Image', 'wpcf'),
  14. 'validate' => array('required'),
  15. 'meta_box_js' => array(
  16. 'wpcf-jquery-fields-file' => array(
  17. 'inline' => 'wpcf_fields_file_meta_box_js_inline',
  18. ),
  19. 'wpcf-jquery-fields-image' => array(
  20. 'inline' => 'wpcf_fields_image_meta_box_js_inline',
  21. ),
  22. ),
  23. 'inherited_field_type' => 'file',
  24. );
  25. }
  26. /**
  27. * Renders inline JS.
  28. */
  29. function wpcf_fields_image_meta_box_js_inline() {
  30. global $post;
  31. ?>
  32. <script type="text/javascript">
  33. //<![CDATA[
  34. jQuery(document).ready(function(){
  35. wpcf_formfield = false;
  36. jQuery('.wpcf-fields-image-upload-link').live('click', function() {
  37. wpcf_formfield = '#'+jQuery(this).attr('id')+'-holder';
  38. tb_show('<?php
  39. echo esc_js(__('Upload image', 'wpcf'));
  40. ?>', 'media-upload.php?post_id=<?php echo $post->ID; ?>&type=image&wpcf-fields-media-insert=1&TB_iframe=true');
  41. return false;
  42. });
  43. });
  44. //]]>
  45. </script>
  46. <?php
  47. }
  48. /**
  49. * Editor callback form.
  50. */
  51. function wpcf_fields_image_editor_callback() {
  52. wp_enqueue_style('wpcf-fields-image',
  53. WPCF_EMBEDDED_RES_RELPATH . '/css/basic.css', array(), WPCF_VERSION);
  54. wp_enqueue_script('jquery');
  55. // Get field
  56. $field = wpcf_admin_fields_get_field($_GET['field_id']);
  57. if (empty($field)) {
  58. _e('Wrong field specified', 'wpcf');
  59. die();
  60. }
  61. // Get post_ID
  62. $post_ID = false;
  63. if (isset($_POST['post_id'])) {
  64. $post_ID = intval($_POST['post_id']);
  65. } else {
  66. $http_referer = explode('?', $_SERVER['HTTP_REFERER']);
  67. if (isset($http_referer[1])) {
  68. parse_str($http_referer[1], $http_referer);
  69. if (isset($http_referer['post'])) {
  70. $post_ID = $http_referer['post'];
  71. }
  72. }
  73. }
  74. // Get attachment
  75. $image = false;
  76. $attachment_id = false;
  77. if ($post_ID) {
  78. $image = get_post_meta($post_ID,
  79. wpcf_types_get_meta_prefix($field) . $field['slug'], true);
  80. if (!empty($image)) {
  81. // Get attachment by guid
  82. global $wpdb;
  83. $attachment_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts}
  84. WHERE post_type = 'attachment' AND guid=%s",
  85. $image));
  86. }
  87. }
  88. // Get post type
  89. $post_type = '';
  90. if ($post_ID) {
  91. $post_type = get_post_type($post_ID);
  92. } else {
  93. $http_referer = explode('?', $_SERVER['HTTP_REFERER']);
  94. parse_str($http_referer[1], $http_referer);
  95. if (isset($http_referer['post_type'])) {
  96. $post_type = $http_referer['post_type'];
  97. }
  98. }
  99. $image_data = wpcf_fields_image_get_data($image);
  100. if (!in_array($post_type, array('view', 'view-template'))) {
  101. // We must ignore errors here and treat image as outsider
  102. if (!empty($image_data['error'])) {
  103. $image_data['is_outsider'] = 1;
  104. $image_data['is_attachment'] = 0;
  105. }
  106. } else {
  107. if (!empty($image_data['error'])) {
  108. $image_data['is_outsider'] = 0;
  109. $image_data['is_attachment'] = 0;
  110. }
  111. }
  112. $last_settings = wpcf_admin_fields_get_field_last_settings($_GET['field_id']);
  113. $form = array();
  114. $form['#form']['callback'] = 'wpcf_fields_image_editor_submit';
  115. if ($attachment_id) {
  116. $form['preview'] = array(
  117. '#type' => 'markup',
  118. '#markup' => '<div style="position:absolute; margin-left:300px;">'
  119. . wp_get_attachment_image($attachment_id, 'thumbnail') . '</div>',
  120. );
  121. }
  122. $alt = '';
  123. $title = '';
  124. if ($attachment_id) {
  125. $alt = trim(strip_tags(get_post_meta($attachment_id,
  126. '_wp_attachment_image_alt', true)));
  127. $attachment_post = get_post($attachment_id);
  128. if (!empty($attachment_post)) {
  129. $title = trim(strip_tags($attachment_post->post_title));
  130. } else if (!empty($alt)) {
  131. $title = $alt;
  132. }
  133. if (empty($alt)) {
  134. $alt = $title;
  135. }
  136. }
  137. $form['title'] = array(
  138. '#type' => 'textfield',
  139. '#title' => __('Image title', 'wpcf'),
  140. '#description' => __('Title text for the image, e.g. &#8220;The Mona Lisa&#8221;',
  141. 'wpcf'),
  142. '#name' => 'title',
  143. '#value' => isset($last_settings['title']) ? $last_settings['title'] : $title,
  144. );
  145. $form['alt'] = array(
  146. '#type' => 'textfield',
  147. '#title' => __('Alternate Text', 'wpcf'),
  148. '#description' => __('Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;',
  149. 'wpcf'),
  150. '#name' => 'alt',
  151. '#value' => isset($last_settings['alt']) ? $last_settings['alt'] : $alt,
  152. );
  153. $form['alignment'] = array(
  154. '#type' => 'radios',
  155. '#title' => __('Alignment', 'wpcf'),
  156. '#name' => 'alignment',
  157. '#default_value' => isset($last_settings['alignment']) ? $last_settings['alignment'] : 'none',
  158. '#options' => array(
  159. __('None', 'wpcf') => 'none',
  160. __('Left', 'wpcf') => 'left',
  161. __('Center', 'wpcf') => 'center',
  162. __('Right', 'wpcf') => 'right',
  163. ),
  164. );
  165. $form['class'] = array(
  166. '#type' => 'textfield',
  167. '#title' => __('Class', 'wpcf'),
  168. '#name' => 'class',
  169. '#value' => isset($last_settings['class']) ? $last_settings['class'] : '',
  170. );
  171. $form['style'] = array(
  172. '#type' => 'textfield',
  173. '#title' => __('Style', 'wpcf'),
  174. '#name' => 'style',
  175. '#value' => isset($last_settings['style']) ? $last_settings['style'] : '',
  176. );
  177. $attributes_outsider = array();
  178. $attributes_attachment = array();
  179. $fetch_remote = (bool) wpcf_get_settings('images_remote');
  180. if ($image_data['is_outsider'] && !$fetch_remote) {
  181. $form['notice'] = array(
  182. '#type' => 'markup',
  183. '#markup' => '<div class="message error" style="margin:0 0 20px 0;"><p>'
  184. . sprintf(__('Remote image resize is currently disabled, so Types will only resize images that you upload. To change, go to the %sTypes settings page%s.',
  185. 'wpcf'),
  186. '<a href="' . admin_url('admin.php?page=wpcf-custom-settings#types-image-settings') . '" target="_blank">',
  187. '</a>')
  188. . '</p></div>',
  189. );
  190. $attributes_outsider = array('disabled' => 'disabled');
  191. $attributes_attachment = array('disabled' => 'disabled');
  192. }
  193. if ($image_data['is_attachment']) {
  194. $default_value = isset($last_settings['image-size']) ? $last_settings['image-size'] : 'thumbnail';
  195. } else if (!$image_data['is_outsider']) {
  196. $default_value = 'wpcf-custom';
  197. } else {
  198. $default_value = 'thumbnail';
  199. }
  200. $form['size'] = array(
  201. '#type' => 'radios',
  202. '#title' => __('Pre-defined sizes', 'wpcf'),
  203. '#name' => 'image-size',
  204. '#default_value' => $default_value,
  205. '#options' => array(
  206. 'thumbnail' => array('#title' => __('Thumbnail', 'wpcf'), '#value' => 'thumbnail', '#attributes' => $attributes_attachment),
  207. 'medium' => array('#title' => __('Medium', 'wpcf'), '#value' => 'medium', '#attributes' => $attributes_attachment),
  208. 'large' => array('#title' => __('Large', 'wpcf'), '#value' => 'large', '#attributes' => $attributes_attachment),
  209. 'full' => array('#title' => __('Full Size', 'wpcf'), '#value' => 'full', '#attributes' => $attributes_attachment),
  210. 'wpcf-custom' => array('#title' => __('Custom size', 'wpcf'), '#value' => 'wpcf-custom', '#attributes' => $attributes_outsider),
  211. ),
  212. );
  213. $form['toggle-open'] = array(
  214. '#type' => 'markup',
  215. '#markup' => '<div id="wpcf-toggle" style="display:none;">',
  216. );
  217. $form['width'] = array(
  218. '#type' => 'textfield',
  219. '#title' => __('Width', 'wpcf'),
  220. '#description' => __('Specify custom width', 'wpcf'),
  221. '#name' => 'width',
  222. '#value' => isset($last_settings['width']) ? $last_settings['width'] : '',
  223. '#suffix' => '&nbsp;px',
  224. '#attributes' => $attributes_outsider,
  225. );
  226. $form['height'] = array(
  227. '#type' => 'textfield',
  228. '#title' => __('Height', 'wpcf'),
  229. '#description' => __('Specify custom height', 'wpcf'),
  230. '#name' => 'height',
  231. '#value' => isset($last_settings['height']) ? $last_settings['height'] : '',
  232. '#suffix' => '&nbsp;px',
  233. '#attributes' => $attributes_outsider,
  234. );
  235. $form['proportional'] = array(
  236. '#type' => 'checkbox',
  237. '#title' => __('Keep proportional', 'wpcf'),
  238. '#name' => 'proportional',
  239. '#default_value' => 1,
  240. '#attributes' => $attributes_outsider,
  241. );
  242. $form['toggle-close'] = array(
  243. '#type' => 'markup',
  244. '#markup' => '</div>',
  245. '#attributes' => $attributes_outsider,
  246. );
  247. if ($post_ID) {
  248. $form['post_id'] = array(
  249. '#type' => 'hidden',
  250. '#name' => 'post_id',
  251. '#value' => $post_ID,
  252. );
  253. }
  254. $form['submit'] = array(
  255. '#type' => 'submit',
  256. '#name' => 'submit',
  257. '#value' => __('Insert shortcode', 'wpcf'),
  258. '#attributes' => array('class' => 'button-primary'),
  259. );
  260. $f = wpcf_form('wpcf-form', $form);
  261. wpcf_admin_ajax_head('Insert email', 'wpcf');
  262. echo '<form method="post" action="">';
  263. echo $f->renderForm();
  264. echo '</form>';
  265. ?>
  266. <script type="text/javascript">
  267. //<![CDATA[
  268. jQuery(document).ready(function(){
  269. jQuery('input[name="image-size"]').change(function(){
  270. if (jQuery(this).val() == 'wpcf-custom') {
  271. jQuery('#wpcf-toggle').slideDown();
  272. } else {
  273. jQuery('#wpcf-toggle').slideUp();
  274. }
  275. });
  276. if (jQuery('input[name="image-size"]:checked').val() == 'wpcf-custom') {
  277. jQuery('#wpcf-toggle').show();
  278. }
  279. });
  280. //]]>
  281. </script>
  282. <?php
  283. wpcf_admin_ajax_footer();
  284. }
  285. /**
  286. * Editor callback form submit.
  287. */
  288. function wpcf_fields_image_editor_submit() {
  289. $add = '';
  290. if (!empty($_POST['alt'])) {
  291. $add .= ' alt="' . strval($_POST['alt']) . '"';
  292. }
  293. if (!empty($_POST['title'])) {
  294. $add .= ' title="' . strval($_POST['title']) . '"';
  295. }
  296. $size = !empty($_POST['image-size']) ? $_POST['image-size'] : false;
  297. if ($size == 'wpcf-custom') {
  298. if (!empty($_POST['width'])) {
  299. $add .= ' width="' . intval($_POST['width']) . '"';
  300. }
  301. if (!empty($_POST['height'])) {
  302. $add .= ' height="' . intval($_POST['height']) . '"';
  303. }
  304. if (!empty($_POST['proportional'])) {
  305. $add .= ' proportional="true"';
  306. }
  307. } else if (!empty($size)) {
  308. $add .= ' size="' . $size . '"';
  309. }
  310. if (!empty($_POST['alignment'])) {
  311. $add .= ' align="' . $_POST['alignment'] . '"';
  312. }
  313. if (!empty($_POST['class'])) {
  314. $add .= ' class="' . $_POST['class'] . '"';
  315. }
  316. if (!empty($_POST['style'])) {
  317. $add .= ' style="' . $_POST['style'] . '"';
  318. }
  319. $field = wpcf_admin_fields_get_field($_GET['field_id']);
  320. if (!empty($field)) {
  321. $shortcode = wpcf_fields_get_shortcode($field, $add);
  322. wpcf_admin_fields_save_field_last_settings($_GET['field_id'], $_POST);
  323. echo editor_admin_popup_insert_shortcode_js($shortcode);
  324. die();
  325. }
  326. }
  327. /**
  328. * View function.
  329. *
  330. * @param type $params
  331. */
  332. function wpcf_fields_image_view($params) {
  333. $output = '';
  334. $alt = false;
  335. $title = false;
  336. $class = array();
  337. $style = array();
  338. // Get image data
  339. $image_data = wpcf_fields_image_get_data($params['field_value']);
  340. //print_r($image_data);
  341. //print_r($params);
  342. // Display error to admin only
  343. if (!empty($image_data['error'])) {
  344. if (current_user_can('administrator')) {
  345. return '<div style="padding:10px;background-color:Red;color:#FFFFFF;">'
  346. . 'Types: ' . $image_data['error'] . '</div>';
  347. }
  348. return $params['field_value'];
  349. }
  350. // Set alt
  351. if (isset($params['alt'])) {
  352. $alt = $params['alt'];
  353. }
  354. // Set title
  355. if (isset($params['title'])) {
  356. $title = $params['title'];
  357. }
  358. // Set attachment class
  359. if (!empty($params['size'])) {
  360. $class[] = 'attachment-' . $params['size'];
  361. }
  362. // Set align class
  363. if (!empty($params['align']) && $params['align'] != 'none') {
  364. $class[] = 'align' . $params['align'];
  365. }
  366. if (!empty($params['class'])) {
  367. $class[] = $params['class'];
  368. }
  369. if (!empty($params['style'])) {
  370. $style[] = $params['style'];
  371. }
  372. // Pre-configured size (use WP function)
  373. if ($image_data['is_attachment'] && !empty($params['size'])) {
  374. //print_r('is_attachment');
  375. if (isset($params['url']) && $params['url'] == 'true') {
  376. //print_r('is_url');
  377. $image_url = wp_get_attachment_image_src($image_data['is_attachment'],
  378. $params['size']);
  379. if (!empty($image_url[0])) {
  380. $output = $image_url[0];
  381. } else {
  382. $output = $params['field_value'];
  383. }
  384. } else {
  385. //print_r('is_not_url');
  386. $output = wp_get_attachment_image($image_data['is_attachment'],
  387. $params['size'], false,
  388. array(
  389. 'class' => implode(' ', $class),
  390. 'style' => implode(' ', $style),
  391. 'alt' => $alt,
  392. 'title' => $title
  393. )
  394. );
  395. }
  396. } else { // Custom size
  397. //print_r('custom_size');
  398. $width = !empty($params['width']) ? intval($params['width']) : null;
  399. $height = !empty($params['height']) ? intval($params['height']) : null;
  400. $crop = (!empty($params['proportional']) && $params['proportional'] == 'true') ? false : true;
  401. //////////////////////////
  402. // If width and height are not set then check the size parameter.
  403. // This handles the case when the image is not an attachment.
  404. if (!$width && !$height && !empty($params['size'])) {
  405. //print_r('no_width_no_height_and_size');
  406. switch ($params['size']) {
  407. case 'thumbnail':
  408. $width = get_option('thumbnail_size_w');
  409. $height = get_option('thumbnail_size_h');
  410. if (empty($params['proportional'])) {
  411. $crop = get_option('thumbnail_crop');
  412. }
  413. break;
  414. case 'medium':
  415. $width = get_option('medium_size_w');
  416. $height = get_option('medium_size_h');
  417. break;
  418. case 'large':
  419. $width = get_option('large_size_w');
  420. $height = get_option('large_size_h');
  421. break;
  422. }
  423. }
  424. // Check if image is outsider
  425. if (!$image_data['is_outsider']) {
  426. //print_r('Not is_outsider');
  427. $resized_image = wpcf_fields_image_resize_image(
  428. $params['field_value'], $width, $height, 'relpath', false,
  429. $crop
  430. );
  431. if (!$resized_image) {
  432. //print_r('Not resized image');
  433. $resized_image = $params['field_value'];
  434. } else {
  435. //print_r('resized image add to lib');
  436. // Add to library
  437. $image_abspath = wpcf_fields_image_resize_image(
  438. $params['field_value'], $width, $height, 'abspath',
  439. false, $crop
  440. );
  441. $add_to_library = wpcf_get_settings('add_resized_images_to_library');
  442. if ($add_to_library) {
  443. //print_r('add to lib');
  444. global $wpdb;
  445. $attachment_exists = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts}
  446. WHERE post_type = 'attachment' AND guid=%s",
  447. $resized_image));
  448. if (empty($attachment_exists)) {
  449. // Add as attachment
  450. $wp_filetype = wp_check_filetype(basename($image_abspath),
  451. null);
  452. $attachment = array(
  453. 'post_mime_type' => $wp_filetype['type'],
  454. 'post_title' => preg_replace('/\.[^.]+$/', '',
  455. basename($image_abspath)),
  456. 'post_content' => '',
  457. 'post_status' => 'inherit',
  458. 'guid' => $resized_image,
  459. );
  460. global $post;
  461. $attach_id = wp_insert_attachment($attachment,
  462. $image_abspath, $post->ID);
  463. // you must first include the image.php file
  464. // for the function wp_generate_attachment_metadata() to work
  465. require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  466. $attach_data = wp_generate_attachment_metadata($attach_id,
  467. $image_abspath);
  468. wp_update_attachment_metadata($attach_id, $attach_data);
  469. }
  470. }
  471. }
  472. } else {
  473. //print_r('is_outsider');
  474. $resized_image = $params['field_value'];
  475. }
  476. if (isset($params['url']) && $params['url'] == 'true') {
  477. //print_r('return');
  478. return $resized_image;
  479. }
  480. //print_r('output');
  481. $output = '<img alt="';
  482. $output .= $alt !== false ? $alt : $resized_image;
  483. $output .= '" title="';
  484. $output .= $title !== false ? $title : $resized_image;
  485. $output .= '"';
  486. $output .=!empty($params['onload']) ? ' onload="' . $params['onload'] . '"' : '';
  487. $output .=!empty($class) ? ' class="' . implode(' ', $class) . '"' : '';
  488. $output .=!empty($style) ? ' style="' . implode(' ', $style) . '"' : '';
  489. $output .= ' src="' . $resized_image . '" />';
  490. }
  491. return $output;
  492. }
  493. /**
  494. * Resizes image using WP image_resize() function.
  495. *
  496. * Caches return data if called more than one time in one pass.
  497. *
  498. * @staticvar array $cached Caches calls in one pass
  499. * @param <type> $url_path Full URL path (works only with images on same domain)
  500. * @param <type> $width
  501. * @param <type> $height
  502. * @param <type> $refresh Set to true if you want image re-created or not cached
  503. * @param <type> $crop Set to true if you want apspect ratio to be preserved
  504. * @param string $suffix Optional (default 'wpcf_$widthxheight)
  505. * @param <type> $dest_path Optional (defaults to original image)
  506. * @param <type> $quality
  507. * @return array
  508. */
  509. function wpcf_fields_image_resize_image($url_path, $width = 300, $height = 200,
  510. $return = 'relpath', $refresh = FALSE, $crop = TRUE, $suffix = '',
  511. $dest_path = NULL, $quality = 75) {
  512. if (empty($url_path)) {
  513. //print_r('return url path');
  514. return $url_path;
  515. }
  516. // Get image data
  517. $image_data = wpcf_fields_image_get_data($url_path);
  518. if (empty($image_data['fullabspath']) || !empty($image_data['error'])) {
  519. //print_r('return url path no full or error');
  520. return $url_path;
  521. }
  522. // Set cache
  523. static $cached = array();
  524. $cache_key = md5($url_path . $width . $height . intval($crop) . $suffix . $dest_path);
  525. // Check if cached in this call
  526. if (!$refresh && isset($cached[$cache_key][$return])) {
  527. //print_r('return cached');
  528. return $cached[$cache_key][$return];
  529. }
  530. $width = intval($width);
  531. $height = intval($height);
  532. // Get size of new file
  533. $size = @getimagesize($image_data['fullabspath']);
  534. if (!$size) {
  535. //print_r('not size');
  536. return $url_path;
  537. }
  538. list($orig_w, $orig_h, $orig_type) = $size;
  539. $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop);
  540. if (!$dims) {
  541. //print_r('not dims');
  542. return $url_path;
  543. }
  544. list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
  545. // Set suffix
  546. if (empty($suffix)) {
  547. $suffix = 'wpcf_' . $dst_w . 'x' . $dst_h;
  548. } else {
  549. $suffix .= '_wpcf_' . $dst_w . 'x' . $dst_h;
  550. }
  551. $image_data['extension'] = in_array(strtolower($image_data['extension']),
  552. array('gif', 'png', 'jpeg')) ? $image_data['extension'] : 'jpg';
  553. $image_relpath = $image_data['relpath'] . '/' . $image_data['image_name'] . '-'
  554. . $suffix . '.' . $image_data['extension'];
  555. $image_abspath = $image_data['abspath'] . DIRECTORY_SEPARATOR
  556. . $image_data['image_name'] . '-' . $suffix . '.'
  557. . $image_data['extension'];
  558. // Check if already resized
  559. if (!$refresh && file_exists($image_abspath)) {
  560. //print_r('file exists');
  561. // Cache it
  562. $cached[$cache_key]['relpath'] = $image_relpath;
  563. $cached[$cache_key]['abspath'] = $image_abspath;
  564. return $return == 'relpath' ? $image_relpath : $image_abspath;
  565. }
  566. // If original file don't exists
  567. if (!file_exists($image_data['fullabspath'])) {
  568. //print_r('not file exists');
  569. return $url_path;
  570. }
  571. // Resize image
  572. $resized_image = @wpcf_image_resize(
  573. $image_data['fullabspath'], $width, $height, $crop, $suffix,
  574. $dest_path, $quality
  575. );
  576. // Check if error
  577. if (is_wp_error($resized_image)) {
  578. //print_r('resized wp error');
  579. //print_r($resized_image);
  580. return $url_path;
  581. }
  582. $image_abspath = $resized_image;
  583. // Cache it
  584. $cached[$cache_key]['relpath'] = $image_relpath;
  585. $cached[$cache_key]['abspath'] = $image_abspath;
  586. return $return == 'relpath' ? $image_relpath : $image_abspath;
  587. }
  588. /**
  589. * Gets all necessary data for processed image.
  590. *
  591. * @global type $wpdb
  592. * @param type $image
  593. * @return type
  594. */
  595. function wpcf_fields_image_get_data($image) {
  596. global $current_user;
  597. // Check if already cached
  598. static $cache = array();
  599. if (isset($cache[md5($image)])) {
  600. return $cache[md5($image)];
  601. }
  602. // Defaults
  603. $data = array(
  604. 'image' => basename($image),
  605. 'image_name' => '',
  606. 'extension' => '',
  607. 'abspath' => '',
  608. 'relpath' => dirname($image),
  609. 'fullabspath' => '',
  610. 'fullrelpath' => $image,
  611. 'is_outsider' => 1,
  612. 'is_in_upload_path' => 0,
  613. 'is_attachment' => 0,
  614. 'error' => '',
  615. );
  616. // Strip GET vars
  617. $image = strtok($image, '?');
  618. // Basic URL check
  619. if (strpos($image, 'http') != 0) {
  620. return array('error' => sprintf(__('Image %s not valid', 'wpcf'), $image));
  621. }
  622. // Extension check
  623. $data['extension'] = pathinfo($image, PATHINFO_EXTENSION);
  624. if (!in_array(strtolower($data['extension']),
  625. array('jpg', 'jpeg', 'gif', 'png'))) {
  626. return array('error' => sprintf(__('Image %s not valid', 'wpcf'), $image));
  627. }
  628. // Parse URL
  629. $parsed = parse_url($image);
  630. $parsed_wp = parse_url(get_site_url());
  631. if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i',
  632. $parsed['host'], $regs)) {
  633. $parsed['domain'] = $regs['domain'];
  634. } else {
  635. $parsed['domain'] = $parsed['host'];
  636. }
  637. if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i',
  638. $parsed_wp['host'], $regs)) {
  639. $parsed_wp['domain'] = $regs['domain'];
  640. } else {
  641. $parsed_wp['domain'] = $parsed_wp['host'];
  642. }
  643. // Check if it's on same domain
  644. $data['is_outsider'] = $parsed['domain'] == $parsed_wp['domain'] ? 0 : 1;
  645. if (!$data['is_outsider']) {
  646. // Check if it's in upload path
  647. $upload_dir = wp_upload_dir();
  648. $upload_dir_parsed = parse_url($upload_dir['baseurl']);
  649. // Determine if in upload path and calculate abspath
  650. //
  651. // This works for regular installation and main blog on multisite
  652. if ((!is_multisite() || is_main_site())
  653. && strpos($parsed['path'], $upload_dir_parsed['path']) === 0) {
  654. $data['is_in_upload_path'] = 1;
  655. if (!empty($parsed_wp['path'])) {
  656. $data['abspath'] = dirname(str_replace($parsed_wp['path'] . '/',
  657. ABSPATH, $parsed['path']));
  658. } else {
  659. $data['abspath'] = ABSPATH . dirname($parsed['path']);
  660. }
  661. $data['fullabspath'] = $data['abspath'] . DIRECTORY_SEPARATOR . basename($image);
  662. //
  663. // Check Multisite
  664. } else if (is_multisite() && !is_main_site()) {
  665. if (strpos($parsed['path'], $upload_dir_parsed['path']) === 0) {
  666. $data['is_in_upload_path'] = 1;
  667. }
  668. $multisite_parsed = explode('/files/', $parsed['path']);
  669. if (isset($multisite_parsed[1])) {
  670. $data['is_in_upload_path'] = 1;
  671. $data['abspath'] = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . dirname($multisite_parsed[1]);
  672. $data['fullabspath'] = $data['abspath'] . DIRECTORY_SEPARATOR . basename($image);
  673. }
  674. }
  675. // Manual upload
  676. if (empty($data['abspath'])) {
  677. if (!empty($parsed_wp['path'])) {
  678. $data['abspath'] = dirname(str_replace($parsed_wp['path'] . '/',
  679. ABSPATH, $parsed['path']));
  680. } else {
  681. $data['abspath'] = ABSPATH . dirname($parsed['path']);
  682. }
  683. $data['fullabspath'] = $data['abspath'] . DIRECTORY_SEPARATOR . basename($image);
  684. }
  685. // Check if it's attachment
  686. global $wpdb;
  687. $data['is_attachment'] = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts}
  688. WHERE post_type = 'attachment' AND guid=%s",
  689. $image));
  690. }
  691. // Set remote if enabled
  692. if ($data['is_outsider'] && wpcf_get_settings('images_remote')) {
  693. $remote = wpcf_fields_image_get_remote($image);
  694. if (!is_wp_error($remote)) {
  695. $data['is_outsider'] = 0;
  696. $data['is_in_upload_path'] = 1;
  697. $data['abspath'] = dirname($remote['abspath']);
  698. $data['fullabspath'] = $remote['abspath'];
  699. $data['image'] = $remote['relpath'];
  700. $data['relpath'] = dirname($remote['relpath']);
  701. $data['fullrelpath'] = $remote['relpath'];
  702. }
  703. }
  704. // Set rest of data
  705. $data['image_name'] = basename($data['image'], '.' . $data['extension']);
  706. $abspath_realpath = realpath($data['abspath']);
  707. $data['abspath'] = $abspath_realpath ? $abspath_realpath : $data['abspath'];
  708. $fullabspath_realpath = realpath($data['fullabspath']);
  709. $data['fullabspath'] = $fullabspath_realpath ? $fullabspath_realpath : $data['fullabspath'];
  710. //$user = wp_get_current_user();
  711. if (isset($current_user->user_email) && $current_user->user_email == 'jocics@gmail.comrr') {
  712. echo '<pre>';
  713. print_r($parsed);
  714. print_r($parsed_wp);
  715. print_r($upload_dir);
  716. print_r($upload_dir_parsed);
  717. print_r($data);
  718. die();
  719. }
  720. // Cache it
  721. $cache[md5($data['image'])] = $data;
  722. return $data;
  723. }
  724. /**
  725. * Strips GET vars from value.
  726. *
  727. * @param type $value
  728. * @return type
  729. */
  730. function wpcf_fields_image_value_filter($value) {
  731. return strtok($value, '?');
  732. }
  733. /**
  734. * Gets cache directory.
  735. *
  736. * @return \WP_Error
  737. */
  738. function wpcf_fields_image_get_cache_directory($suppress_filters = false) {
  739. $wp_upload_dir = wp_upload_dir();
  740. if (!empty($wp_upload_dir['error'])) {
  741. return new WP_Error('wpcf_image_cache_dir', $wp_upload_dir['error']);
  742. } else {
  743. $cache_dir = $wp_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'types_image_cache';
  744. }
  745. if (!$suppress_filters) {
  746. $cache_dir = apply_filters('types_image_cache_dir', $cache_dir);
  747. if (!wp_mkdir_p($cache_dir)) {
  748. return new WP_Error('wpcf_image_cache_dir', sprintf(__('Image cache directory %s could not be created',
  749. 'wpcf'),
  750. '<strong>' . $cache_dir . '</strong>'));
  751. }
  752. }
  753. return $cache_dir;
  754. }
  755. function wpcf_image_http_request_timeout($timeout) {
  756. return 20;
  757. }
  758. /**
  759. * Fetches remote images.
  760. *
  761. * @param type $url
  762. * @return \WP_Error
  763. */
  764. function wpcf_fields_image_get_remote($url) {
  765. $refresh = false;
  766. // Set directory
  767. $cache_dir = wpcf_fields_image_get_cache_directory();
  768. if (is_wp_error($cache_dir)) {
  769. return $cache_dir;
  770. }
  771. // Validate image
  772. $extension = pathinfo($url, PATHINFO_EXTENSION);
  773. if (!in_array(strtolower($extension), array('jpg', 'jpeg', 'gif', 'png'))) {
  774. return new WP_Error('wpcf_image_cache_not_valid', sprintf(__('Image %s not valid',
  775. 'wpcf'), $url));
  776. }
  777. $image = $cache_dir . DIRECTORY_SEPARATOR . md5($url) . '.' . $extension;
  778. // Refresh if necessary
  779. $refresh_time = intval(wpcf_get_settings('images_remote_cache_time'));
  780. if ($refresh_time != 0 && file_exists($image)) {
  781. $time_modified = filemtime($image);
  782. if (time() - $time_modified > $refresh_time * 60 * 60) {
  783. $refresh = true;
  784. $files = glob($cache_dir . DIRECTORY_SEPARATOR . md5($url) . "-*");
  785. if ($files) {
  786. foreach ($files as $filename) {
  787. @unlink($filename);
  788. }
  789. }
  790. }
  791. }
  792. // Check if image is fetched
  793. if ($refresh || !file_exists($image)) {
  794. // fetch the remote url and write it to the placeholder file
  795. add_filter('http_request_timeout', 'wpcf_image_http_request_timeout',
  796. 10, 1);
  797. $resp = wp_remote_get($url);
  798. remove_filter('http_request_timeout', 'wpcf_image_http_request_timeout',
  799. 10, 1);
  800. // make sure the fetch was successful
  801. if ($resp['response']['code'] != '200') {
  802. return new WP_Error('wpcf_image_cache_file_error', sprintf(__('Remote server returned error response %1$d %2$s',
  803. 'wpcf'),
  804. esc_html($resp['response']),
  805. get_status_header_desc($resp['response'])));
  806. }
  807. if (strlen($resp['body']) != $resp['headers']['content-length']) {
  808. return new WP_Error('wpcf_image_cache_file_error', __('Remote file is incorrect size',
  809. 'wpcf'));
  810. }
  811. $out_fp = fopen($image, 'w');
  812. if (!$out_fp) {
  813. return new WP_Error('wpcf_image_cache_file_error', __('Could not create cache file',
  814. 'wpcf'));
  815. }
  816. fwrite($out_fp, $resp['body']);
  817. fclose($out_fp);
  818. $max_size = (int) apply_filters('import_attachment_size_limit', 0);
  819. $filesize = filesize($image);
  820. if (!empty($max_size) && $filesize > $max_size) {
  821. @unlink($image);
  822. return new WP_Error('wpcf_image_cache_file_error', sprintf(__('Remote file is too large, limit is %s',
  823. 'wpcf'), size_format($max_size)));
  824. }
  825. }
  826. return array(
  827. 'abspath' => $image,
  828. 'relpath' => icl_get_file_relpath($image) . '/' . basename($image)
  829. );
  830. }
  831. /**
  832. * Clears remote image cache.
  833. *
  834. * @param type $action
  835. */
  836. function wpcf_fields_image_clear_cache($cache_dir = null, $action = 'outdated') {
  837. if (is_null($cache_dir)) {
  838. $cache_dir = wpcf_fields_image_get_cache_directory();
  839. }
  840. $refresh_time = intval(wpcf_get_settings('images_remote_cache_time'));
  841. if ($refresh_time == 0 && $action != 'all') {
  842. return true;
  843. }
  844. foreach (glob($cache_dir . DIRECTORY_SEPARATOR . "*") as $filename) {
  845. if ($action == 'all') {
  846. @unlink($filename);
  847. } else {
  848. $time_modified = filemtime($filename);
  849. if (time() - $time_modified > $refresh_time * 60 * 60) {
  850. @unlink($filename);
  851. // Clear resized images
  852. $path = pathinfo($filename);
  853. foreach (glob($path['dirname'] . DIRECTORY_SEPARATOR . $path['filename'] . "-*") as $resized) {
  854. @unlink($resized);
  855. }
  856. }
  857. }
  858. }
  859. }
  860. /**
  861. * Filters upload paths (to fix Windows issues).
  862. *
  863. * @param type $args
  864. * @return type
  865. */
  866. function wpcf_fields_image_uploads_realpath($args) {
  867. $fixes = array('path', 'subdir', 'basedir');
  868. foreach ($fixes as $fix) {
  869. if (isset($args[$fix])) {
  870. $args[$fix] = realpath($args[$fix]);
  871. }
  872. }
  873. return $args;
  874. }
  875. /**
  876. * i18n friendly version of basename(), copy from wp-includes/formatting.php to solve bug with windows
  877. *
  878. * @since 3.1.0
  879. *
  880. * @param string $path A path.
  881. * @param string $suffix If the filename ends in suffix this will also be cut off.
  882. * @return string
  883. */
  884. function wpcf_basename( $path, $suffix = '' ) {
  885. return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
  886. }
  887. /**
  888. * Copy from wp-includes/media.php
  889. * Scale down an image to fit a particular size and save a new copy of the image.
  890. *
  891. * The PNG transparency will be preserved using the function, as well as the
  892. * image type. If the file going in is PNG, then the resized image is going to
  893. * be PNG. The only supported image types are PNG, GIF, and JPEG.
  894. *
  895. * Some functionality requires API to exist, so some PHP version may lose out
  896. * support. This is not the fault of WordPress (where functionality is
  897. * downgraded, not actual defects), but of your PHP version.
  898. *
  899. * @since 2.5.0
  900. *
  901. * @param string $file Image file path.
  902. * @param int $max_w Maximum width to resize to.
  903. * @param int $max_h Maximum height to resize to.
  904. * @param bool $crop Optional. Whether to crop image or resize.
  905. * @param string $suffix Optional. File suffix.
  906. * @param string $dest_path Optional. New image file path.
  907. * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
  908. * @return mixed WP_Error on failure. String with new destination path.
  909. */
  910. function wpcf_image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
  911. $image = wp_load_image( $file );
  912. if ( !is_resource( $image ) )
  913. return new WP_Error( 'error_loading_image', $image, $file );
  914. $size = @getimagesize( $file );
  915. if ( !$size )
  916. return new WP_Error('invalid_image', __('Could not read image size'), $file);
  917. list($orig_w, $orig_h, $orig_type) = $size;
  918. $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
  919. if ( !$dims )
  920. return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
  921. list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
  922. $newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );
  923. imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
  924. // convert from full colors to index colors, like original PNG.
  925. if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
  926. imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );
  927. // we don't need the original in memory anymore
  928. imagedestroy( $image );
  929. // $suffix will be appended to the destination filename, just before the extension
  930. if ( !$suffix )
  931. $suffix = "{$dst_w}x{$dst_h}";
  932. $info = pathinfo($file);
  933. $dir = $info['dirname'];
  934. $ext = $info['extension'];
  935. $name = wpcf_basename($file, ".$ext"); // use fix here for windows
  936. if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
  937. $dir = $_dest_path;
  938. $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
  939. if ( IMAGETYPE_GIF == $orig_type ) {
  940. if ( !imagegif( $newimage, $destfilename ) )
  941. return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
  942. } elseif ( IMAGETYPE_PNG == $orig_type ) {
  943. if ( !imagepng( $newimage, $destfilename ) )
  944. return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
  945. } else {
  946. // all other formats are converted to jpg
  947. if ( 'jpg' != $ext && 'jpeg' != $ext )
  948. $destfilename = "{$dir}/{$name}-{$suffix}.jpg";
  949. if ( !imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) ) )
  950. return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
  951. }
  952. imagedestroy( $newimage );
  953. // Set correct file permissions
  954. $stat = stat( dirname( $destfilename ));
  955. $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
  956. @ chmod( $destfilename, $perms );
  957. return $destfilename;
  958. }