File: V1_0.pm

package info (click to toggle)
libvuser-google-api-perl 1.0.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 348 kB
  • sloc: perl: 3,176; makefile: 4
file content (1346 lines) | stat: -rw-r--r-- 32,659 bytes parent folder | download | duplicates (3)
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
#A class that encapsulates the Google Apps for Your Domain Provisioning API V1.0
#see http://code.google.com/apis/apps-for-your-domain/google_apps_provisioning_api_v1.0_reference.html
#(C) 2006 Johan Reinalda, johan at reinalda dot net
#
#skeleton generated with h2xs -AXc -n Google::ProvisioningAPI
#
package VUser::Google::ProvisioningAPI::V1_0;

use 5.008005;

use strict;
use warnings;
use vars qw($VERSION);

use Carp;
use LWP::UserAgent qw(:strict);
use HTTP::Request qw(:strict);
use Encode;
use XML::Simple;

#I don't see the need for this - JKR
#require Exporter;

#NOT NEEDED FOR THIS CLASS
#our @ISA = qw(Exporter AutoLoader);

# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.

# This allows declaration	use VUser::Google::ProvisioningAPI ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.

#I don't see the need for this - JKR
#our %EXPORT_TAGS = ( 'all' => [ qw(
#
#) ] );
#
#our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
#
#our @EXPORT = qw(
#
#);

our $VERSION = '0.11';
our $APIVersion = '1.0';

#some constants
#web agent identification
use constant GOOGLEAGENT => "Google_ProvisioningAPI-perl/$VERSION";

#url for Google API token login
use constant GOOGLEHOST => 'www.google.com';
use constant GOOGLETOKENURL => 'https://www.google.com/accounts/ClientLogin';
use constant MAXTOKENAGE => 24 * 60 * 60;	#24 hours, see API docs

#base url to the Google REST API
use constant GOOGLEBASEURL => 'https://www.google.com/a/services/v1.0/';

use constant SUCCESSCODE => 'Success(2000)';
use constant FAILURECODE => 'Failure(2001)';

#some size constants
use constant MAXNAMELEN => 40;
use constant MAXUSERNAMELEN => 30;


# Preloaded methods go here.

#the constructor
sub new
{
	#parse parameters, if any
	(@_ == 4) || croak 'Constructor takes 3 arguments: domain, admin, adminpassword';

	my $object = shift();
	my $class = ref($object) || $object;

	my $self = {
		#Google related variables
		domain => shift(),		#the Google hosted domain we are accessing
		admin => shift(),		#the account to use when authenticating
		password => shift(),	#the password to use when authenticating
		refreshtoken => 0,		#if set, will force a re-authentication
		authtoken => '',		#the authentication token returned from google
		authtime => 0,			#time when authentication happened; only valid for 24 hours
		requestcontent => '',	#the last http content posted to Google
		replyheaders => '',		#the http headers of the last reply
		replycontent => '',		#the http content of the last reply
		result => {},			#the resulting hash from the last reply data as parsed by XML::Simple
	
		#some other variables
		debug => 0,			#when turned on, will spit out debug info to STDERR
		
		#some statistics that are 'read-only'
		stats => {
			ctime =>  time,			#object creation time
			rtime => 0,				#time of last request
			requests => 0,			#number of API requests made
			success => 0,			#number of successes
			logins => 0,			#number of authentications performed
		}
	};
	#return object
	bless( $self, 'VUser::Google::ProvisioningAPI::V1_0');
	return $self;
	
}

