forked from pekastel/flickr-pick-a-picture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pick-a-pic.php
847 lines (746 loc) · 31.3 KB
/
pick-a-pic.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
<?php
/*
Plugin Name: Flickr - Pick a Picture
Plugin URI: http://www.3nodos.com.ar
Description: Lets you pick a Creative Commons picture from Flickr and use it anywhere you want on your WordPress installation.
Version: 1.2.6
Author: Pablo Adrian Castillo
Author URI: http://www.3nodos.com.ar
License: GPL2
*/
/* Copyright 2014 Pablo Adrián Castillo (email : [email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* This plugin is based on the work of http://wordpress.org/extend/plugins/flickr-picture-find-and-attribute/ by pgogy, OpenAttribute (http://politicsinspires.org/)
*
* TODO:
* - Make the flickr api_key a global parameter on the Options page.
* - Add Search options
*
**/
// Plugin path
define( 'PICAPICK_PATH', plugin_dir_path(__FILE__) );
require_once(PICAPICK_PATH . "/admin/settings.php");
/**
* Add the new tab to media upload window
*
* @param string $tabs, the original lists of tabs
* @return string $tabs, the modified lists of tabs
**/
add_filter('media_upload_tabs', 'pac_pickapic_upload_tab');
function pac_pickapic_upload_tab($tabs) {
$tabs['pickapictab'] = 'Freie Fotos';
return $tabs;
}
/**
* Main tab handler
*
* @param noting.
* @return nothing.
*
* Note that wp_iframe() will add the css for the "media" page when the callback
* function begins with "media".
**/
function media_upload_pac_pickapictab() {
// Two things can happen here, either we need to show the first page after the search button has been hit
// or we need to display the paginated results for previous searches.
if ( ( isset( $_POST['pac_pickapic_search_term'] ) && isset( $_POST['pac_pickapic_results_per_page'] ) ) ||
( isset( $_GET['pac_pickapic_search_term'] ) && isset( $_GET['pac_pickapic_results_per_page'] ) && isset( $_GET['paged'] )) &&
! isset( $_POST['pac_pickapic_choose'] ) ) {
// Displays the search results
$search_term = sanitize_text_field($_REQUEST['pac_pickapic_search_term'],'');
$results = absint( $_REQUEST['pac_pickapic_results_per_page'] );
$paged = 0;
if ( isset( $_REQUEST['paged'] ) ) {
$paged = absint( $_REQUEST['paged'] );
}
wp_iframe( 'media_pac_pickapic_search_results', $search_term, $results, $paged );
return;
} else if ( isset( $_POST['pac_pickapic_choose'] ) ) {
// A picture has been selected so we must download it from flickr and show it to the user.
//TODO: Implement better error handling
check_admin_referer( 'pac_pickapic_nonce', 'pac_pickapic_nonce_field' );
//Show the selected image using get_media_item
wp_iframe( 'media_pac_pickapic_final_form' );
return;
} else if ( isset( $_POST['send'] ) ) {
// Check the final form arguments generated by get_media_item() function
// and if they are ok the image will be inserted to the editor
media_upload_form_handler();
}
wp_iframe( 'media_pac_pickapic_search' );
}
add_action('media_upload_pickapictab', 'media_upload_pac_pickapictab');
/**
* Loads the initial content in the media upload frame.
*
* @param noting.
* @return nothing
**/
function media_pac_pickapic_search() {
media_upload_header();
pac_pickapic_search_form( __("Flickr - Pick a Picture",'pickapic') );
}
/**
* Displays the search form.
*
* @param string $form_title.
* @param int $page, the page index.
* @return nothing
**/
function pac_pickapic_search_form( $form_title ) {
global $type;
$post_id = absint($_REQUEST['post_id']);
$form_action_url = admin_url("media-upload.php?type=$type&tab=pickapictab&post_id=$post_id");
$form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type );
?>
<script type="text/javascript">
//<![CDATA[
var flickrSearch = {
search: function() {
var f = document.forms['pickapic-media-form'];
if ( '' == f.pac_pickapic_search_term.value ) {
return false;
}
jQuery("#pickapic-media-form").submit();
jQuery("#tb_search_form").fadeTo(500,0.2);
},
validate: function() {
var f = document.forms['pickapic-media-form'];
if ( '' == f.pac_pickapic_search_term.value ) {
document.getElementById('search_button').style.color = '#bbb';
} else {
document.getElementById('search_button').style.color = '#333';
}
},
handleKeyPress: function(e) {
var f = document.forms['pickapic-media-form'];
if (e.keyCode == 13 && '' == f.pac_pickapic_search_term.value ) {
e.preventDefault();
}
}
}
//]]>
</script>
<form id="pickapic-media-form" enctype="multipart/form-data" action="<?php echo esc_html($form_action_url); ?>" class="media-upload-form type-form validate" method="post">
<h3 class="media-title"> <?php echo $form_title; ?> </h3>
<?php wp_nonce_field( 'pac_pickapic_nonce', 'pac_pickapic_nonce_field' ); ?>
<table id="tb_search_form" class="describe"><tbody>
<tr>
<th valign="top" scope="row" class="label" style="width:130px;">
<span class="alignleft"><label for="insertonly[searchterms]"><?php _e('Suche', 'pickapic'); ?> </label></span>
<span class="alignright"><abbr id="status_img" title="required" class="required">*</abbr></span>
</th>
<td class="field"><input id="pac_pickapic_search_term" name="pac_pickapic_search_term" value="" type="text" aria-required="true" onkeydown="flickrSearch.handleKeyPress(event);" onkeyup="flickrSearch.validate();" onblur="flickrSearch.validate();"></td>
</tr>
<tr><td></td><td class="help"> <?php _e('Sucht nach Fotos deren Titel, Beschreibung oder Schlagwörter den Suchbegriff enthalten. Wenn Du Begriffe ausschließen willst, musst du ihnen ein - voransetzen.', 'pickapic'); ?></td></tr>
<tr>
<th valign="top" scope="row" class="label">
<span class="alignleft"><label for="insertonly[results]"> <?php _e('Resultate pro Seite', 'pickapic'); ?> </label></span>
</th>
<td class="field">
<select id="pac_pickapic_results_per_page" name="pac_pickapic_results_per_page">
<option value="14">14</option>
<option value="28">28</option>
<option value="63">63</option>
<option value="250" selected="selected">250</option>
</select>
</td>
</tr>
<tr class="image-only">
<td></td>
<td>
<input type="button" id="search_button" class="button" style="color:#bbb;" value=<?php _e( "Suchen", 'pickapic' ); ?> onclick="flickrSearch.search()" name="pac_pickapic_search" />
</td>
</tr>
</tbody></table>
</form>
<?php
}
/*
* Simple wrapper to fetch a url using curl or file_get_contents
*/
function pac_pickapic_get_url($url){
// Test if curl_init is defined.
if ( function_exists('curl_init') ) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
} elseif ( ini_get('allow_url_fopen') ) {
$r = file_get_contents($url);
} else {
return new WP_Error('failure', __("I'm sorry but this plugin needs the CURL module or the 'allow_url_fopen' option enabled, please check your php.ini.",'pickapic'));
}
return $r;
}
/**
* Invokes the flickr.photos.search method api and returns the search
* results
*
* @param string $search_term.
* @param int $results_per_page.
* @param int $page, the page index.
* @return array With the results
**/
function pac_pickapic_flickr_search($search_term, $results_per_page, $page) {
// Arguments to search flickr using their api.
$params = array(
'per_page' => $results_per_page,
'page' => $page,
//'safe_search' => 1,
//'content_type' => 1, // Search for photos only
//'privacy_filter' => 1, // Search for public photos
'sort' => pac_pickapic_get_option('flickrsort'),
'license' => pac_pickapic_get_option('flickrlicenses'),
'text' => $search_term,
'api_key' => pac_pickapic_get_option('flickrapikey'),
'method' => 'flickr.photos.search',
'format' => 'php_serial'
);
$encoded_params = array();
foreach ($params as $k => $v){
$encoded_params[] = urlencode($k).'='.urlencode($v);
}
$url = "https://api.flickr.com/services/rest/?".implode('&', $encoded_params);
$r = pac_pickapic_get_url($url);
if ( is_wp_error($r) ) {
pac_pickapic_show_error($r);
return $r;
}
$rsp_obj = unserialize($r);
$error = pac_pickapic_flickr_answer_ok($rsp_obj);
if ( is_wp_error($error) ){
return $error;
}
return $rsp_obj;
}
/**
* Displays the search results
*
* @param string $search_term.
* @param int $results_per_page.
* @param int $page, the page index.
* @return nothing
**/
function media_pac_pickapic_search_results( $search_term, $results_per_page = 12, $page = 0 ) {
global $type;
$post_id = absint($_REQUEST['post_id']);
media_upload_header();
$rsp_obj = pac_pickapic_flickr_search($search_term, $results_per_page, $page);
?>
<?php
if ( is_wp_error($rsp_obj) ) {
pac_pickapic_show_error($rsp_obj);
return;
}
$pictures = $rsp_obj['photos']['photo'];
if ( count($pictures) ){
echo '<h3 class="media-title" style="padding:1em 0 0 10px; margin:0px;">'.__('Ergebnis für: ','pickapic').'"'.$search_term.'"</h3>';
} else {
echo '<h3 class="media-title" style="padding:1em 0 0 10px; margin:0px;">'.__('Nichts gefunden zu: ','pickapic').'"'.$search_term.'"</h3>';
}
// The total amount of results retuned by flickr. Please have in mind that Flickr will
// return at most 4.000 results for any given search query.
$total = $rsp_obj['photos']['total'] >= 4000? 4000 : $rsp_obj['photos']['total'];
$form_action_url = admin_url("media-upload.php?type=$type&tab=pickapictab&post_id=$post_id");
$form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type );
?>
<link rel="stylesheet" href="<?php echo plugin_dir_url( dirname(__FILE__).'/pick-a-pic.php' ) . 'fancybox/jquery.fancybox-1.3.4.css'; ?>" type="text/css" media="screen" />
<script type="text/javascript">
//<![CDATA[
jQuery(function() {
jQuery('.frm_image_result').submit(function() {
jQuery("#frm_image_results").fadeTo(500,0.2);
});
jQuery('.page-numbers').click(function() {
jQuery("#frm_image_results").fadeTo(500,0.2);
});
jQuery("a#single_image").fancybox();
});
//]]>
</script>
<?php
// Build navigation
$paged = isset($_GET['paged']) ? intval($_GET['paged']) : 0;
if ( $paged < 1 ) {
$paged = 1;
}
$page_links = paginate_links( array(
'base' => add_query_arg( // Append 'paged' 'search_term' and 'results_per_page' to $_GET for further navigation
array( 'paged' => '%#%',
'pac_pickapic_search_term' => urlencode($search_term),
'pac_pickapic_results_per_page' => $results_per_page ) ),
'format' => '',
'prev_text' => __('«', 'pickapic'),
'next_text' => __('»', 'pickapic'),
'total' => ceil($total / absint($results_per_page) ),
'current' => $paged
));
// Displays navigation
if ( $page_links ) {
echo "<div class='tablenav' style='margin-right:14px'>\n";
echo "\t<div class='tablenav-pages'>";
echo "\t<span class=\"displaying-num\">$total ".__('Results', 'pickapic')."</span>";
echo $page_links;
echo "\t</div>\n";
echo "</div>\n";
}
?>
<div id="frm_image_results" style="margin-left:13px">
<?php
while($pic = array_shift($pictures)){
$flickr_farm_thumb_url = 'http://farm'.$pic['farm'].'.static.flickr.com/'.$pic['server'].'/'.$pic['id'].'_'.$pic['secret'].'_m.jpg';
$flickr_farm_url = 'http://farm'.$pic['farm'].'.static.flickr.com/'.$pic['server'].'/'.$pic['id'].'_'.$pic['secret'].'.jpg';
?>
<div style="float:left; position:relative; width:240px; height:285px; background-color:#eee; border:0px solid #aaa; margin:1px; margin-bottom:10px;">
<form class="frm_image_result" style="width:240px; margin:0 auto; text-align:center;" enctype="multipart/form-data" action="<?php esc_html($form_action_url);?>" class="media-upload-form type-form validate" method="post">
<?php wp_nonce_field( 'pac_pickapic_nonce', 'pac_pickapic_nonce_field' ); ?>
<a id="single_image" href="<?php echo $flickr_farm_url;?>">
<img style="margin-top:5px" src="<?php echo $flickr_farm_thumb_url; ?>"/>
</a>
<br />
<input name="pac_pickapic_data" type="hidden" value="<?php echo urlencode(serialize($pic)); ?>"/>
<input type="hidden" name="pac_pickapic_flickr_id" value="<?php echo $pic['id']; ?>"/>
<input type="submit" class="button" name="pac_pickapic_choose" value="<?php _e( "Choose", 'pickapic' ); ?>" style="margin-top:10px" />
</form>
</div>
<?php
}
?>
</div> <!-- #frm_image_results -->
<?php
// Displays navigation
if ( $page_links ) {
echo "<div class='tablenav' style='margin-right:14px'>\n";
echo "\t<div class='tablenav-pages'>";
echo "\t<span class=\"displaying-num\">$total ".__('Results', 'pickapic')."</span>";
echo $page_links;
echo "\t</div>\n";
echo "</div>\n";
}
pac_pickapic_search_form( __("New search", 'pickapic') );
}
/**
* Invokes the flickr.photo.getInfo method api and returns the owner
* url and the title of the image
*
* @param int $photo_id. The flickr photo_id
* @return flickr_info array
**/
function pac_pickapic_flickr_getInfo( $photo_id ) {
$params = array(
'photo_id' => $photo_id,
'api_key' => pac_pickapic_get_option('flickrapikey'),
'method' => 'flickr.photos.getInfo',
'format' => 'php_serial'
);
$encoded_params = array();
foreach ($params as $k => $v){
$encoded_params[] = urlencode($k).'='.urlencode($v);
}
# call the API and decode the response
$url = "https://api.flickr.com/services/rest/?".implode('&', $encoded_params);
$r = pac_pickapic_get_url($url);
$rsp_obj = unserialize($r);
$pic_data = urldecode($_POST['pac_pickapic_data']);
$pic = unserialize($pic_data);
if( $rsp_obj['photo']['owner']['realname'] == "" ){
$flickr_info['owner'] = $rsp_obj['photo']['owner']['username'];
}else{
$flickr_info['owner'] = $rsp_obj['photo']['owner']['realname'];
}
// Removes [] if found in content since this would colide with shortcode content
$flickr_info['owner'] = preg_replace( array( '/\[/i', '/\]/i' ), "", $flickr_info['owner'] );
$a = array_shift($rsp_obj['photo']['urls']['url']);
// Extracts de flickr url of the image.
$flickr_info['url'] = $a['_content'];
$flickr_info['title'] = $rsp_obj['photo']['title']['_content'];
$flickr_info['license'] = $rsp_obj['photo']['license'];
return $flickr_info;
}
/**
* Invokes the flickr.photo.getSizes method api and returns the image url
* defined in plugin options.
*
* @param int $photo_id. The
* @return photo_url string
**/
function pac_pickapic_flickr_getSizes( $photo_id ) {
$params = array(
'photo_id' => $photo_id,
'api_key' => pac_pickapic_get_option('flickrapikey'),
'method' => 'flickr.photos.getSizes',
'format' => 'php_serial'
);
$encoded_params = array();
foreach ($params as $k => $v){ $encoded_params[] = urlencode($k).'='.urlencode($v); }
$url = "https://api.flickr.com/services/rest/?".implode('&', $encoded_params);
$r = pac_pickapic_get_url($url);
$rsp_obj = unserialize($r);
$error = pac_pickapic_flickr_answer_ok($rsp_obj);
if ( is_wp_error($error) ){
return $error;
}
$sizes = $rsp_obj['sizes']['size'];
while($size = array_shift($sizes)){
if ( $size['label'] == pac_pickapic_get_option('flickrimgsize') ) {
return $size['source'];
} // If the image size defined is not available use PICKAPIC_DEFAULT_FLICKR_IMG_SIZE instead.
elseif ( $size['label'] == PICKAPIC_DEFAULT_FLICKR_IMG_SIZE ) {
$default_size = $size['source'];
}
}
return $default_size;
}
/**
* Verifies the flickr answer, returns WP_Error on failure | true on success.
**/
function pac_pickapic_flickr_answer_ok( $rsp_obj ){
if ($rsp_obj['stat'] != 'ok'){
// XXX Validate the first argument to wp_error
return new WP_Error($rsp_obj['code'], $rsp_obj['message']);
}
return true;
}
/**
* Download the picture selected, associate it to the post and displays the
* final form using get_media_item()
*
* @param noting.
* @return noting.
**/
function media_pac_pickapic_final_form() {
global $type, $wp_version;
$post_id = absint($_REQUEST['post_id']);
$form_action_url = admin_url("media-upload.php?type=$type&tab=pickapictab&post_id=$post_id");
$form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type );
media_upload_header();
$flickr_info = pac_pickapic_flickr_getInfo($_POST['pac_pickapic_flickr_id']);
$photo_url = pac_pickapic_flickr_getSizes($_POST['pac_pickapic_flickr_id']);
if ( is_wp_error($photo_url) ) {
pac_pickapic_show_error($rsp_obj);
return;
}
?>
<form id="pickapic-media-form" enctype="multipart/form-data" action="<?php echo esc_html($form_action_url); ?>" class="media-upload-form type-form validate" method="post">
<?php wp_nonce_field('media-form'); ?>
<div id="media-items">
<?php
if ( version_compare( $wp_version, '3.4', '<') ) {
$excerpt = __('Foto: '.$flickr_info['owner'], 'pickapic');
} else {
$excerpt = __('Foto: ', 'pickapic')."<a href='".$flickr_info['url']."' target='_blank'>".$flickr_info['owner']."</a>";
$show_license = pac_pickapic_get_option('flickrshowlicense');
if ( $show_license ) {
$flickr_licenses = unserialize(PICKAPIC_FLICKR_LICENSES);
$excerpt .= ' - '.$flickr_licenses[$flickr_info['license']];
}
}
$attachment_id = pac_pickapic_media_sideload_image($photo_url, $post_id, '', array(
'post_title' => __($flickr_info['title'], 'pickapic'),
'post_excerpt' => $excerpt,
),
$flickr_info['url'],
$flickr_info['owner']
);
if ( is_wp_error($attachment_id) ) {
echo '<div id="media-upload-error">'.esc_html($attachment_id->get_error_message()).'</div></div>';
} else {
// Render the form content using get_media_item
$args = array(
'toggle' => false,
'show_title' => true
);
echo get_media_item( $attachment_id, $args );
}
?>
</div>
</form>
<?php
}
/**
* Almost similar to media_sideload_image (from wp-admin/includes/media.php)
* the only difference is that this one returns attachment_id
* instead of an piece of html code like the original function
*
* Download an image from the specified URL and attach it to a post.
*
* @param string $url The URL of the image to download
* @param int $post_id The post ID the media is to be associated with
* @param string $desc Optional. Description of the image
* @param array $post_data Optional. Allows to overwrite some of the attachment information
* @return string|WP_Error int|attachment_id
*/
function pac_pickapic_media_sideload_image($url, $post_id, $desc = null, $post_data = array(), $photo_url, $owner ) {
global $wp_version;
if ( ! empty($url) ) {
// Download url to temp location
$tmp = download_url( $url );
// Set variables for storage
// fix file filename for query strings
preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$attachment_id = media_handle_sideload( $file_array, $post_id, $desc, $post_data );
// If error storing permanently, unlink and return WP_Error
if ( is_wp_error($attachment_id) ) {
@unlink($file_array['tmp_name']);
} else {
/**
* Since WP 3.4 there is no need to save the caption metadata since we have
* native support for html in captions.
**/
if ( version_compare( $wp_version, '3.4', '<') ) {
// Set the attachment flickr metadata.
update_post_meta( $attachment_id, 'pac_flickr_image_url', addslashes($photo_url) );
update_post_meta( $attachment_id, 'pac_flickr_image_owner', addslashes($owner) );
}
}
return $attachment_id;
}
}
/**
* Rewrites the image caption to add flickr credits using the information
* saved on meta the fields of the image.
*
* @param string $a not really needed here
* @param string $attr The shortcode attributes
* @param string $content The shortcode content
* @return string HTML representing the shortcode.
**/
function pac_pickapic_custom_img_caption_shortcode( $a , $attr, $content = null) {
global $wp_version;
/**
* Since WP 3.4 there is no need to overwrite this method since no we have native
* support for html on image captions
**/
if ( version_compare( $wp_version, '3.4', '>=') ) {
return;
}
extract(shortcode_atts(array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
), $attr));
if ( 1 > (int) $width ) {
return $content;
}
// Extracts the attachment id
$attachment_id = intval(preg_replace("/attachment_/","",$id));
// Get the attachment flickr metadata
$flickr_photo_url = get_post_meta($attachment_id, 'pac_flickr_image_url', true);
$flickr_owner = get_post_meta($attachment_id, 'pac_flickr_image_owner', true);
if ( empty($flickr_photo_url) || empty($flickr_owner) ) {
// Don't change anything if the flickr url or the owner are empty
return;
}
// Rebuild the caption by adding credits to original flickr image owner
$caption = __('Foto: ', 'pickapic')."<a href='".$flickr_photo_url."' target='_blank'>".$flickr_owner."</a>";
if ( $id ) {
$id = 'id="' . esc_attr($id) . '" ';
}
return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
. do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
}
//Add the filter to override the standard caption shortcode
add_filter( 'img_caption_shortcode', 'pac_pickapic_custom_img_caption_shortcode', 10, 3 );
/**
* This is mostly the same function found in media.php at WP core with the only
* difference being that the caption of each image will include the flickr
* credits, maintaining the link to the original image in flickr.
*
*
* @param string $val
* @param array $attr Attributes of the shortcode.
* @return string HTML content to display gallery.
*/
function pac_pickapic_gallery_shortcode($val, $attr) {
global $post, $wp_version;
/**
* Since WP 3.4 there is no need to overwrite this method since no we have native
* support for html on image captions
**/
if ( version_compare( $wp_version, '3.4', '>=') ) {
return;
}
static $instance = 0;
$instance++;
// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
if ( isset( $attr['orderby'] ) ) {
$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
if ( !$attr['orderby'] )
unset( $attr['orderby'] );
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ( 'RAND' == $order )
$orderby = 'none';
if ( !empty($include) ) {
$include = preg_replace( '/[^0-9,]+/', '', $include );
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
} elseif ( !empty($exclude) ) {
$exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}
if ( empty($attachments) )
return '';
if ( is_feed() ) {
$output = "\n";
foreach ( $attachments as $att_id => $attachment )
$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
return $output;
}
$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';
$selector = "gallery-{$instance}";
$gallery_style = $gallery_div = '';
if ( apply_filters( 'use_default_gallery_style', true ) )
$gallery_style = "
<style type='text/css'>
#{$selector} {
margin: auto;
}
#{$selector} .gallery-item {
float: {$float};
margin-top: 10px;
text-align: center;
width: {$itemwidth}%;
}
#{$selector} img {
border: 2px solid #cfcfcf;
}
#{$selector} .gallery-caption {
margin-left: 0;
}
</style>
<!-- see gallery_shortcode() in wp-includes/media.php -->";
$size_class = sanitize_html_class( $size );
$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
$output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
$i = 0;
foreach ( $attachments as $id => $attachment ) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
if ( $captiontag && trim($attachment->post_excerpt) ) {
$flickr_photo_url = get_post_meta($id, 'pac_flickr_image_url', true);
$flickr_owner = get_post_meta($id, 'pac_flickr_image_owner', true);
if ( empty($flickr_photo_url) || empty($flickr_owner) ) {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
} else {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>
" .
__('Foto: ', 'pickapic')."<a href='".$flickr_photo_url."' target='_blank'>".$flickr_owner."</a>".
"</{$captiontag}>";
}
}
$output .= "</{$itemtag}>";
if ( $columns > 0 && ++$i % $columns == 0 )
$output .= '<br style="clear: both" />';
}
$output .= "
<br style='clear: both;' />
</div>\n";
return $output;
}
add_filter('post_gallery', 'pac_pickapic_gallery_shortcode', 10, 2);
/**
* Adds the pick a pic icon to the media bar.
*
* @param it editor_id.
* @return noting.
**/
function pac_pickapic_media_buttons($editor_id = '') {
$img = '<img src="' . esc_url( plugin_dir_url( dirname(__FILE__).'/pick-a-pic.php' ).'icoWPcam.png' ) . '" width="15" height="15" />';
// TODO: postear esto!!
echo '<a href="' . add_query_arg('tab','pickapictab', esc_url( get_upload_iframe_src() ) ). '" class="thickbox add_media" id="' . esc_attr( $editor_id ) . '-add_media" title="' . esc_attr__( 'Flickr - pick a pic', 'pickapic' ) . '" onclick="return false;">' . sprintf( $img ) . ' Freies Foto suchen</a>';
}
//add_action( 'media_buttons', 'pac_pickapic_media_buttons', 20 );
/**
* Load language file.
*
* @param noting.
* @return noting.
**/
function pac_pickapic_load_textdomain() {
load_plugin_textdomain( 'pickapic', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
add_action('plugins_loaded', 'pac_pickapic_load_textdomain');
/**
* Add the fancybox jquery plugin to WP backend.
**/
function pac_pickapic_custom_scripts() {
wp_enqueue_script('fancybox', (plugin_dir_url( dirname(__FILE__).'/pick-a-pic.php' ) . 'fancybox/jquery.fancybox-1.3.4.pack.js' ) , '', '', true);
}
add_action('admin_enqueue_scripts', 'pac_pickapic_custom_scripts');
/**
* Display error messages
**/
function pac_pickapic_show_error($rsp_obj){
?>
<h3 class="media-title" style="padding:1em 0 0 10px; margin:0px;"> <?php _e('Flickr - Pick a Picture','pickapic');?> </h3>
<h4 class="media-title" style="padding:1em 0 0 10px; margin:0px;"> <?php echo __('Error: ','pickapic').$rsp_obj->get_error_message(); ?> </h4>
<?php
pac_pickapic_search_form( __("Try a new search", 'pickapic') );
}
/**
* Simple wrapper to get_option()
**/
function pac_pickapic_get_option($name){
$options = get_option('pac_pickapic_options',array(
'flickrimgsize' => PICKAPIC_DEFAULT_FLICKR_IMG_SIZE,
'flickrapikey' => PICKAPIC_FLICKR_API_KEY,
'flickrlicenses' => PICKAPIC_FLICKR_LICENSES_SELECTED,
'flickrsort' => PICKAPIC_FLICKR_SORT,
'flickrshowlicense' => 1
));
return $options[$name];
}
?>