-
Notifications
You must be signed in to change notification settings - Fork 1
/
picasasilo.plugin.php
executable file
·970 lines (807 loc) · 29.9 KB
/
picasasilo.plugin.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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
<?php
/*
* Picasa API interface
*/
class PicasaAPI
{
// set query urls
protected static $QUERY_URLS = array(
'auth' => "https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2F&session=1&secure=0&next=",
'auth_sub_session' => "https://www.google.com/accounts/AuthSubSessionToken",
'picasa' => 'http://picasaweb.google.com/data/feed/api/user/default',
'picasa_secure' => 'https://picasaweb.google.com/data/feed/api/user/default');
/**
* Execute a call to the Picasa Service
*
* @param $url string The destination url
* @param $args array Optional Extra arguments
* @param $post_data Optional Post data
* @return mixed false on error or xml string
*/
public function call($url, $args = array(), $post_data = '')
{
$token = Options::get('picasa_token_' . User::identify()->id);
$default_args = array('method' => 'GET');
$args = array_merge($default_args, $args);
$request = new RemoteRequest($url, $args['method']);
// set authorisation header
$request->add_header(array("Authorization" => "AuthSub token=" . $token));
// add extra headers
if ( isset( $args['http_headers'] ) ) {
foreach($args['http_headers'] as $key => $value) {
$request->add_header(array($key => $value));
}
}
if($post_data != '')
$request->set_body($post_data);
$request->set_timeout(30);
// execute request
$result = $request->execute();
if(Error::is_error($result))
return $result;
// get the response if executed
if($request->executed())
$response = $request->get_response_body();
if(!$response)
return Error::raise('API call failure', E_USER_WARNING);
// parse the result
try
{
$xml = new SimpleXMLElement($response);
return $xml;
}
catch(Exception $e)
{
Session::error('Currently unable to connect to the Picasa API.', 'Picasa API');
return false;
}
}
/**
* Exchange AuthSub token for a session one
*
* @param string $token The AuthSub token
*/
public function exchange_token($token)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, (PicasaAPI::$QUERY_URLS['auth_sub_session']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: AuthSub token="' . $token . '"'));
$result = curl_exec($ch);
curl_close($ch);
// store the session token
$parsed_result = explode("=", $result);
Options::set('picasa_token_' . User::identify()->id, $parsed_result[1]);
}
/*
* Return query url for AuthSub request
*/
public function get_auth_url()
{
return PicasaAPI::$QUERY_URLS['auth'];
}
}
/**
* Picasa class
*
* Provides a set of operations for the Picasa API.
*/
class Picasa extends PicasaAPI
{
/**
* Return the list of albums
*
* @return string xml string representation of the albums
*/
public function get_albums()
{
$xml = $this->call(PicasaAPI::$QUERY_URLS['picasa'] . "?kind=album&alt=rss&prettyprint=true");
return $xml;
}
/**
* Return a list of photos by most recent, album or tag
*
* @param array $args Possible values are 'album', 'tag'.
* @return string xml string representation of the photos
*/
public function get_photos($args = array())
{
if(empty($args))
{
$xml = $this->call(PicasaAPI::$QUERY_URLS['picasa'] . "?kind=photo&max-results=10");
}
elseif(isset($args['album']))
{
$xml = $this->call(PicasaAPI::$QUERY_URLS['picasa'] . "/albumid/" . $args['album'] . "?prettyprint=true");
}
elseif(isset($args['tag']))
{
$xml = $this->call(PicasaAPI::$QUERY_URLS['picasa'] . "?kind=photo&tag=" . $args['tag'] . "&prettyprint=true");
}
return $xml;
}
/**
* Return the list of tags
*
* @return string xml string representation of the tags
*/
public function get_tags()
{
$xml = $this->call(PicasaAPI::$QUERY_URLS['picasa'] . "?kind=tag");
return $xml;
}
/**
* Create a new album
*
* @param array $args Album properties such as name, summary etc...
* @return mixed An xml string of the result or false on error
*/
public function create_album($args)
{
$date = explode("/", $args['date']);
// timestamp has to be multiplied by 1000 as the Picasa API requires milliseconds
// and mktime returns seconds. Also need to add 1 to the day for some reason
$timestamp = mktime(0, 0, 0, $date[1], (int)$date[0] + 1, $date[2]) * 1000;
$entry = "<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:media='http://search.yahoo.com/mrss/'
xmlns:gphoto='http://schemas.google.com/photos/2007'>
<title type='text'>" . $args['name'] . "</title>
<summary type='text'>" . $args['summary'] . "</summary>
<gphoto:location>" . $args['location'] . "</gphoto:location>
<gphoto:access>" . $args['access'] . "</gphoto:access>
<gphoto:timestamp>" . $timestamp . "</gphoto:timestamp>
<media:group>
<media:keywords>" . $args['keywords'] . "</media:keywords>
</media:group>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/photos/2007#album'></category>
</entry>";
$result = $this->call(PicasaAPI::$QUERY_URLS['picasa'],
array(
'method' => 'POST',
'http_headers' => array('Content-Type' => 'application/atom+xml')),
$entry);
if(Error::is_error($result))
return $result->get();
else
return "Album successfuly created";
}
/**
* Upload a photo
*
* @param string $file_url Temporary URL of uploaded file
* @param string $album The album id
* @param string title The title of the photo
* @return mixed An xml string of the result or false on error
*/
public function upload_photo($file_url, $album, $title, $summary)
{
$photo .= 'Media multipart posting' . "\n";
$photo .= '--END_OF_PART' . "\n";
$photo .= 'Content-Type: application/atom+xml' . "\n\n"; // need two end of lines
$photo .= '<entry xmlns="http://www.w3.org/2005/Atom">' . "\n";
$photo .= '<title>' . $title . '</title>' . "\n";
$photo .= '<summary>' . $summary . '</summary>' . "\n";
$photo .= '<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/>' . "\n";
$photo .= '</entry>' . "\n";
$photo .= '--END_OF_PART' . "\n";
$photo .= 'Content-Type: image/jpeg' . "\n\n"; // need to end of lines
$photo .= file_get_contents($file_url);
$photo .= "\n" . '--END_OF_PART--' . "\n";
$result = $this->call(PicasaAPI::$QUERY_URLS['picasa'] . "/album/" . $album,
array('method' => 'POST',
'http_headers' => array('Content-Type' => 'multipart/related; boundary="END_OF_PART"',
'MIME-version' => '1.0')),
$photo);
if(Error::is_error($result))
return $result->get();
else
return "Photo successfuly uploaded";
}
}
/**
* PicasaSilo class
*/
class PicasaSilo extends Plugin implements MediaSilo
{
const SILO_NAME = 'Picasa';
public function action_init()
{
$this->add_template('picasasilo.album', dirname(__FILE__) . '/picasasilo.album.php');
$this->add_template( 'block.picasa_album', dirname(__FILE__) . '/block.picasa_album.php' );
}
public function action_admin_header($theme)
{
$vars = Controller::get_handler_vars();
if ( $theme->admin_page == 'plugins' && isset( $vars['configure'] ) && $vars['configure'] === $this->plugin_id )
{
Stack::add('admin_stylesheet', array( $this->get_url(true) . 'admin.css', 'screen' ), 'picasa-silo-admin-css', 'admin');
}
Stack::add('admin_header_javascript', $this->get_url(true) . 'picasasilo.js', 'picasasilo', 'jquery');
// Add the AJAX callback URL.
$url = 'picasagallery.url=\''.URL::get('auth_ajax', array('context' => 'picasagallery')).'\'';
Stack::add('admin_header_javascript', $url, 'picasasilo_url', 'picasasilo');
}
/**
* Respond to Javascript callbacks
* The name of this method is action_auth_ajax_ followed by what you passed to the context parameter above.
*/
public function action_auth_ajax_picasagallery($handler)
{
// Get the data that was sent
$album = $handler->handler_vars['album'];
// Get the album content (this is almost the same code as in silo_dir())
$path_elements = explode("/", $album);
$size = Options::get('picasasilo__picasa_size');
$picasa = new Picasa();
$xml = $picasa->get_photos(array($path_elements[1] => $path_elements[2]));
foreach($xml->entry as $photo)
{
$media = $photo->children('http://search.yahoo.com/mrss/');
$props['title'] = (string)$media->group->title;
$props['description'] = (string)$media->group->description;
//Add the desired size to the url for the thumbnail
$src = (string)$photo->content->attributes()->src;
$props['thumbnail_url'] = substr($src, 0, strrpos($src, '/')) . "/$size" . substr($src, strrpos($src, '/'));
// Do the same for fullsize, Google does not return fullsize by default
$props['picasa_url'] = substr($src,0,strrpos($src,'/'))."/s0".substr($src,strrpos($src,'/'));
$imagelist[] = $props;
}
// Convert list to gallery
$gallerystring = "";
if(count($imagelist))
{
foreach($imagelist as $image)
{
$gallerystring .= "<a href='" . $image["picasa_url"] . "' rel='gallery' class='picasa_link'><img src='" . $image["thumbnail_url"] . "' class='picasa_img' alt='" . $image["description"] . "' title='" . $image["title"] . "'></a>";
}
}
// Send the response
echo json_encode($gallerystring);
}
public function silo_info()
{
if($this->is_auth())
return array('name' => self::SILO_NAME, 'icon' => URL::get_from_filesystem(__FILE__) . '/icon.png');
else
return array();
}
/**
* Return directory contents for the silo path
*
* @param string $path The path to retrieve the contents of
* @return array An array of MediaAssets describing the contents of the directory
*/
public function silo_dir($path)
{
$path_elements = explode("/", $path);
$type = $path_elements[0];
$size = Options::get('picasasilo__picasa_size');
$picasa = new Picasa();
$results = array();
switch($type)
{
case 'albums':
{
$xml = $picasa->get_albums();
foreach($xml->channel->item as $album)
{
$media = $album->children('http://search.yahoo.com/mrss/');
$photo = $album->children('http://schemas.google.com/photos/2007');
$props['title'] = (string)$album->title;
$results[] = new MediaAsset(self::SILO_NAME . '/photos/album/' . $photo->id,
true,
$props);
}
}
break;
case 'photos':
{
$xml = $picasa->get_photos(array($path_elements[1] => $path_elements[2]));
foreach($xml->entry as $photo)
{
$media = $photo->children('http://search.yahoo.com/mrss/');
$props['filetype'] = 'picasa';
$props['thumbnail_url'] = (string)$media->group->thumbnail->attributes()->url;
$props['title'] = (string)$media->group->title;
$props['description'] = (string)$media->group->description;
//$props['filetype'] = str_replace("/", "_", $photo->content->attributes()->type);
//Utils::debug($photo->content->attributes()->type);
//Add the desired size to the url
$src = (string)$photo->content->attributes()->src;
$props['url'] = substr($src,0,strrpos($src,'/'))."/$size".substr($src,strrpos($src,'/'));
// Do the same for fullsize, Google does not return fullsize by default
$props['picasa_url'] = substr($src,0,strrpos($src,'/'))."/s0".substr($src,strrpos($src,'/'));
$results[] = new MediaAsset(self::SILO_NAME . '/photos/' . $path_elements[2] . '/' . $media->group->title,
false,
$props);
}
}
break;
case 'recent':
{
$xml = $picasa->get_photos();
foreach($xml->entry as $photo)
{
$media = $photo->children('http://search.yahoo.com/mrss/');
$props['filetype'] = 'picasa';
$props['thumbnail_url'] = (string)$media->group->thumbnail->attributes()->url;
$props['title'] = (string)$media->group->title;
//$props['filetype'] = str_replace("/", "_", $photo->content->attributes()->type);
//Add the desired size to the url
$src = (string)$photo->content->attributes()->src;
$props['url'] = substr($src,0,strrpos($src,'/'))."/$size".substr($src,strrpos($src,'/'));
$props['picasa_url'] = $src;
$results[] = new MediaAsset(self::SILO_NAME . '/photos/' . $media->group->title,
false,
$props);
}
}
break;
case 'tags':
{
$xml = $picasa->get_tags();
foreach($xml->entry as $tag)
{
$props['title'] = (string)$tag->title;
$results[] = new MediaAsset(self::SILO_NAME . '/photos/tag/' . (string)$tag->title,
true,
$props);
}
}
break;
case '':
{
$results[] = new MediaAsset(self::SILO_NAME . '/albums',
true,
array('title' => 'Albums'));
$results[] = new MediaAsset(self::SILO_NAME . '/recent',
true,
array('title' => 'Recently Uploaded'));
$results[] = new MediaAsset(self::SILO_NAME . '/tags',
true,
array('title' => 'Tags'));
}
break;
}
return $results;
}
/**
* Get the file from the specified path
*
* @param string $path The path of the file to retrieve
* @param array $qualities Qualities that specify the version of the file to retrieve.
* @return MediaAsset The requested asset
*/
public function silo_get($path, $qualities = null)
{
}
/**
* Get the direct URL of the file of the specified path
*
* @param string $path The path of the file to retrieve
* @param array $qualities Qualities that specify the version of the file to retrieve.
* @return string The requested url
*/
public function silo_url($path, $qualities = null)
{
}
/**
* Create a new asset instance for the specified path
*
* @param string $path The path of the new file to create
* @return MediaAsset The requested asset
*/
public function silo_new($path)
{
}
/**
* Store the specified media at the specified path
*
* @param string $path The path of the file to retrieve
* @param MediaAsset $ The asset to store
*/
public function silo_put($path, $filedata)
{
}
/**
* Delete the file at the specified path
*
* @param string $path The path of the file to retrieve
*/
public function silo_delete($path)
{
}
/**
* Retrieve a set of highlights from this silo
* This would include things like recently uploaded assets, or top downloads
*
* @return array An array of MediaAssets to highlihgt from this silo
*/
public function silo_highlights()
{
}
/**
* Retrieve the permissions for the current user to access the specified path
*
* @param string $path The path to retrieve permissions for
* @return array An array of permissions constants (MediaSilo::PERM_READ, MediaSilo::PERM_WRITE)
*/
public function silo_permissions($path)
{
}
/*
* Add Authorisation or De-authorisation actions
*
* @param array $actions List of plugin actions
* @param int $plugin_id Plugin ID
* @return array An updated array of plugin actions
*/
public function filter_plugin_config($actions, $plugin_id)
{
if($plugin_id == $this->plugin_id)
{
$picasa_ok = $this->is_auth();
if($picasa_ok)
$actions[] = _t('De-Authorize');
else
$actions[] = _t('Authorize');
}
$actions[] = _t('Configure');
return $actions;
}
/**
* Produce a link for the media control bar that causes a specific path to be displayed
*
* @param string $path The path to display
* @param string $title The text to use for the link in the control bar
* @return string The link to create
*/
public function link_path($path, $title = '')
{
if($title == '')
$title = basename($path);
return '<a href="#" onclick="habari.media.showdir(\''.$path.'\');return false;">' . $title . '</a>';
}
/**
* Produce a link for the media control bar that causes a specific panel to be displayed
*
* @param string $path The path to pass
* @param string $path The panel to display
* @param string $title The text to use for the link in the control bar
* @return string The link to create
*/
public function link_panel($path, $panel, $title)
{
return '<a href="#" onclick="habari.media.showpanel(\''.$path.'\', \''.$panel.'\');return false;">' . $title . '</a>';
}
/**
* Provide controls for the media control bar
*
* @param array $controls Incoming controls from other plugins
* @param MediaSilo $silo An instance of a MediaSilo
* @param string $path The path to get controls for
* @param string $panelname The name of the requested panel, if none then emptystring
* @return array The altered $controls array with new (or removed) controls
*
* @todo This should really use FormUI, but FormUI needs a way to submit forms via ajax
*/
public function filter_media_controls($controls, $silo, $path, $panelname)
{
$class = __CLASS__;
if($silo instanceof $class)
{
if(User::identify()->can('upload_media'))
$controls[] = $this->link_panel(self::SILO_NAME . '/', 'upload', 'Upload');
if(User::identify()->can('create_directories'))
$controls[] = $this->link_panel(self::SILO_NAME . '/', 'new-album', 'Create Album');
// Add a link that sets the current album and then kicks off AJAX action that inserts a gallery
$controls[] = "<a href='#' onclick='picasagallery.album=\"$path\";start_picasagallery();'>Insert Gallery</a>";
}
return $controls;
}
/**
* Display the different media panels
*
* @param string $panel HTML content to be output
* @param object $silo Silo object
* @param string $path Current silo path
* @param string $panelname Curren panel name
* @return string The modified panel output
*/
public function filter_media_panels($panel, $silo, $path, $panelname)
{
$class = __CLASS__;
if($silo instanceof $class)
{
switch($panelname)
{
case 'new-album':
$fullpath = self::SILO_NAME . '/' . $path;
$form = new FormUI('picasasilo-newalbum');
$today = date('d/m/Y', time());
// first column
$form->append('static', 'col1', '<div class="column">');
$form->append('text', 'album_name', 'null:unused', 'Album name');
$form->append('textarea', 'album_summary', 'null:unused', 'Summary');
$form->append('text', 'album_date', 'null:unused', 'Date');
$form->album_date->value = $today;
$form->append('static', 'col2', '</div>');
// second column
$form->append('static', 'col3', '<div class="column">');
$form->append('text', 'album_location', 'null:unused', 'Location');
$form->append('select', 'album_visibility', 'null:unused', 'Visibility');
$form->album_visibility->options = array('public' => 'Public', 'private' => 'Anyone with the link', 'protected' => 'Private');
$form->append('static', 'col4', '</div>');
// clear columns
$form->append('static', 'colend', '<br style="clear: both">');
$form->append('submit', 'create-album', 'Create');
$form->media_panel($fullpath, $panelname, 'habari.media.forceReload();');
$form->on_success(array($this, 'create_album'));
$panel = $form->get();
return $panel;
break;
case 'upload':
if(isset($_FILES['upload_file']))
{
$panel = $this->upload_photo();
}
else
{
$fullpath = self::SILO_NAME . '/' . $path;
$action = URL::get('admin_ajax', array('context' => 'media_panel'));
$picasa = new Picasa();
// collect album names
$xml = $picasa->get_albums();
foreach($xml->channel->item as $album)
{
$title = (string)$album->title;
$options .= "<option value='" . $title . "'>" . $title . "</option>";
}
// create a form that sends the request to an IFrame (as done in the Habari Silo)
$static = <<< PICASA_UPLOAD
<form enctype="multipart/form-data" method="post" id="picasasilo-upload" target="picasa_upload_frame" action="{$action}" class="span-10" style="margin:0px auto;" target="picasa_upload_frame">
<div class="formcontrol"><input type="file" name="upload_file"></div>
<div class="formcontrol">
<label for="upload">Album:</label>
<select name="upload_album">{$options}</select>
</div>
<div class="formcontrol">
<label for="summary">Summary:</label>
<textarea name="summary"></textarea>
</div>
<div class="formcontrol"><input type="submit" name="upload" value="Upload"></div>
<input type="hidden" name="path" value="{$fullpath}">
<input type="hidden" name="panel" value="{$panelname}">
</form>
<iframe id="picasa_upload_frame" name="picasa_upload_frame" style="width:1px;height:1px;" onload="picasa_uploaded();">
</iframe>
<script type="text/javascript">
var responsedata;
function picasa_uploaded()
{
if(!jQuery('#picasa_upload_frame')[0].contentWindow)return;
var response = jQuery(jQuery('#picasa_upload_frame')[0].contentWindow.document.body).text();
if(response)
{
eval('responsedata = ' + response);
window.setTimeout(picasa_uploaded_complete, 500);
}
}
function picasa_uploaded_complete()
{
habari.media.jsonpanel(responsedata);
}
</script>
PICASA_UPLOAD;
$panel = $static;
}
return $panel;
break;
}
}
}
/**
* Create a new album based on values in the form
*
* @param $form object FormUI object
* @return string HTML that displays feedback message
*/
public function create_album($form)
{
$picasa = new Picasa();
$args['name'] = $form->album_name;
$args['summary'] = $form->album_summary;
$args['date'] = $form->album_date;
$args['location'] = $form->album_location;
$args['visibilty'] = $form->album_visibility;
$result = $picasa->create_album($args);
return "<span>" . $result . "</span>";
}
/**
* Upload a photo
*
* @param $form object FormUI object
* @return string HTML that displays feedback message
*/
public function upload_photo()
{
$temp_file = $_FILES['upload_file']['tmp_name'];
$album = $_POST['upload_album'];
$summary = $_POST['summary'];
$filename = $_FILES['upload_file']['name'];
$picasa = new Picasa();
$result = $picasa->upload_photo($temp_file, $album, $filename, $summary);
if(!$result)
return "<span>Error uploading photo</span>";
else
return "<span>Photo successfuly uploaded</span>";
}
/**
* Determine if the user has granted authorization to his/her Picasa Account
*
* @return boolean true if authorised, false otherwise
*/
public function is_auth()
{
static $authorized = null;
if(isset($authorized))
return $authorized;
$authorized = false;
$token = Options::get('picasa_token_' . User::identify()->id);
if($token != null)
$authorized = true;
return $authorized;
}
/**
* Perform plugin operation
*
* @param int $plugin_id The plugin id
* @param string $action The action to perform
*/
public function action_plugin_ui($plugin_id, $action)
{
$confirm_url = rawurlencode(URL::get('admin',
array('page' => 'plugins',
'configure' => $this->plugin_id(),
'configaction' => 'Confirm')) . '#plugin_options');
$picasa = new Picasa();
$auth_url = $picasa->get_auth_url() . $confirm_url;
$deauth_url = URL::get('admin',
array('page' => 'plugins',
'configure' => $this->plugin_id(),
'configaction' => 'De-Authorize')) . '#plugin_options';
if($plugin_id == $this->plugin_id)
{
switch($action)
{
case _t('Authorize'):
if($this->is_auth())
{
echo "<p>"._t("This installation has already been authorized to access your Picasa account.")."</p>";
echo "<p><a href='" . $deauth_url . "' title='"._t("De-Authorize")."'>"._t("De-Authorize access to your Picasa account")."</p>";
}
else
{
echo "<p>"._t("You have not authorized access to your Picasa account")."</p>";
echo "<p><a href='" . $auth_url . "' target='_blank'>"._t("Authorize")."</a> "._t("your Habari installation to access your Picasa account")."</p>";
}
break;
case 'Confirm':
{
if(!isset($_GET['token']))
{
echo "<p>"._t("Your account has not been authorized access to this installation.")."<p>";
echo "<p><a href='" . $auth_url . "' target='_blank'>"._t("Authorize")."</a> "._t("your Habari installation to access your Picasa account.")."</p>";
}
else
{
$token = $_GET['token'];
$picasa->exchange_token($token);
echo "<p>"._t("Your authorization was successful.")."</p>";
echo "<p><a href='" . $deauth_url . "' title='". _t("De-Authorize") . "'>" . _t("De-Authorize access to your Picasa account") . "</p>";
}
}
break;
case _t('De-Authorize'):
{
Options::delete('picasa_token_' . User::identify()->id, $token);
echo "<p>"._t("De-Authorization successful. This installation will no longer be able to access your Picasa account.")."</p>";
echo "<p><a href='" . $auth_url . "' title='"._t("Authorize")."' target='_blank'>"._t("Authorize")."</a> "._t("your Habari installation to access your Picasa account")."</p>";
}
break;
case _t('Configure') :
$ui = new FormUI( strtolower( get_class( $this ) ) );
$ui->append( 'select', 'picasa_size','option:picasasilo__picasa_size', _t( 'Default size for images in Posts:' ) );
//I did not _t() the following as it should be replaced. Picasa supports all sizes up to original size.
$ui->picasa_size->options = array( 's75' => 'Square (75x75)', 's100' => 'Thumbnail (100px)', 's240' => 'Small (240px)', 's500' => 'Medium (500px)', 's1024' => 'Large (1024px)', '' => 'Original Size' );
$ui->append('submit', 'save', _t( 'Save' ) );
$ui->set_option('success_message', _t('Options saved'));
$ui->out();
break;
}
}
}
function cache_albumlist()
{
if(Cache::has(array(__CLASS__, "picasa_albumids")) && Cache::has(array(__CLASS__, "picasa_albumlinks"))) return;
$picasa = new Picasa();
$picasa->userid = $post->user_id;
$xml = $picasa->get_albums();
foreach($xml->channel->item as $album)
{
$albumids[(string)$album->title] = (string)$album->children('http://schemas.google.com/photos/2007')->id;
$albumlinks[(string)$album->title] = (string)$album->link;
Cache::set(array(__CLASS__, "picasa_albumids"), $albumids, 3600 * 12);
Cache::set(array(__CLASS__, "picasa_albumlinks"), $albumlinks, 3600 * 12);
}
}
public function filter_post_picasa_images($out, $post)
{
try
{
// Check if there is any album requested
$albumname = $post->info->picasa_album;
if(!isset($albumname) || empty($albumname))
return $out;
// TODO: Size to post options
$size = "s200";
//Check if the photos are already cached first because then we're already finished
if(Cache::has(array(__CLASS__, "album_$albumname")))
return Cache::get(array(__CLASS__, "album_$albumname"));
$picasa = new Picasa();
$picasa->userid = $post->user_id;
$this->cache_albumlist();
$albumids = Cache::get(array(__CLASS__, "picasa_albumids"));
$albumlinks = Cache::get(array(__CLASS__, "picasa_albumlinks"));
// Get the actual photos
$xml = $picasa->get_photos(array("album" => $albumids[$albumname]));
foreach($xml->entry as $photo)
{
// Warum drei URLs?
// TODO: Irgendwas mit thumbnails machen
$media = $photo->children('http://search.yahoo.com/mrss/');
// $props['thumbnail_url'] = (string)$media->group->thumbnail->attributes()->url;
$props['title'] = (string)$media->group->title;
$props['description'] = (string)$media->group->description;
$src = (string)$photo->content->attributes()->src;
$props['url'] = substr($src,0,strrpos($src,'/'))."/$size".substr($src,strrpos($src,'/'));
$props['picasa_url'] = $src;
$photos[] = $props;
}
// TODO: Add cache expire option to the admin interface
Cache::set(array(__CLASS__, "album_$albumname"), $photos, 60 * 60 * 24);
}
catch(exception $e) { $photos = array(_t(vsprintf("No photos available or an error occured. Sometimes reloading the page helps. %s", $e), __CLASS__)); }
return $photos;
}
public function filter_post_picasalink($out, $post)
{
$this->cache_albumlist();
$albumlinks = Cache::get(array(__CLASS__, "picasa_albumlinks"));
return $albumlinks[$post->info->picasa_album];
}
public function action_form_publish($form, $post, $context)
{
$form->insert('tags', 'text', 'picasa_album', 'null:null', _t('Picasa album to assign to this post', __CLASS__), 'admincontrol_textArea');
$form->picasa_album->value = $post->info->picasa_album;
$form->picasa_album->template = 'admincontrol_text';
}
// Save the fields
public function action_publish_post( $post, $form )
{
$post->info->picasa_album = $form->picasa_album->value;
}
// Delete album list cache when a new post with album is published
public function action_post_publish_after( $post )
{
$albumname = $post->info->picasa_album;
if(!isset($albumname) || empty($albumname))
return $out;
Cache::expire(array(__CLASS__, "picasa_albumids"));
Cache::expire(array(__CLASS__, "picasa_albumlinks"));
}
}
?>