#method used to (re)login to the API, either first time, or as token times out
sub Relogin
{
	
	#get object reference
	my $self = shift();

	$self->dprint("Relogin called\n");

	my $retval = 0;
	
	#adjust stats counter
	$self->{stats}->{logins}++;
	
	#clear last results
	$self->{replyheaders} = $self->{replycontent} = '';
	$self->{result} = {};
	
	# Create an LWP object to make the HTTP POST request
	my $lwp = LWP::UserAgent->new;

	if(defined($lwp)) {
		$lwp->agent(GOOGLEAGENT);
		$lwp->from($self->{admin}.'@'.$self->{domain});
		# Submit the request with values for
		# accountType, Email and Passwd variables.
		my $response = $lwp->post( GOOGLETOKENURL,
				[ 'accountType' => 'HOSTED',
				  'Email' => $self->{admin}.'@'.$self->{domain},
				  'Passwd' => $self->{password}
				]
			);
		#save reply page
		$self->{replyheaders} = $response->headers->as_string;
		$self->{replycontent} = $response->content;
	
		if ($response->is_success) {
			# Extract the authentication token from the response
			foreach my $line (split/\n/, $response->content) {
				#$self->dprint( "RECV'd: $line" );
				if ($line =~ m/^SID=(.+)$/) {
					$self->{authtoken} = $1;
					$self->{authtime} = time;
					$self->dprint("Token found: $self->{authtoken}\n");
					#clear refresh
					$self->{refreshtoken} = 0;
					$retval = 1;
					last;
				}
			}
		}
		else {
			$self->dprint("Error in login: " . $response->status_line . "\n");
			$self->{result}->{reason} = "Error in login: " . $response->status_line;

		}
	} else {
		$self->dprint("Error getting lwp object: $!\n");
		$self->{result}->{reason} = "Error getting lwp object: $!";
	}
	return $retval;
}



#check if we are authenticated. If not, try to re-login
sub IsAuthenticated {

	#get object reference
	my $self = shift();

	if( $self->{refreshtoken} or ( (time - $self->{authtime}) > MAXTOKENAGE ) ) {
		return $self->Relogin();
	}
	#we are still okay!
	return 1;
}

#generic request routine that handles most functionality
#requires 3 arguments: Type, Action, Body
#Type is the object type to action upon. ('Account', 'Alias', 'MailingList')
#Action is what needs to be done
#Body is the xml specific to the action
sub Request
{
	my $retval = 0;

	#get object reference
	my $self = shift();

	$self->dprint( "***REQUEST***\n");
	
	#clear last results
	$self->{replyheaders} = $self->{replycontent} = '';
	$self->{result} = {};
	
	if(@_ != 3) {
		$self->{result}->{reason} = 'Invalid number of arguments to request()';
		return 0;
	}
	
	#get parameters
	my($type,$action,$body) = @_;
	
	$self->dprint( "Type: $type\nAction: $action\n$body\n");
	
	#keep some stats
	$self->{stats}->{requests}++;
	$self->{stats}->{rtime} = time;
	
	#check if we are authenticated to google
	if(!$self->IsAuthenticated()) {
		$self->dprint( "Error authenticating\n");
		return 0;
	}

	#standard XML pre and post segments
	my $pre = <<"EOL";
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
	<hs:rest xmlns:hs=\"google:accounts:rest:protocol\"
		xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\">
	<hs:type>$type<\/hs:type>
	<hs:token>$self->{authtoken}</hs:token>
	<hs:domain>$self->{domain}</hs:domain>
EOL

	my $post = '</hs:rest>';


	#create to request body
	$body = $pre . $body . $post;
	#properly encode it
	$body = encode('UTF-8',$body);

	#save the request content
	$self->{requestcontent} = $body;
	
	# Create an LWP object to make the HTTP POST request over
	my($ua) = LWP::UserAgent->new;
	if(!defined($ua)) {
		$self->dprint("Cannot create LWP::UserAgent object: $!\n");
		$self->{result}->{reason} = "Cannot create LWP::UserAgent object in request(): $!";
		return $retval;
	}
	
	#and create the request object where are we connecting to
	my $url = GOOGLEBASEURL . $action;
	$self->dprint("URL: $url\n");
	my $req = HTTP::Request->new(POST => $url);
	if(!defined($req)) {
		$self->dprint("Cannot create HTTP::Request object: $!\n");
		$self->{result}->{reason} = "Cannot create HTTP::Request object in request(): $!";
		return $retval;
	}
	
	#set some user agent variables
	$ua->agent( GOOGLEAGENT );
	$ua->from( '<' . $self->{admin}.'@'.$self->{domain} . '>');

	# Submit the request with values for
	# accountType, Email and Passwd variables.
	#$req->header('ContentType' => 'application/x-www-form-urlencoded');
	$req->header('Content-Type' => 'application/xml');
	$req->header('Accept' => 'application/xml');
	$req->header('Content-Lenght' => length($body) );
	$req->header('Connection' => 'Keep-Alive');
	$req->header('Host' => GOOGLEHOST);
	#assign the data to the request
	$req->content($body);
	
	#execute the request
	my $response = $ua->request($req);
	#save reply page
	$self->{replyheaders} = $response->headers->as_string;
	$self->{replycontent} = $response->content;
	#check result
	if ($response->is_success) {
		$self->{stats}->{success}++;
		$self->dprint( "Success in post:\n");
		
		#delete all namespace elements to keep it simple (ie. remove "hs:")
		#this avoids the need to use XML::NameSpace
		my $xml = decode('UTF-8', $response->content);
		$xml =~ s/hs\://g;
		$self->dprint( $xml );
		
		#now go parse it using XML::Simple
		$self->{result} = XMLin($xml,ForceArray => 0);
		#include Data::Dumper above if you want to use this line:
		#$self->dprint( Dumper($self->{result}) );

		#see if this was a successful call
		if( defined($self->{result}->{status}) and $self->{result}->{status} eq SUCCESSCODE ) {
			$self->dprint("Google API success!");
			$retval = 1;
		} else {
			$self->dprint("Google API failure!");
			if(defined($self->{result}->{reason})) {
				$@ = "Google API failure: $self->{result}->{status} - $self->{result}->{reason}";
			} else {
				$@ = "Google API failure: reason not found!";
				$self->{result}->{reason} = "Google API failure: reason not found!";
			}
		}
	}
	else {
		$self->dprint( "Error in post: " . $response->status_line . "\n");
		$self->{result}->{reason} = "Error in http post: " . $response->status_line;
	}
	#show full response for now
	#$self->dprint( "Headers:\n" . $response->headers->as_string);
	#foreach my $line (split/\n/, $response->content) {
	#	$self->dprint( "RECV'd:   $line\n");
	#}
	
	return $retval;
}


