AMF51DegreesFilter.pm untested

filter: Statementstmt 0.0% 0 / 576 Branchbran 0.0% 0 / 182 Conditioncond 0.0% 0 / 66 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 889 CC 78 SCAR 62.4
CC
78
Cov
0%
handler
992.0
loadConfigFile
650.0
parse51DegreesFile
272.0
CRAP 510.4
1 #file:Apache2/AMF51DegreesFilter.pm;
2 #--------------------------------
3  
4 #
5 # Created by Idel Fuschini
6 # Date: 08/12/11
7 # Site: http://www.apachemobilefilter.org
8 # Mail: idel.fuschini@gmail.com
9  
10  
11 package Apache2::AMF51DegreesFilter;
12 use strict;
13 use warnings;
14 use threads;
15 use threads::shared;
16 use Apache2::AMFCommonLib ();
17
18 use Apache2::RequestRec ();
19 use Apache2::RequestUtil ();
20 use Apache2::SubRequest ();
21 use Apache2::Log;
22 use Apache2::Filter ();
23 use APR::Table ();
24 use LWP::Simple qw($ua get);
25 use Apache2::Const -compile => qw(OK REDIRECT DECLINED);
26 use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
27 use constant BUFF_LEN => 1024;
28 use Cache::FileBackend;
29  
30  
31 #
32 # Define the global environment
33 #
34  
35 use vars qw($VERSION);
36 $VERSION= "4.33";;;
37 my $CommonLib = new Apache2::AMFCommonLib ();
38
39 # this is the environment........
40
41 my %Capability ;
42 my %Array_fb ;
43 my %Array_id ;
44 my %Array_fullua_id ;
45 my %Array_DDRcapability ;
46  
47 my %MobileArray=$CommonLib->getMobileArray;
48 my %PCArray=$CommonLib->getPCArray;
49 my $mobileversionurl="none";
50 my $fullbrowserurl="none";
51 my $redirecttranscoder="true";
52 my $redirecttranscoderurl="none";
53 my $resizeimagedirectory="none";
54 my $Degreesnetdownload="false";
55 my $download51Degreesurl="https://51degrees.mobi/Products/Downloads/Premium.aspx";
56 my $listall="false";
57 my $cookiecachesystem="false";
58 my $DegreesVersion="unknown";
59 my $personal51Degreesurl='unknown';
60 my $cachedirectorystore="/tmp";
61 my $capabilitylist="none";
62 my $restmode='false';
63 my $deepSearch=0;
64 my $checkVersion='false';
65 my $mobilenable="false";
66
67 #details
68 my %PCDetails;
69 $PCDetails{'google_chrome'}='Chrome|Google';
70 $PCDetails{'google_chrome_0'}='Chrome|Google';
71 $PCDetails{'google_chrome_1'}='Chrome|Google';
72 $PCDetails{'google_chrome_2'}='Chrome|Google';
73 $PCDetails{'google_chrome_3'}='Chrome|Google';
74 $PCDetails{'msie'}="Microsoft Explorer|Microsoft";
75 $PCDetails{'safari'}='Safari|Apple';
76 $PCDetails{'opera'}='Opera|Opera Software';
77 $PCDetails{'konqueror'}='Konqueror|Mozilla';
78
79 $CommonLib->printLog("---------------------------------------------------------------------------");
80 $CommonLib->printLog("------- APACHE MOBILE FILTER V$VERSION -------");
81 $CommonLib->printLog("------- support http://groups.google.com/group/amf-device-detection -------");
82 $CommonLib->printLog("---------------------------------------------------------------------------");
83 $CommonLib->printLog("AMF51DegreesFilter module Version $VERSION");
84 if (($ENV{AMFSetProxy}) && $ENV{AMFSetProxy} eq 'true' ) {
85 $CommonLib->printLog("AMFSetHttpProxy is ".$ENV{AMFSetHttpProxy});
86 my $port=3128;
87 my $default="";
88 if ($ENV{AMFSetHttpProxyPort}) {
89 $port=$ENV{AMFSetHttpProxyPort};
90 } else {
91 $default=' (default)';
92 }
93 $CommonLib->printLog("AMFSetHttpProxyPort is ".$port.$default);
94 $ua->proxy('http','http://'.$ENV{AMFSetHttpProxy}.':'.$port);
95 }
96 my $timeoutinsecond=5;
97 my $default="";
98 if ($ENV{AMFSetGetParameterTimeoOut}) {
99 $timeoutinsecond=$ENV{AMFSetGetParameterTimeoOut};
100 } else {
101 $default=' (default)';
102 }
103 $CommonLib->printLog("AMFSetGetParameterTimeoOut is ".$timeoutinsecond.'s'.$default);
104 $ua->timeout($timeoutinsecond);
105 if ($ENV{AMFCheckVersion}) {
106 $checkVersion=$ENV{AMFCheckVersion};
107 }
108 if ($ENV{AMFCheckVersion}) {
109 $checkVersion=$ENV{AMFCheckVersion};
110 }
111 if ($checkVersion eq 'true') {
112 $CommonLib->printLog("Check on apchemobilefilter.org if the installed AMF is the last version");
113 $CommonLib->printLog("Try to download http://www.apachemobilefilter.org/param/amf.config");
114 my $url="http://www.apachemobilefilter.org/param/amf.config";
115 my $content = get ($url);
116 $content =~ s/\n//g;
117 my $check_version=0;
118 if ($content) {
119 $check_version=$content;
120 }
121 if ($check_version > $VERSION && $check_version ne 0) {
122 $CommonLib->printLog("---------------------------------------------------------------------------");
123 $CommonLib->printLog("----- There is a new version of AMF V$check_version online ----");
124 $CommonLib->printLog("---------------------------------------------------------------------------");
125 } else {
126 $CommonLib->printLog("AMF installed is the last version");
127 }
128 } else {
129 $CommonLib->printLog("AMFCheckVersion is false, AMF don't check the last version.");
130 }
131 if ($ENV{ResizeImageDirectory}) {
132 $Capability{'max_image_width'}="max_image_width";
133 $Capability{'max_image_height'}="max_image_width";
134 $resizeimagedirectory=$ENV{ResizeImageDirectory};
135 }
136 if (($ENV{FullBrowserUrl}) || ($ENV{MobileVersionUrl})) {
137 $Capability{'device_claims_web_support'}="device_claims_web_support";
138 $Capability{'is_wireless_device'}="is_wireless_device";
139 $fullbrowserurl=$ENV{FullBrowserUrl}
140 }
141 if ($ENV{RedirectTranscoderUrl}) {
142 $Capability{'is_transcoder'}="is_transcoder";
143 $redirecttranscoderurl=$ENV{RedirectTranscoderUrl};
144 }
145  
146 #
147 # Check if AMFMobileHome and CacheDirectoryStore is setting in apache httpd.conf file for example:
148 # PerlSetEnv AMFMobileHome <apache_directory>/MobileFilter
149 #
150 if ($ENV{CacheDirectoryStore}) {
151 $cachedirectorystore=$ENV{CacheDirectoryStore};
152 $CommonLib->printLog("CacheDirectoryStore is: $cachedirectorystore");
153 } else {
154 $CommonLib->printLog("CacheDirectoryStore not exist. Please set the variable CacheDirectoryStore into httpd.conf, (the directory must be writeable)");
155 ModPerl::Util::exit();
156 }
157 #
158 # Define the cache system directory
159 #
160 my $cacheSystem = new Cache::FileBackend( $cachedirectorystore, 3, 000 );
161 $cacheSystem->store( '51Degrees-id', 'device_not_found', "id=device_not_found&device=false&device_claims_web_support=true&is_wireless_device=false");
162 if ($cacheSystem->restore('51Degrees-conf','ver')) {
163 } else {
164 $CommonLib->printLog('Create new wurf-con store');
165 $cacheSystem->store('51Degrees-conf', 'ver', 'null');
166 $cacheSystem->store('51Degrees-conf', 'caplist', 'null');
167 $cacheSystem->store('51Degrees-conf', 'listall', 'null');
168 $cacheSystem->store('51Degrees-conf', 'RedirectTranscoderUrl','null');
169 $cacheSystem->store('51Degrees-conf', 'MobileVersionUrl','null');
170 $cacheSystem->store('51Degrees-conf', 'FullBrowserUrl','null');
171 $cacheSystem->store('51Degrees-conf', 'ResizeImageDirectory','null');
172 }
173 if ($ENV{AMFMobileHome}) {
174 &loadConfigFile("$ENV{AMFMobileHome}/51Degrees.xml");
175 } else {
176 $CommonLib->printLog("AMFMobileHome not exist. Please set the variable AMFMobileHome into httpd.conf");
177 ModPerl::Util::exit();
178 }
179 sub loadConfigFile {
180 my ($file51Degrees) = @_;
181 my $null="";
182 my $null2="";
183 my $null3="";
184 my $val;
185 my $capability;
186 my $r_id;
187 my $dummy;
188 #The filter
189 $CommonLib->printLog("Start read configuration from httpd.conf");
190
191 if ($ENV{Degrees51NetDownload}) {
192 if ($ENV{Degrees51NetDownload} eq 'true' || $ENV{Degrees51NetDownload} eq 'false') {
193 $Degreesnetdownload=$ENV{Degrees51NetDownload};
194 $CommonLib->printLog("51DegreesNetDownload is: $Degreesnetdownload");
195 } else {
196 $CommonLib->printLog("Error 51DegreesNetDownload parmeter must set to true or false");
197 ModPerl::Util::exit();
198 }
199 }
200
201 if ($ENV{Download51DegreesURL}) {
202 $download51Degreesurl=$ENV{Download51DegreesURL};
203 $CommonLib->printLog("Download51DegreesURL is: $download51Degreesurl");
204 }
205  
206 if ($Degreesnetdownload eq 'true') {
207 if ($ENV{Key51Degrees}) {
208 $download51Degreesurl=$download51Degreesurl."?LicenseKeys=".$ENV{Key51Degrees}."&Type=XML&Download=True";
209 $CommonLib->printLog("Key51Degrees is: $ENV{Key51Degrees}");
210 } else {
211 $CommonLib->printLog("Error Key51Degrees parmeter must be setted ");
212 ModPerl::Util::exit();
213 }
214
215 }
216 if ($ENV{CapabilityList}) {
217 my @dummycapability = split(/,/, $ENV{CapabilityList});
218 $capabilitylist=$ENV{CapabilityList};
219 foreach $dummy (@dummycapability) {
220 if ($dummy eq "all") {
221 $listall="true";
222 }
223 $Capability{$dummy}=$dummy;
224 $CommonLib->printLog("CapabilityList is: $dummy");
225 }
226 } else {
227 $listall="true";
228 $CommonLib->printLog('CapabilityList not setted so the default value is "all"');
229 }
230 if ($ENV{AMFMobileKeys}) {
231 my @dummyMobileKeys = split(/,/, $ENV{AMFMobileKeys});
232 foreach $dummy (@dummyMobileKeys) {
233 $MobileArray{$dummy}='mobile';
234 }
235 $CommonLib->printLog("AMFMobileKeys is: $ENV{AMFMobileKeys}");
236 }
237
238  
239 if ($ENV{AMFProductionMode}) {
240 $cookiecachesystem=$ENV{AMFProductionMode};
241 $CommonLib->printLog("AMFProductionMode is: $cookiecachesystem");
242 } else {
243 $CommonLib->printLog("AMFProductionMode (the CookieCacheSystem is deprecated) is not setted the default value is $cookiecachesystem");
244 }
245 if ($ENV{Personal51DegreesFileName}) {
246 $personal51Degreesurl=$ENV{AMFMobileHome}."/".$ENV{Personal51DegreesFileName};
247 $CommonLib->printLog("Personal51DegreesFileName is: $ENV{Personal51DegreesFileName}");
248 }
249 if ($ENV{RestMode}) {
250 $restmode=$ENV{RestMode};
251 $CommonLib->printLog("RestMode is: $restmode");
252 }
253 if ($ENV{AMFDeepParse}) {
254 $deepSearch=$ENV{AMFDeepParse};
255 $CommonLib->printLog("AMFDeepParse is: $deepSearch");
256 } else {
257 $CommonLib->printLog("AMFDeepParse is not setted the default value is $deepSearch");
258 }
259  
260 if ($ENV{FullBrowserMobileAccessKey}) {
261 $mobilenable="$ENV{FullBrowserMobileAccessKey}";
262 $CommonLib->printLog("FullBrowserMobileAccessKey is: $ENV{FullBrowserMobileAccessKey}");
263 $CommonLib->printLog("For access the device to fullbrowser set the link: <url>?$mobilenable=true");
264 }
265 $CommonLib->printLog("Finish loading parameter");
266 $CommonLib->printLog("---------------------------------------------------------------------------");
267 if ($Degreesnetdownload eq "true") {
268
269 $CommonLib->printLog("Start process downloading 51Degrees.xml from $download51Degreesurl");
270 $CommonLib->printLog ("Test the URL");
271 my ($content_type, $document_length, $modified_time, $expires, $server) = head($download51Degreesurl);
272 if ($content_type eq "") {
273 $CommonLib->printLog("Couldn't get $download51Degreesurl.");
274 $CommonLib->printLog("Take the last version downloaded.");
275 # ModPerl::Util::exit();
276 } else {
277 $CommonLib->printLog("The URL is correct");
278 $CommonLib->printLog("The size of document 51Degrees file: $document_length bytes");
279 }
280
281 if ($content_type eq 'application/octet-stream') {
282 $CommonLib->printLog("The file is a zip file.");
283 $CommonLib->printLog ("Start downloading");
284 my @dummypairs = split(/\//, $download51Degreesurl);
285 my ($ext_zip) = $download51Degreesurl =~ /\.(\w+)$/;
286 my $filezip=$dummypairs[-1];
287 my $tmp_dir=$ENV{AMFMobileHome};
288 $filezip="$tmp_dir/$filezip";
289 my $status = getstore ($download51Degreesurl,$filezip);
290 my $output="$tmp_dir/51Degrees.xml";
291 gunzip $filezip => $output
292 or die "gzip failed: $GunzipError\n";
293 $CommonLib->printLog("Finish downloading 51Degrees from $download51Degreesurl");
294 } else {
295 $CommonLib->printLog("Error download 51Degrees device repository, check the premium keys. AMF try to load the previous version.");
296 }
297  
298 }
299 if (-e "$file51Degrees") {
300 $CommonLib->printLog("Start loading 51Degrees.xml");
301 if (open (IN,"$file51Degrees")) {
302 my $filesize= -s $file51Degrees;
303 read (IN,my $content,$filesize);
304 close IN;
305 if ($content =~ /\<validation/o) {
306 $DegreesVersion=substr($content,index($content,'<version>') + 9 ,index($content,'<validation>') - index($content,'<version>') - 9);
307 } else {
308 $DegreesVersion=substr($content,index($content,'<version>') + 9 ,index($content,'</version>') - index($content,'<version>') - 9);
309 }
310 $content =~ s/\n//g;
311 $content =~ s/>/>\n/g;
312 my @rows = split(/\n/, $content);
313 my $numberRow=scalar(@rows);
314 my $progress=0;
315 foreach my $row (@rows){
316 $r_id=parse51DegreesFile($row,$r_id);
317 $progress++;
318 my $perc=int(($progress/$numberRow)*100);
319 print "Percent loaded: ".$perc."%\r";
320  
321 }
322 } else {
323 $CommonLib->printLog("Error open file:$file51Degrees");
324 ModPerl::Util::exit();
325 }
326 } else {
327 $CommonLib->printLog("File $file51Degrees not found");
328 ModPerl::Util::exit();
329 }
330
331 close IN;
332 my $arrLen = scalar %Array_fb;
333 ($arrLen,$dummy)= split(/\//, $arrLen);
334 if ($arrLen == 0) {
335 $CommonLib->printLog("Error the file probably is not a 51Degrees file, control the url or path");
336 $CommonLib->printLog("Control also if the file is compress file, and DownloadZipFile parameter is seted false");
337 ModPerl::Util::exit();
338 }
339 $CommonLib->printLog("51Degrees version: $DegreesVersion");
340 if ($cacheSystem->restore('51Degrees-conf', 'amfver') ne $VERSION||
341 $cacheSystem->restore('51Degrees-conf', 'ResizeImageDirectory') ne $resizeimagedirectory||
342 $cacheSystem->restore('51Degrees-conf', 'Download51DegreesURL') ne $download51Degreesurl||
343 $cacheSystem->restore('51Degrees-conf', 'FullBrowserUrl') ne $fullbrowserurl||
344 $cacheSystem->restore('51Degrees-conf', 'RedirectTranscoderUrl') ne $redirecttranscoderurl||
345 $cacheSystem->restore('51Degrees-conf', 'ver') ne $DegreesVersion ||
346 $cacheSystem->restore('51Degrees-conf', 'caplist') ne $capabilitylist||
347 $cacheSystem->restore('51Degrees-conf', 'listall') ne $listall) {
348 $CommonLib->printLog("********************************************************************************************************");
349 $CommonLib->printLog("* This is a new version of 51Degrees or you change some parameter value or it's a new version of AMF, now the old cache must be deleted *");
350 $CommonLib->printLog("********************************************************************************************************");
351 $cacheSystem->store('51Degrees-conf', 'ver', $DegreesVersion);
352 $cacheSystem->store('51Degrees-conf', 'amfver', $VERSION);
353 $cacheSystem->store('51Degrees-conf', 'caplist', $capabilitylist);
354 $cacheSystem->store('51Degrees-conf', 'listall', $listall);
355 $cacheSystem->store('51Degrees-conf', 'RedirectTranscoderUrl', $redirecttranscoderurl);
356 $cacheSystem->store('51Degrees-conf', 'FullBrowserUrl', $fullbrowserurl);
357 $cacheSystem->store('51Degrees-conf', 'Download51DegreesURL', $download51Degreesurl);
358 $cacheSystem->store('51Degrees-conf', 'ResizeImageDirectory', $resizeimagedirectory);
359
360 $cacheSystem->delete_namespace( '51Degrees-id' );
361 $cacheSystem->delete_namespace( '51Degrees-ua' );
362 }
363 $CommonLib->printLog("This version of 51Degrees has $arrLen UserAgent");
364 $CommonLib->printLog("End loading 51Degrees.xml");
365 if ($personal51Degreesurl ne 'unknown') {
366 $CommonLib->printLog("---------------------------------------------------------------------------");
367 if (-e "$personal51Degreesurl") {
368 $CommonLib->printLog("Start loading $ENV{Personal51DegreesFileName}");
369 if (open (IN,"$personal51Degreesurl")) {
370 my $filesize= -s $personal51Degreesurl;
371 my $string_file;
372 read (IN,$string_file,$filesize);
373 close IN;
374 $string_file =~ s/\n//g;
375 $string_file =~ s/>/>\n/g;
376 my @arrayFile=split(/\n/, $string_file);
377 my $progress=0;
378 my $numberRow=scalar(@arrayFile);
379 foreach my $line (@arrayFile) {
380 $r_id=parse51DegreesFile($line,$r_id);
381 $progress++;
382 my $perc=int(($progress/$numberRow)*100);
383 print "Percent loaded: ".$perc."%\r";
384  
385 }
386 } else {
387 $CommonLib->printLog("Error open file:$personal51Degreesurl");
388 ModPerl::Util::exit();
389 }
390 $CommonLib->printLog("END loading $ENV{Personal51DegreesFileName}");
391 close IN;
392
393 } else {
394 $CommonLib->printLog("File $personal51Degreesurl not found");
395 ModPerl::Util::exit();
396 }
397 }
398  
399  
400 }
401 sub callparse51DegreesFile {
402 my ($output) = @_;
403 my $r_id;
404 if (open (IN,"$output")) {
405 my $filesize= -s $output;
406 my $string_file;
407 read (IN,$string_file,$filesize);
408 close IN;
409 $string_file =~ s/\n//g;
410 $string_file =~ s/>/>\n/g;
411 my @arrayFile=split(/\n/, $string_file);
412 foreach my $line (@arrayFile) {
413 $r_id=parse51DegreesFile($line,$r_id);
414 }
415 } else {
416 $CommonLib->printLog("Error open file:$output");
417 ModPerl::Util::exit();
418 }
419 }
420 sub parse51DegreesFile {
421 my ($record,$val) = @_;
422 my $null="";
423 my $null2="";
424 my $null3="";
425 my $uagent="";
426 my $fb="";
427 my $value="";
428 my $id;
429 my $name="";
430 my $version="";
431 if ($val) {
432 $id="$val";
433 }
434 if ($record =~ /\<profile/o) {
435 my @field=split(/\"/, $record);
436 if ($field[5]) {
437 $uagent=lc($field[5]);
438 if (index($uagent,'blackberry') >-1 ) {
439 $uagent=substr($uagent,index($uagent,'blackberry'));
440 }
441 ($uagent,$version)=$CommonLib->androidDetection($uagent);
442 }
443 if ($field[1]) {
444 $id=$field[1];
445 if ($id eq '1') {
446 $id='generic_web_browser';
447 }
448  
449 }
450 if ($field[3]) {
451 $fb=$field[3];
452 if ($fb eq '1') {
453 $fb='generic_web_browser';
454 }
455 }
456 if (($fb) && ($id)) {
457 $Array_fb{"$id"}=$fb;
458 }
459 if (($field[5]) && ($id)) {
460 my %ParseUA=$CommonLib->GetMultipleUa($uagent,$deepSearch);
461 my $pair;
462 my $arrUaLen = scalar %ParseUA;
463 my $contaUA=0;
464 my $Array_fullua_id=$uagent;
465 foreach $pair (reverse sort { $a <=> $b } keys %ParseUA) {
466 my $dummy=$ParseUA{$pair};
467 if ($Array_id{$dummy}) {} else {
468 $Array_id{$dummy}=$id;
469 }
470 $contaUA=$contaUA-1;
471 }
472 }
473
474 }
475 if ($record =~ /\<property/o) {
476 ($null,$name,$null2,$value,$null3,$fb)=split(/\"/, $record);
477 if ($listall eq "true") {
478 $Capability{$name}=$name;
479 }
480 if (($id) && ($Capability{$name}) && ($name) && ($value)) {
481 $Array_DDRcapability{"$val|$name"}=$value;
482 }
483 }
484 if ($record =~ /\/version>/o) {
485 $DegreesVersion=substr($record,index($record,'<version>') + 9 ,index($record,'<validation>') -13);
486 }
487 return $id;
488  
489 }
490 sub FallBack {
491 my ($idToFind) = @_;
492 my $dummy_id;
493 my $dummy;
494 my $dummy2;
495 my $LOOP;
496 my %ArrayCapFoundToPass;
497 my $capability;
498 foreach $capability (sort keys %Capability) {
499 $dummy_id=$idToFind;
500 $LOOP=0;
501 while ($LOOP<2) {
502 $dummy="$dummy_id|$capability";
503 if ($Array_DDRcapability{$dummy}) {
504 $LOOP=2;
505 $dummy2="$dummy_id|$capability";
506 $ArrayCapFoundToPass{$capability}=$Array_DDRcapability{$dummy2};
507 } else {
508 if ($Array_fb{$dummy_id}) {
509 $dummy_id=$Array_fb{$dummy_id};
510 } else {
511 $dummy_id="generic_web_browser";
512 }
513 if ($dummy_id eq "generic_web_browser") {
514 $LOOP++;
515 }
516 }
517 }
518
519 }
520 return %ArrayCapFoundToPass;
521 }
522 sub IdentifyUAMethod {
523 my ($UserAgent) = @_;
524 my $ind=0;
525 my %ArrayPM;
526 my $pair;
527 my $pair2;
528 my $id_find="";
529 my $dummy;
530 my $uagent_toMatch;
531 my $near_toFind=100;
532 my $near_toMatch;
533 my %ArrayUAType=$CommonLib->GetMultipleUa(lc($UserAgent),$deepSearch);
534 foreach $pair (reverse sort { $a <=> $b } keys %ArrayUAType)
535 {
536 my $dummy=$ArrayUAType{$pair};
537 if ($Array_id{$dummy}) {
538 if (!$id_find) {
539 $id_find=$Array_id{$dummy};
540 }
541 }
542 }
543 return $id_find;
544 }
545 sub IdentifyPCUAMethod {
546 my ($UserAgent) = @_;
547 my $ind=0;
548 my $id_find="none";
549 my $pair;
550 my $length=0;
551  
552 foreach $pair (sort keys %PCArray) {
553 if ($UserAgent =~ m/$pair/ && $id_find eq 'none') {
554 $id_find=$PCArray{$pair};
555 }
556 }
557 if ($id_find) {}else{$id_find="";};
558 return $id_find;
559 }
560  
561  
562 sub handler {
563 my $f = shift;
564 my $capability2;
565 my $variabile="";
566 my $user_agent=lc($f->headers_in->{'User-Agent'}|| '');
567 my $x_user_agent=$f->headers_in->{'X-Device-User-Agent'}|| '';
568 my $x_operamini_phone_ua=$f->headers_in->{'X-OperaMini-Phone-Ua'}|| '';
569 my $x_operamini_ua=$f->headers_in->{'X-OperaMini-Ua'}|| '';
570 my $query_string=$f->args;
571 my $docroot = $f->document_root();
572 my $id="";
573 my $location="none";
574 my $width_toSearch;
575 my $type_redirect="internal";
576 my $return_value;
577 my $dummy="";
578 my $variabile2="";
579 my %ArrayCapFound;
580 my $controlCookie;
581 my $query_img="";
582 $ArrayCapFound{is_transcoder}='false';
583 $ArrayCapFound{'IsMobile'}='true';
584  
585 my %ArrayQuery;
586 my $var;
587 my $version="";
588 my $realPCbrowser='none';
589 if ($user_agent eq "") {
590 $user_agent="no useragent found";
591 }
592 if ($x_user_agent) {
593 $user_agent=lc($x_user_agent);
594 }
595 if ($x_operamini_phone_ua) {
596 $user_agent=lc($x_operamini_phone_ua);
597 }
598 my $cookie = $f->headers_in->{Cookie} || '';
599 $id=$CommonLib->readCookie($cookie);
600 my $amfFull=$CommonLib->readCookie_fullB($cookie);
601 if ($query_string) {
602 my @vars = split(/&/, $query_string);
603 foreach $var (sort @vars){
604 if ($var) {
605 my ($v,$i) = split(/=/, $var);
606 $v =~ tr/+/ /;
607 $v =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
608 if ($i) {
609 $i =~ tr/+/ /;
610 $i =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
611 $i =~ s/<!--(.|\n)*-->//g;
612 $ArrayQuery{$v}=$i;
613 }
614 }
615 }
616 if (($ArrayQuery{amf}) && $restmode eq 'true') {
617 $user_agent=lc($ArrayQuery{amf});
618 }
619 if ($ArrayQuery{$mobilenable}) {
620 $f->err_headers_out->set('Set-Cookie' => "amfFull=false; path=/;");
621 $amfFull='ok';
622 }
623  
624 }
625  
626 $user_agent=lc($user_agent);
627 if ($user_agent =~ m/blackberry/i) {
628 $user_agent=substr($user_agent,index($user_agent,'blackberry'));
629 }
630 if ($user_agent =~ m/up.link/i ) {
631 $user_agent=substr($user_agent,0,index($user_agent,'up.link') - 1);
632 }
633 if ($user_agent =~ m/c4_acer_mozilla/i ) {
634 $user_agent=substr($user_agent,index($user_agent,'mozilla'));
635 }
636
637 ($user_agent,$version)=$CommonLib->androidDetection($user_agent);
638  
639 if ($cacheSystem->restore( '51Degrees-ua', $user_agent )) {
640 #
641 # cookie is not empty so I try to read in memory cache on my httpd cache
642 #
643 $id=$cacheSystem->restore( '51Degrees-ua', $user_agent );
644 if ($cacheSystem->restore( '51Degrees-id', $id )) {
645 #
646 # I'm here only for old device
647 #
648 my @pairs = split(/&/, $cacheSystem->restore( '51Degrees-id', $id ));
649 my $param_tofound;
650 my $string_tofound;
651 foreach $param_tofound (@pairs) {
652 ($string_tofound,$dummy)=split(/=/, $param_tofound);
653 if ($dummy) {
654 $ArrayCapFound{$string_tofound}=$dummy;
655 my $upper2=uc($string_tofound);
656 $f->subprocess_env("AMF_$upper2" => $ArrayCapFound{$string_tofound});
657 $f->pnotes($string_tofound => $ArrayCapFound{$string_tofound});
658 }
659 }
660 $id=$ArrayCapFound{id};
661 if ($ArrayCapFound{realpcbrowser} ne 'none') {
662 $id=$realPCbrowser;
663 $ArrayCapFound{'IsMobile'}='false';
664 }
665 }
666 } else {
667 if ($id eq "") {
668 if ($user_agent) {
669 my $pair;
670 my $lcuser_agent=lc($user_agent);
671 if (!$id) {$id="";};
672 if ($id eq "") {
673 $id=IdentifyUAMethod($user_agent);
674 }
675 if ($id eq "") {
676 $id='generic_web_browser';
677 } else {
678 #this check the correct version of Android
679 if ($version) {
680 if ($version ne 'nc') {
681 my $lengthId=length($version);
682 my $count=0;
683 while($count<$lengthId) {
684 my $idToCheck=$id."_sub".substr($version,0,length($version)-$count);
685 if ($Array_fb{$idToCheck}) {
686 $id=$idToCheck;
687 $count=$lengthId;
688 }
689 $count++;
690 }
691 }
692 }
693 }
694 $cacheSystem->store( '51Degrees-ua', $user_agent, $id);
695 }
696 }
697 if ($id ne "") {
698 #
699 # device detected
700 #
701 if ($cacheSystem->restore( '51Degrees-id', $id )) {
702 #
703 # I'm here only for old device looking in cache
704 #
705 my @pairs = split(/&/, $cacheSystem->restore( '51Degrees-id', $id ));
706 my $param_tofound;
707 my $string_tofound;
708 foreach $param_tofound (@pairs) {
709 ($string_tofound,$dummy)=split(/=/, $param_tofound);
710 $ArrayCapFound{$string_tofound}=$dummy;
711 my $upper2=uc($string_tofound);
712 $f->subprocess_env("AMF_$upper2" => $ArrayCapFound{$string_tofound});
713 $f->pnotes("$string_tofound" => $ArrayCapFound{$string_tofound});
714 }
715 $id=$ArrayCapFound{id};
716  
717  
718 } else {
719  
720 %ArrayCapFound=FallBack($id);
721 foreach $capability2 (sort keys %ArrayCapFound) {
722 $variabile2="$variabile2$capability2=$ArrayCapFound{$capability2}&";
723 my $upper=uc($capability2);
724 $f->subprocess_env("AMF_$upper" => $ArrayCapFound{$capability2});
725 $f->pnotes("$capability2" => $ArrayCapFound{$capability2});
726 }
727  
728 $variabile2="id=$id&$variabile2&realpcbrowser=$realPCbrowser";
729 $f->subprocess_env("AMF_ID" => $id);
730 $f->pnotes('id' => $id);
731 $cacheSystem->store( '51Degrees-id', $id, $variabile2 );
732 $cacheSystem->store( '51Degrees-ua', $user_agent, $id);
733 }
734 if ($cookiecachesystem eq "true") {
735 $f->err_headers_out->set('Set-Cookie' => "amf=$id; path=/;");
736 }
737 }
738 }
739 if ($ArrayCapFound{'ScreenPixelsWidth'} ne 'Unknown') {
740 $f->pnotes("max_image_width" => $ArrayCapFound{'ScreenPixelsWidth'});
741 $f->pnotes("max_image_height" => $ArrayCapFound{'ScreenPixelsHeight'});
742 }
743 if ($ArrayCapFound{'IsTablet'}) {
744 $f->pnotes("is_tablet" => lc($ArrayCapFound{'IsTablet'}));
745 $f->subprocess_env("AMF_DEVICE_IS_TABLET" => lc($ArrayCapFound{'IsTablet'}));
746 }
747 if ($amfFull ne "") {
748 $f->subprocess_env("AMF_FORCE_TO_DESKTOP" => 'true');
749 $f->pnotes("amf_force_to_desktop" => 'true');
750 }
751 $f->pnotes("amf_device_ismobile" => lc($ArrayCapFound{'IsMobile'}));
752 $f->subprocess_env("AMF_DEVICE_IS_MOBILE" => lc($ArrayCapFound{'IsMobile'}));
753 $f->subprocess_env("AMF_VER" => $VERSION);
754 $f->subprocess_env("AMF_DEGREES51_VER" => $DegreesVersion);
755 $f->headers_out->set("AMF-Ver"=> $VERSION);
756 if ($x_operamini_ua) {
757 $f->subprocess_env("AMF_MOBILE_BROWSER" => $x_operamini_ua);
758 $f->pnotes("mobile_browser" => $x_operamini_ua);
759 $f->subprocess_env("AMF_IS_TRANCODER" => 'true');
760 $f->pnotes("is_transcoder" => 'true');
761 }
762 return Apache2::Const::DECLINED;
763 }
764 1;
765  
766
767 =head1 NAME
768  
769 Apache2::AMF51DegreesFilter - The module detects the mobile device and passes the 51Degrees capabilities on to the other web application as environment variables
770  
771 =head1 DESCRIPTION
772  
773 Module for device detection, the cache is based on file system
774  
775 h=head1 AMF PROJECT SITE
776  
777 http://www.apachemobilefilter.org
778  
779 =head1 DOCUMENTATION
780  
781 http://wiki.apachemobilefilter.org
782  
783 Perl Module Documentation: http://wiki.apachemobilefilter.org/index.php/AMF51DegreesFilter
784  
785 =head1 AUTHOR
786  
787 Idel Fuschini (idel.fuschini [at] gmail [dot] com)
788  
789 =head1 COPYRIGHT
790  
791 You may distribute under the terms of either the GNU General Public
792 License or the Artistic License, as specified in the Perl README file.
793  
794 =cut
795