######################################
### these are the actual API calls ###
### See the Google docs for more   ###
######################################


### HOSTED ACCOUNT routines ###

sub CreateAccountEmail
{
	#get object reference
	my $self = shift();

	$self->dprint( "CreateAccount called\n");

	#check remaining arguments
	if(@_ < 4) {
		$self->dprint( "CreateAccountEmail method requires at least 4 arguments!\n");
		$self->{result}->{reason} = "CreateAccountEmail method requires at least 4 arguments!";
		return 0;
	}

	#get arguments
    my $userName = shift();
	my $firstName = shift();
    my $lastName = shift();
    my $password = shift();
	my $quota = shift() if (@_);	#this one is optional

	my $body = <<"EOL";
	<hs:CreateSection>
		<hs:firstName>$firstName</hs:firstName>
		<hs:lastName>$lastName</hs:lastName>
		<hs:password>$password</hs:password>
		<hs:userName>$userName</hs:userName>
EOL

	if(defined($quota)) {
		$body .= "\t\t<hs:quota>$quota<\/hs:quota>\n";
	}

	#add the final end-of-section tab
	$body .= "\t<\/hs:CreateSection>\n";


	return $self->Request('Account','Create/Account/Email',$body);

}

#NOTE: this API call may be discontinued!
sub CreateAccount
{
	#get object reference
	my $self = shift();

	$self->dprint( "CreateAccount called\n");

	#check remaining arguments
	if(@_ != 4) {
		$self->dprint( "CreateAccount method requires 4 arguments!\n");
		$self->{result}->{reason} = "CreateAccount method requires 4 arguments!";
		return 0;
	}

	#get arguments
    my $userName = shift();
	my $firstName = shift();
    my $lastName = shift();
    my $password = shift();

	my $body = <<"EOL";
	<hs:CreateSection>
		<hs:firstName>$firstName</hs:firstName>
		<hs:lastName>$lastName</hs:lastName>
		<hs:password>$password</hs:password>
		<hs:userName>$userName</hs:userName>
	</hs:CreateSection>
EOL

	return $self->Request('Account','Create/Account',$body);

}

sub UpdateAccount
{
	#get object reference
	my $self = shift();

	$self->dprint( "UpdateAccount called\n");

	#check remaining arguments
	if(@_ != 4) {
		$self->dprint( "UpdateAccount method requires 4 arguments!\n");
		$self->{result}->{reason} = "UpdateAccount method requires 4 arguments!";
		return 0;
	}

	#get arguments
    my $userName = shift();
	my $firstName = shift();
    my $lastName = shift();
    my $password = shift();

	#build request body
	my $body = <<"EOL";
	<hs:queryKey>userName</hs:queryKey>
	<hs:queryData>$userName</hs:queryData>
	<hs:UpdateSection>
EOL

	if(defined($firstName)) {
		$body .= "\t\t<hs:firstName>$firstName<\/hs:firstName>\n";
	}
	if(defined($lastName)) {
		$body .= "\t\t<hs:lastName>$lastName<\/hs:lastName>\n";
	}
	if(defined($password)) {
		$body .= "\t\t<hs:password>$password<\/hs:password>\n";
	}

	#add the final end-of-section tab
	$body .= "\t<\/hs:UpdateSection>\n";


	return $self->Request('Account','Update/Account',$body);

}

sub UpdateAccountEmail
{
	#get object reference
	my $self = shift();

	$self->dprint( "UpdateAccountEmail called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "UpdateAccount method requires 1 argument!\n");
		$self->{result}->{reason} = "CreateAccount method requires 1 argument!";
		return 0;
	}

	#get arguments
    my $userName = shift();

	my $body = <<"EOL";
	<hs:queryKey>userName</hs:queryKey>
	<hs:queryData>$userName</hs:queryData>
	<hs:UpdateSection>
		<hs:shouldEnableEmailAccount>1</hs:shouldEnableEmailAccount>
	</hs:UpdateSection>
EOL

	return $self->Request('Account','Update/Account/Email',$body);

}

sub UpdateAccountStatus
{
	#get object reference
	my $self = shift();

	$self->dprint( "UpdateAccountStatus called\n");

	#check remaining arguments
	if(@_ != 2) {
		$self->dprint( "UpdateAccount method requires 2 argument!\n");
		$self->{result}->{reason} = "CreateAccount method requires 2 arguments!";
		return 0;
	}

	#get arguments
    my $userName = shift();
	my $status = shift();

	if($status ne 'locked' and $status ne 'unlocked') {
		$self->dprint( "Error: status invalid!\n");
		$self->{result}->{reason} = 'Invalid status';
		return 0;
	}
	
	my $body = <<"EOL";
	<hs:queryKey>userName</hs:queryKey>
	<hs:queryData>$userName</hs:queryData>
	<hs:UpdateSection>
		<hs:accountStatus>$status</hs:accountStatus>
	</hs:UpdateSection>
EOL

	return $self->Request('Account','Update/Account/Status',$body);

}

sub RetrieveAccount
{
	#get object reference
	my $self = shift();
	
	$self->dprint( "RetrieveAccount called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "RetrieveAccount method requires 1 argument!\n");
		$self->{result}->{reason} = "RetrieveAccount method requires 1 argument!";
		return 0;
	}

	#get argument
    my $userName = shift();

	my $body = <<"EOL";
	<hs:queryKey>userName</hs:queryKey>
	<hs:queryData>$userName</hs:queryData>
EOL

	return $self->Request('Account','Retrieve/Account',$body);
}


sub DeleteAccount
{
	#get object reference
	my $self = shift();

	$self->dprint( "DeleteAccount called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "DeleteAccount method requires 1 argument!\n");
		$self->{result}->{reason} = "DeleteAccount method requires 1 argument!";
		return 0;
	}

	#get argument
    my $userName = shift();

	my $body = <<"EOL";
	<hs:queryKey>userName</hs:queryKey>
	<hs:queryData>$userName</hs:queryData>
EOL

	return $self->Request('Account','Delete/Account',$body);
}

sub RenameAccount
{
#This is derived from the Python sample code:
#-----
#Username change. Note that this feature must be explicitly
#   enabled by the domain administrator, and is not enabled by
#   default.
#
#   Args:
#     oldname: user to rename
#     newname: new username to set for the user
#     alias: if 1, create an alias of oldname for newname
#-----
#Ie. this may not work yet - JKR 20061204
	
	#get object reference
	my $self = shift();

	$self->dprint( "RenameAccount called\n");

	#check remaining arguments
	if(@_ != 3) {
		$self->dprint( "RenameAccount method requires 3 arguments!\n");
		$self->{result}->{reason} = "RenameAccount method requires 3 arguments!";
		return 0;
	}

	#get arguments
    my $oldName = shift();
    my $newName = shift();
    my $alias = shift();
	#check format of alias; default to 0
	$alias = lc($alias);
	if($alias ne '1') { $alias = '0'; }

	#build request format
	my $body = <<"EOL";
	<hs:queryKey>userName</hs:queryKey>
	<hs:queryData>$oldName</hs:queryData>
	<hs:UpdateSection>
		<hs:userName>$newName</hs:userName>
		<hs:shouldCreateAlias>$alias</hs:shouldCreateAlias>
	</hs:UpdateSection>
EOL

	return $self->Request('Account','Update/Account/Username',$body);
}


### ALIAS routines ###

sub CreateAlias
{
	#get object reference
	my $self = shift();

	$self->dprint( "CreateAlias called\n");

	#check remaining arguments
	if(@_ != 2) {
		$self->dprint( "CreateAlias method requires 2 arguments!\n");
		$self->{result}->{reason} = "CreateAlias method requires 2 arguments!";
		return 0;
	}

	#get argument
    my $userName = shift();
	my $alias = shift();
	
	#create the command format
	my $body = <<"EOL";
	<hs:CreateSection>
		<hs:userName>$userName</hs:userName>
		<hs:aliasName>$alias</hs:aliasName>
	</hs:CreateSection>
EOL

	return $self->Request('Alias','Create/Alias',$body);
}

sub RetrieveAlias
{
	#get object reference
	my $self = shift();
	
	$self->dprint( "RetrieveAlias called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "RetrieveAlias method requires 1 argument!\n");
		$self->{result}->{reason} = "RetrieveAlias method requires 1 argument!";
		return 0;
	}

	#get argument
    my $userName = shift();

	my $body = <<"EOL";
	<hs:queryKey>aliasName</hs:queryKey>
	<hs:queryData>$userName</hs:queryData>
EOL

	return $self->Request('Alias','Retrieve/Alias',$body);
}

sub DeleteAlias
{
	#get object reference
	my $self = shift();

	$self->dprint( "DeleteAlias called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "DeleteAlias method requires 1 argument!\n");
		$self->{result}->{reason} = "DeleteAlias method requires 1 argument!";
		return 0;
	}

	#get arguments
    my $alias = shift();

	my $body = <<"EOL";
	<hs:queryKey>aliasName</hs:queryKey>
	<hs:queryData>$alias</hs:queryData>
EOL

	return $self->Request('Alias','Delete/Alias',$body);
}


### Mailing List routines


sub CreateMailingList
{
	#get object reference
	my $self = shift();

	$self->dprint( "CreateMailingList called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "CreateMailingList method requires 1 argument!\n");
		$self->{result}->{reason} = "CreateMailingList method requires 1 argument!";
		return 0;
	}

	#get arguments
	my $mailingListName = shift();

	my $body = <<"EOL";
	<hs:CreateSection>
		<hs:mailingListName>$mailingListName</hs:mailingListName>
	</hs:CreateSection>
EOL

	return $self->Request('MailingList','Create/MailingList',$body);

}


sub UpdateMailingList
{
	#get object reference
	my $self = shift();

	$self->dprint( "UpdateMailingList called\n");

	#check remaining arguments
	if(@_ != 3) {
		$self->dprint( "UpdateMailingList method requires 3 arguments!\n");
		$self->{result}->{reason} = 'UpdateMailingList method requires 3 arguments!';
		return 0;
	}

	#get arguments
    my $mailingListName = shift();
    my $userName = shift();
	my $listOperation = shift();

	my $body = <<"EOL";
	<hs:queryKey>mailingListName</hs:queryKey>
	<hs:queryData>$mailingListName</hs:queryData>
	<hs:UpdateSection>
		<hs:userName>$userName</hs:userName>
		<hs:listOperation>$listOperation</hs:listOperation>
	</hs:UpdateSection>
EOL

	return $self->Request('MailingList','Update/MailingList',$body);

}



sub RetrieveMailingList
{
	#get object reference
	my $self = shift();
	
	$self->dprint( "RetrieveMailingList called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "RetrieveMailingList method requires 1 argument!\n");
		$self->{result}->{reason} = 'RetrieveMailingList method requires 1 arguments!';
		return 0;
	}

	#get argument
    my $mailingListName = shift();

	my $body = <<"EOL";
	<hs:queryKey>mailingListName</hs:queryKey>
	<hs:queryData>$mailingListName</hs:queryData>
EOL

	return $self->Request('MailingList','Retrieve/MailingList',$body);
}


sub DeleteMailingList
{
	#get object reference
	my $self = shift();

	$self->dprint( "DeleteMailingList called\n");

	#check remaining arguments
	if(@_ != 1) {
		$self->dprint( "DeleteMailingList method requires 1 argument!\n");
		$self->{result}->{reason} = 'DeleteMailingList method requires 1 argument!';
		return 0;
	}

	#get argument
    my $mailingListName = shift();

	my $body = <<"EOL";
	<hs:queryKey>mailingListName</hs:queryKey>
	<hs:queryData>$mailingListName</hs:queryData>
EOL

	return $self->Request('MailingList','Delete/MailingList',$body);
}


################################################################
# below are various subroutines to access local 'private' data #
################################################################

#the content of the request from and reply from Google API engine
sub requestcontent
{
	my $self = shift();

	return $self->{requestcontent};
}

sub replyheaders
{
	my $self = shift();

	return $self->{replyheaders};
}

sub replycontent
{
	my $self = shift();

	return $self->{replycontent};
}

		
#various access to local variables
sub debug
{
	my $self = shift();

	$self-> { debug } = shift() if (@_);
	
	return $self->{debug};
}

#change the admin account
sub admin
{
	my $self = shift();

	if (@_)
	{
		$self-> { admin } = shift();
		$self-> { refreshtoken } = 1;
	}
	
	return $self->{admin};
}

#password can only be set, not read!
sub password
{
	my $self = shift();


	if (@_)
	{
		$self-> { password } = shift();
		#force authentication update on next request
		$self-> { refreshtoken } = 1;
	}
	
	return '';
}

#the following can only be read!
sub authtime
{
	my $self = shift();

	return $self->{authtime};
}

#same for create time
sub ctime
{
	my $self = shift();

	return $self->{stats}->{ctime};
}

#and request time
sub rtime
{
	my $self = shift();

	return $self->{stats}->{rtime};
}

sub requests
{
	my $self = shift();

	return $self->{stats}->{requests};
}

sub logins
{
	my $self = shift();

	return $self->{stats}->{logins};
}

sub success
{
	my $self = shift();

	return $self->{stats}->{success};
}

sub version
{
	my $self = shift();

	return $APIVersion;
}

#several helper routines

#print out debugging to STDERR if debug is set
sub dprint
{
	my $self = shift();
	my($text) = shift if (@_);
	if( $self->{debug} and defined ($text) ) {
		print STDERR $text . "\n";
	}
}

1;
__END__

=pod

=head1 NAME

VUser::Google::ProvisioningAPI::V1_0 - Perl module that implements version 1.0 of the Google Apps for Your Domain Provisioning API

=head1 SYNOPSIS

  use VUser::Google::ProvisioningAPI;
  my $google = new VUser::Google::ProvisioningAPI($domain,$admin,$password);

  $google->CreateAccount($userName, $firstName, $lastName, $password);
  $google->RetrieveAccount($userName);

=head1 REQUIREMENTS

VUser::Google::ProvisioningAPI requires the following modules to be installed:

=over

=item

C<LWP::UserAgent>

=item

C<HTTP::Request>

=item

C<Encode>

=item

C<XML::Simple>

=back

=head1 DESCRIPTION

VUser::Google::ProvisioningAPI provides a simple interface to the Google Apps for Your Domain Provisioning API.
It uses the C<LWP::UserAgent> module for the HTTP transport, and the C<HTTP::Request> module for the HTTP request and response.

=head2 Examples

For a complete description of the meaning of the following methods, see the Google API documentation referenced in the SEE ALSO section.

	#create the object
	$google = new Google:ProvisioningAPI($domain,$admin,$password) || die "Cannot create google object";
	
	print 'Module version: ' . $google->VERSION . "\nAPI Version: " . $google->version() . "\n";
	
	#create a hosted account
	if( $google->CreateAccount( $userName, $firstName, $lastName, $password ) ) 
	{
		print "Account created!\N";
	}
	
	#add email services to the account
	$google->UpdateAccountEmail($userName);
	
	#retrieving account data
	if($google->RetrieveAccount($userName))
	{
		print 'Username: ' . $google->{result}->{RetrievalSection}->{userName} . "\n";
		print 'firstName: ' . $google->{result}->{RetrievalSection}->{firstName} . "\n";
		print 'lastName: ' . $google->{result}->{RetrievalSection}->{lastName} . "\n";
		print 'accountStatus: ' . $google->{result}->{RetrievalSection}->{accountStatus} . "\n";
		
	}
	
	#see what the result hash after a request looks like
	use Data::Dumper;
	print Dumper($google->{result});
	
	#delete an account
	$ret = DeleteAccount($userName);
	
	#accessing the HTML data as it was received from the Google servers:
	print $google->replyheaders();
	print $google->replycontent();


=head1 CONSTRUCTOR

new ( $domain, $admin, $adminpassword )

This is the constructor for a new VUser::Google::ProvisioningAPI object.
$domain is the domain name registered with Google Apps For Your Domain,
$admin is an account in the above domain that has the right to manage that domain, and
$adminpassword is the password for that account.

Note that the constructor will NOT attempt to perform the 'ClientLogin' call to the Google Provisioning API (see below).
Authentication happens automatically when the first API call is performed. The token will be remembered for the duration of the object, and will be automatically refreshed as needed.
If you want to verify that you can get a valid token before performing any operations, follow the constructor with a call to IsAuthenticated() as such:

	print "Authentication OK\n" unless not $google->IsAuthenticated();

=head1 METHODS

Below are all the methods available on the object. For the Google API specific methods, see the Google API documentation for more details.
When a request is properly handled by Google's API engine, the webpost to the API succeeds. This results in a valid page being returned. The content of this page then defines whether the request succeeded or not.
All pages returing the 'Success(2000)' status code will result in the API method succeeding, and returning a 1. All failures return 0.
Please see the section below on how to access the result data, and how to determine the reasons for errors.

If the web post fails (as determined by the C<HTTP::Request> method IsSuccess() ), the method returns 0, and the {reason} hash is set to a descriptive error.
You can then examine the raw data to get an idea of what went wrong.

=head2 Checking Authentication

IsAuthenticated()

=over

will check if the object has been able to authenticate with Google's api engine, and get an authentication ticket.
Returns 1 if successful, 0 on failure. To see why it may fail, see the $@ variable, and the $google->{results}->{reason} hash, and parse the returned page (see the 'content' and 'header' variables.)

=back

=head2 Methods to Create/Retrieve/Delete

=head3 'Hosted account' methods

CreateAccountEmail(  $userName, $firstName, $lastName, $password, $quota )

=over

Creates a hosted account with email services in your domains name space.
The first 4 arguments are required. The $quota argument is optional. If $quota is given, the <quota> tag will be sent with the request, otherwize is will be omitted.
See the Google API docs for the API call for more details.

=back

CreateAccount(  $userName, $firstName, $lastName, $password )

=over

Creates a hosted account in your domains name space. This account does NOT have email services by default.
You need to call UpdateAccountEmail() to add email services.
NOTE: this API call may be discontinued! See CreateAccountEmail() for a replacement.

=back

UpdateAccount( $username, $firstName, $lastName, $password )

=over

$username is the mandatory name of the hosted account. The remaining paramaters are optional, and can be set to 'undef' if you do not wish to change them
Eg. to change the password on an account, call this as;

=back

	UpdateAccount( $username, undef, undef, 'newpassword' );

=over

to change names only, you would call it as such:

=back

	UpdateAccount( $username, 'newfirstname', 'newlastname', undef );


UpdateAccountEmail( $userName )

=over

Adds email services to a hosted account created with CreateAccount().
NOTE: this API call may be discontinued! See CreateAccountEmail() for a replacement.

=back

UpdateAccountStatus( $userName, $status )

=over	

$status is either 'locked' or 'unlocked'

=back

RetrieveAccount( $userName )

DeleteAccount( $userName )

RenameAccount( $oldName, $newName, $alias )

=over

$alias is either '1' or '0'

WARNING: this method is derived from the Python sample code provided by Google:
(Ie. this may not work yet)
"Username change. Note that this feature must be explicitly enabled by the domain administrator, and is not enabled by default.
Args:

=over

oldname: user to rename
newname: new username to set for the user
alias: if 1, create an alias of oldname for newname"	

=back

=back


=head3 'Alias' methods

CreateAlias( $userName, $alias )

RetrieveAlias( $userName );

DeleteAlias( $alias );


=head3 'Mailing List' methods

CreateMailingList( $mailingListName )

UpdateMailingList( $mailingListName, $userName, $listOperation )

=over

$listOperation is either 'add' or 'remove'

=back

RetrieveMailingList( $mailingListName )

DeleteMailingList( $mailingListName )



=head2 Methods to set/get variables

After creating the object you can get/set the administrator account and set the password with these methods.
Note this will cause a re-authentication next time a Google API method is called.

admin( $admin )

=over	

set the administrative user, and will return administator username.

=back
	
password( $string )

=over

set the password, returns an empty string

=back

=head2 Miscelleaneous statistics methods

There are a few methods to access some statistics data that is collected while the object performing Google API calls.

authtime()

=over

returns the time of last authentication, as generated by the time() function

=back

ctime()

=over

returns the create time of the object, as generated by the time() function

=back

rtime()

=over

returns the time of the most recent request, as generated by the time() function

=back

logins()

=over

returns the number of API logins that have been performed

=back

requests()

=over

returns the numbers of API requests that have been submitted to Google

=back

success()

=over

returns the numbers of successful api request performed

=back

And finally,

version()

=over

returns a string with the api version implemented. This is currently '1.0'

=back


=head1 ACCESSING RESULTING DATA

Valid return data from Google is parsed into a hash named 'result', available through the object. In this hash you can find all elements as returned by Google.
This hash is produced by XML::Simple. See the Google API documentation in the SEE ALSO section for complete details.
Some of the more useful elements you may need to look at are:

	$google->{result}->{reason}		#this typically has the textual reason for a failure
	$google->{result}->{extendedMessage}	#a more extensive description of the failure reason may be here
	$google->{result}->{result}		#typically empty!
	$google->{result}->{type}		#should be same of query type, eg 'Account', 'Alias', 'MailingList'

The retrieval section contains data when you are querying. Here is what this section looks like when you call the RetrieveAccount method:

	$google->{result}->{RetrievalSection}->{firstName}
	$google->{result}->{RetrievalSection}->{lastName}
	$google->{result}->{RetrievalSection}->{accountStatus}
	$google->{result}->{RetrievalSection}->{aliases}->{alias}
	$google->{result}->{RetrievalSection}->{emailLists}->{emailList}


To see the structure of the result hash, use the Data::Dumper module as such:

	use Data::Dumper;
	print Dumper($google->{result});


=head1 ACCESSING RAW GOOGLE POST AND RESULT DATA

The data from the most recent post to the Google servers is available. You can access it as:

	print $google->requestcontent();

The most recent received HTML data is stored in two parts, the headers and the content. Both are strings. They can be accessed as such:

	print $google->replyheaders();
	print $google->replycontent();

Note the headers are new-line separated and can easily be parsed:

	foreach my $headerline ( split/\n/, $g->replyheaders() )
	{
		my ($header, $value) = split/:/, $headerline;
	}

=head1 EXPORT

None by default.


=head1 SEE ALSO

The official Google documentation can be found at
http://code.google.com/apis/apps-for-your-domain/google_apps_provisioning_api_v1.0_reference.html

For support, see the Google Group at
http://groups.google.com/group/apps-for-your-domain-apis

For additional support specific to this modules, email me at johan at reinalda dot net.

=head1 AUTHOR

Johan Reinalda, johan at reinalda dot net

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2006 by Johan Reinalda, johan at reinalda dot net

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.

If you make useful modification, kindly consider emailing then to me for inclusion in a future version of this module.

=cut