Merge branch 'MDL-58454-master' of git://github.com/junpataleta/moodle
[moodle.git] / lib / classes / useragent.php
blob2e547086bd72673c1c6e49addaf248bbab3522f2
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Environment class to aid with the detection and establishment of the working environment.
20 * @package core
21 * @copyright 2013 Sam Hemelryk
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 /**
26 * The user agent class.
28 * It's important to note that we do not like browser sniffing and its use in core code is highly discouraged.
29 * No new uses of this API will be integrated unless there is absolutely no alternative.
31 * This API supports the few browser checks we do have in core, all of which one day will hopefully be removed.
32 * The API will remain to support any third party use out there, however at some point like all code it will be deprecated.
34 * Use sparingly and only with good cause!
36 * @package core
37 * @copyright 2013 Sam Hemelryk
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 class core_useragent {
42 /**
43 * The default for devices, think of as a computer.
45 const DEVICETYPE_DEFAULT = 'default';
46 /**
47 * Legacy devices, or at least legacy browsers. These are older devices/browsers
48 * that don't support standards.
50 const DEVICETYPE_LEGACY = 'legacy';
51 /**
52 * Mobile devices like your cell phone or hand held gaming device.
54 const DEVICETYPE_MOBILE = 'mobile';
55 /**
56 * Tables, larger than hand held, but still easily portable and smaller than a laptop.
58 const DEVICETYPE_TABLET = 'tablet';
60 /**
61 * An instance of this class.
62 * @var core_useragent
64 protected static $instance = null;
66 /**
67 * The device types we track.
68 * @var array
70 public static $devicetypes = array(
71 self::DEVICETYPE_DEFAULT,
72 self::DEVICETYPE_LEGACY,
73 self::DEVICETYPE_MOBILE,
74 self::DEVICETYPE_TABLET,
77 /**
78 * The current requests user agent string if there was one.
79 * @var string|bool|null Null until initialised, false if none available, or string when available.
81 protected $useragent = null;
83 /**
84 * The users device type, one of self::DEVICETYPE_*.
85 * @var string null until initialised
87 protected $devicetype = null;
89 /**
90 * Custom device types entered into the admin interface.
91 * @var array
93 protected $devicetypecustoms = array();
95 /**
96 * True if the user agent supports the display of svg images. False if not.
97 * @var bool|null Null until initialised, then true or false.
99 protected $supportssvg = null;
102 * Get an instance of the user agent object.
104 * @param bool $reload If set to true the user agent will be reset and all ascertations remade.
105 * @param string $forceuseragent The string to force as the user agent, don't use unless absolutely unavoidable.
106 * @return core_useragent
108 public static function instance($reload = false, $forceuseragent = null) {
109 if (!self::$instance || $reload) {
110 self::$instance = new core_useragent($forceuseragent);
112 return self::$instance;
116 * Constructs a new user agent object. Publically you must use the instance method above.
118 * @param string|null $forceuseragent Optional a user agent to force.
120 protected function __construct($forceuseragent = null) {
121 global $CFG;
122 if (!empty($CFG->devicedetectregex)) {
123 $this->devicetypecustoms = json_decode($CFG->devicedetectregex, true);
125 if ($this->devicetypecustoms === null) {
126 // This shouldn't happen unless you're hardcoding the config value.
127 debugging('Config devicedetectregex is not valid JSON object');
128 $this->devicetypecustoms = array();
130 if ($forceuseragent !== null) {
131 $this->useragent = $forceuseragent;
132 } else if (!empty($_SERVER['HTTP_USER_AGENT'])) {
133 $this->useragent = $_SERVER['HTTP_USER_AGENT'];
134 } else {
135 $this->useragent = false;
136 $this->devicetype = self::DEVICETYPE_DEFAULT;
141 * Returns the user agent string.
142 * @return bool|string The user agent string or false if one isn't available.
144 public static function get_user_agent_string() {
145 $instance = self::instance();
146 return $instance->useragent;
150 * Returns the device type we believe is being used.
151 * @return string
153 public static function get_device_type() {
154 $instance = self::instance();
155 if ($instance->devicetype === null) {
156 return $instance->guess_device_type();
158 return $instance->devicetype;
162 * Guesses the device type the user agent is running on.
164 * @return string
166 protected function guess_device_type() {
167 global $CFG;
168 if (empty($CFG->enabledevicedetection)) {
169 $this->devicetype = self::DEVICETYPE_DEFAULT;
170 return $this->devicetype;
172 foreach ($this->devicetypecustoms as $value => $regex) {
173 if (preg_match($regex, $this->useragent)) {
174 $this->devicetype = $value;
175 return $this->devicetype;
178 if ($this->is_useragent_mobile()) {
179 $this->devicetype = self::DEVICETYPE_MOBILE;
180 } else if ($this->is_useragent_tablet()) {
181 $this->devicetype = self::DEVICETYPE_TABLET;
182 } else if (self::check_ie_version('0') && !self::check_ie_version('7.0')) {
183 // IE 6 and before are considered legacy.
184 $this->devicetype = self::DEVICETYPE_LEGACY;
185 } else {
186 $this->devicetype = self::DEVICETYPE_DEFAULT;
188 return $this->devicetype;
192 * Returns true if the user appears to be on a mobile device.
193 * @return bool
195 protected function is_useragent_mobile() {
196 // Mobile detection PHP direct copy from open source detectmobilebrowser.com.
197 $phonesregex = '/android .+ mobile|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i';
198 $modelsregex = '/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i';
199 return (preg_match($phonesregex, $this->useragent) || preg_match($modelsregex, substr($this->useragent, 0, 4)));
203 * Returns true if the user appears to be on a tablet.
205 * @return int
207 protected function is_useragent_tablet() {
208 $tabletregex = '/Tablet browser|android|iPad|iProd|GT-P1000|GT-I9000|SHW-M180S|SGH-T849|SCH-I800|Build\/ERE27|sholest/i';
209 return (preg_match($tabletregex, $this->useragent));
213 * Whether the user agent relates to a web crawler.
214 * This includes all types of web crawler.
215 * @return bool
217 protected function is_useragent_web_crawler() {
218 $regex = '/Googlebot|google\.com|Yahoo! Slurp|\[ZSEBOT\]|msnbot|bingbot|BingPreview|Yandex|AltaVista|Baiduspider|Teoma/i';
219 return (preg_match($regex, $this->useragent));
223 * Gets a list of known device types.
225 * @param bool $includecustomtypes If set to true we'll include types that have been added by the admin.
226 * @return array
228 public static function get_device_type_list($includecustomtypes = true) {
229 $types = self::$devicetypes;
230 if ($includecustomtypes) {
231 $instance = self::instance();
232 $types = array_merge($types, array_keys($instance->devicetypecustoms));
234 return $types;
238 * Returns the theme to use for the given device type.
240 * This used to be get_selected_theme_for_device_type.
241 * @param null|string $devicetype The device type to find out for. Defaults to the device the user is using,
242 * @return bool
244 public static function get_device_type_theme($devicetype = null) {
245 global $CFG;
246 if ($devicetype === null) {
247 $devicetype = self::get_device_type();
249 $themevarname = self::get_device_type_cfg_var_name($devicetype);
250 if (empty($CFG->$themevarname)) {
251 return false;
253 return $CFG->$themevarname;
257 * Returns the CFG var used to find the theme to use for the given device.
259 * Used to be get_device_cfg_var_name.
261 * @param null|string $devicetype The device type to find out for. Defaults to the device the user is using,
262 * @return string
264 public static function get_device_type_cfg_var_name($devicetype = null) {
265 if ($devicetype == self::DEVICETYPE_DEFAULT || empty($devicetype)) {
266 return 'theme';
268 return 'theme' . $devicetype;
272 * Gets the device type the user is currently using.
273 * @return string
275 public static function get_user_device_type() {
276 $device = self::get_device_type();
277 $switched = get_user_preferences('switchdevice'.$device, false);
278 if ($switched != false) {
279 return $switched;
281 return $device;
285 * Switches the device type we think the user is using to what ever was given.
286 * @param string $newdevice
287 * @return bool
288 * @throws coding_exception
290 public static function set_user_device_type($newdevice) {
291 $devicetype = self::get_device_type();
292 if ($newdevice == $devicetype) {
293 unset_user_preference('switchdevice'.$devicetype);
294 return true;
295 } else {
296 $devicetypes = self::get_device_type_list();
297 if (in_array($newdevice, $devicetypes)) {
298 set_user_preference('switchdevice'.$devicetype, $newdevice);
299 return true;
302 throw new coding_exception('Invalid device type provided to set_user_device_type');
306 * Returns true if the user agent matches the given brand and the version is equal to or greater than that specified.
308 * @param string $brand The branch to check for.
309 * @param scalar $version The version if we need to find out if it is equal to or greater than that specified.
310 * @return bool
312 public static function check_browser_version($brand, $version = null) {
313 switch ($brand) {
315 case 'MSIE':
316 // Internet Explorer.
317 return self::check_ie_version($version);
319 case 'Edge':
320 // Microsoft Edge.
321 return self::check_edge_version($version);
323 case 'Firefox':
324 // Mozilla Firefox browsers.
325 return self::check_firefox_version($version);
327 case 'Chrome':
328 return self::check_chrome_version($version);
330 case 'Opera':
331 // Opera.
332 return self::check_opera_version($version);
334 case 'Safari':
335 // Desktop version of Apple Safari browser - no mobile or touch devices.
336 return self::check_safari_version($version);
338 case 'Safari iOS':
339 // Safari on iPhone, iPad and iPod touch.
340 return self::check_safari_ios_version($version);
342 case 'WebKit':
343 // WebKit based browser - everything derived from it (Safari, Chrome, iOS, Android and other mobiles).
344 return self::check_webkit_version($version);
346 case 'Gecko':
347 // Gecko based browsers.
348 return self::check_gecko_version($version);
350 case 'WebKit Android':
351 // WebKit browser on Android.
352 return self::check_webkit_android_version($version);
354 case 'Camino':
355 // OSX browser using Gecke engine.
356 return self::check_camino_version($version);
358 // Who knows?! doesn't pass anyway.
359 return false;
363 * Checks the user agent is camino based and that the version is equal to or greater than that specified.
365 * Camino browser is at the end of its life, its no longer being developed or supported, just don't worry about it.
367 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
368 * @return bool
370 protected static function check_camino_version($version = null) {
371 // OSX browser using Gecko engine.
372 $useragent = self::get_user_agent_string();
373 if ($useragent === false) {
374 return false;
376 if (strpos($useragent, 'Camino') === false) {
377 return false;
379 if (empty($version)) {
380 return true; // No version specified.
382 if (preg_match("/Camino\/([0-9\.]+)/i", $useragent, $match)) {
383 if (version_compare($match[1], $version) >= 0) {
384 return true;
387 return false;
391 * Checks the user agent is Firefox (of any version).
393 * @return bool true if firefox
395 public static function is_firefox() {
396 return self::check_firefox_version();
400 * Checks the user agent is Firefox based and that the version is equal to or greater than that specified.
402 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
403 * @return bool
405 public static function check_firefox_version($version = null) {
406 // Mozilla Firefox browsers.
407 $useragent = self::get_user_agent_string();
408 if ($useragent === false) {
409 return false;
411 if (strpos($useragent, 'Firefox') === false && strpos($useragent, 'Iceweasel') === false) {
412 return false;
414 if (empty($version)) {
415 return true; // No version specified..
417 if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $useragent, $match)) {
418 if (version_compare($match[2], $version) >= 0) {
419 return true;
422 return false;
426 * Checks the user agent is Gecko based (of any version).
428 * @return bool true if Gecko based.
430 public static function is_gecko() {
431 return self::check_gecko_version();
435 * Checks the user agent is Gecko based and that the version is equal to or greater than that specified.
437 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
438 * @return bool
440 public static function check_gecko_version($version = null) {
441 // Gecko based browsers.
442 // Do not look for dates any more, we expect real Firefox version here.
443 $useragent = self::get_user_agent_string();
444 if ($useragent === false) {
445 return false;
447 if (empty($version)) {
448 $version = 1;
449 } else if ($version > 20000000) {
450 // This is just a guess, it is not supposed to be 100% accurate!
451 if (preg_match('/^201/', $version)) {
452 $version = 3.6;
453 } else if (preg_match('/^200[7-9]/', $version)) {
454 $version = 3;
455 } else if (preg_match('/^2006/', $version)) {
456 $version = 2;
457 } else {
458 $version = 1.5;
461 if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $useragent, $match)) {
462 // Use real Firefox version if specified in user agent string.
463 if (version_compare($match[2], $version) >= 0) {
464 return true;
466 } else if (preg_match("/Gecko\/([0-9\.]+)/i", $useragent, $match)) {
467 // Gecko might contain date or Firefox revision, let's just guess the Firefox version from the date.
468 $browserver = $match[1];
469 if ($browserver > 20000000) {
470 // This is just a guess, it is not supposed to be 100% accurate!
471 if (preg_match('/^201/', $browserver)) {
472 $browserver = 3.6;
473 } else if (preg_match('/^200[7-9]/', $browserver)) {
474 $browserver = 3;
475 } else if (preg_match('/^2006/', $version)) {
476 $browserver = 2;
477 } else {
478 $browserver = 1.5;
481 if (version_compare($browserver, $version) >= 0) {
482 return true;
485 return false;
489 * Checks the user agent is Edge (of any version).
491 * @return bool true if Edge
493 public static function is_edge() {
494 return self::check_edge_version();
498 * Check the User Agent for the version of Edge.
500 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
501 * @return bool
503 public static function check_edge_version($version = null) {
504 $useragent = self::get_user_agent_string();
506 if ($useragent === false) {
507 // No User Agent found.
508 return false;
511 if (strpos($useragent, 'Edge/') === false) {
512 // Edge was not found in the UA - this is not Edge.
513 return false;
516 if (empty($version)) {
517 // No version to check.
518 return true;
521 // Find the version.
522 // Edge versions are always in the format:
523 // Edge/<version>.<OS build number>
524 preg_match('%Edge/([\d]+)\.(.*)$%', $useragent, $matches);
526 // Just to be safe, round the version being tested.
527 // Edge only uses integer versions - the second component is the OS build number.
528 $version = round($version);
530 // Check whether the version specified is >= the version found.
531 return version_compare($matches[1], $version, '>=');
535 * Checks the user agent is IE (of any version).
537 * @return bool true if internet exporeer
539 public static function is_ie() {
540 return self::check_ie_version();
544 * Checks the user agent is IE and returns its main properties:
545 * - browser version;
546 * - whether running in compatibility view.
548 * @return bool|array False if not IE, otherwise an associative array of properties.
550 public static function check_ie_properties() {
551 // Internet Explorer.
552 $useragent = self::get_user_agent_string();
553 if ($useragent === false) {
554 return false;
556 if (strpos($useragent, 'Opera') !== false) {
557 // Reject Opera.
558 return false;
560 // See: http://www.useragentstring.com/pages/Internet%20Explorer/.
561 if (preg_match("/MSIE ([0-9\.]+)/", $useragent, $match)) {
562 $browser = $match[1];
563 // See: http://msdn.microsoft.com/en-us/library/ie/bg182625%28v=vs.85%29.aspx for IE11+ useragent details.
564 } else if (preg_match("/Trident\/[0-9\.]+/", $useragent) && preg_match("/rv:([0-9\.]+)/", $useragent, $match)) {
565 $browser = $match[1];
566 } else {
567 return false;
570 $compatview = false;
571 // IE8 and later versions may pretend to be IE7 for intranet sites, use Trident version instead,
572 // the Trident should always describe the capabilities of IE in any emulation mode.
573 if ($browser === '7.0' and preg_match("/Trident\/([0-9\.]+)/", $useragent, $match)) {
574 $compatview = true;
575 $browser = $match[1] + 4; // NOTE: Hopefully this will work also for future IE versions.
577 $browser = round($browser, 1);
578 return array(
579 'version' => $browser,
580 'compatview' => $compatview
585 * Checks the user agent is IE and that the version is equal to or greater than that specified.
587 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
588 * @return bool
590 public static function check_ie_version($version = null) {
591 // Internet Explorer.
592 $properties = self::check_ie_properties();
593 if (!is_array($properties)) {
594 return false;
596 // In case of IE we have to deal with BC of the version parameter.
597 if (is_null($version)) {
598 $version = 5.5; // Anything older is not considered a browser at all!
600 // IE uses simple versions, let's cast it to float to simplify the logic here.
601 $version = round($version, 1);
602 return ($properties['version'] >= $version);
606 * Checks the user agent is IE and that IE is running under Compatibility View setting.
608 * @return bool true if internet explorer runs in Compatibility View mode.
610 public static function check_ie_compatibility_view() {
611 // IE User Agent string when in Compatibility View:
612 // - IE 8: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; ...)".
613 // - IE 9: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; ...)".
614 // - IE 10: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/6.0; ...)".
615 // - IE 11: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; ...)".
616 // Refs:
617 // - http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx.
618 // - http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx.
619 // - http://blogs.msdn.com/b/ie/archive/2011/04/15/the-ie10-user-agent-string.aspx.
620 // - http://msdn.microsoft.com/en-us/library/ie/hh869301%28v=vs.85%29.aspx.
621 $properties = self::check_ie_properties();
622 if (!is_array($properties)) {
623 return false;
625 return $properties['compatview'];
629 * Checks the user agent is Opera (of any version).
631 * @return bool true if opera
633 public static function is_opera() {
634 return self::check_opera_version();
638 * Checks the user agent is Opera and that the version is equal to or greater than that specified.
640 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
641 * @return bool
643 public static function check_opera_version($version = null) {
644 // Opera.
645 $useragent = self::get_user_agent_string();
646 if ($useragent === false) {
647 return false;
649 if (strpos($useragent, 'Opera') === false) {
650 return false;
652 if (empty($version)) {
653 return true; // No version specified.
655 // Recent Opera useragents have Version/ with the actual version, e.g.:
656 // Opera/9.80 (Windows NT 6.1; WOW64; U; en) Presto/2.10.289 Version/12.01
657 // That's Opera 12.01, not 9.8.
658 if (preg_match("/Version\/([0-9\.]+)/i", $useragent, $match)) {
659 if (version_compare($match[1], $version) >= 0) {
660 return true;
662 } else if (preg_match("/Opera\/([0-9\.]+)/i", $useragent, $match)) {
663 if (version_compare($match[1], $version) >= 0) {
664 return true;
667 return false;
671 * Checks the user agent is webkit based
673 * @return bool true if webkit
675 public static function is_webkit() {
676 return self::check_webkit_version();
680 * Checks the user agent is Webkit based and that the version is equal to or greater than that specified.
682 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
683 * @return bool
685 public static function check_webkit_version($version = null) {
686 // WebKit based browser - everything derived from it (Safari, Chrome, iOS, Android and other mobiles).
687 $useragent = self::get_user_agent_string();
688 if ($useragent === false) {
689 return false;
691 if (strpos($useragent, 'AppleWebKit') === false) {
692 return false;
694 if (empty($version)) {
695 return true; // No version specified.
697 if (preg_match("/AppleWebKit\/([0-9.]+)/i", $useragent, $match)) {
698 if (version_compare($match[1], $version) >= 0) {
699 return true;
702 return false;
706 * Checks the user agent is Safari
708 * @return bool true if safari
710 public static function is_safari() {
711 return self::check_safari_version();
715 * Checks the user agent is Safari based and that the version is equal to or greater than that specified.
717 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
718 * @return bool
720 public static function check_safari_version($version = null) {
721 // Desktop version of Apple Safari browser - no mobile or touch devices.
722 $useragent = self::get_user_agent_string();
723 if ($useragent === false) {
724 return false;
726 if (strpos($useragent, 'AppleWebKit') === false) {
727 return false;
729 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SymbianOS and any other mobile devices.
730 if (strpos($useragent, 'OmniWeb')) {
731 // Reject OmniWeb.
732 return false;
734 if (strpos($useragent, 'Shiira')) {
735 // Reject Shiira.
736 return false;
738 if (strpos($useragent, 'SymbianOS')) {
739 // Reject SymbianOS.
740 return false;
742 if (strpos($useragent, 'Android')) {
743 // Reject Androids too.
744 return false;
746 if (strpos($useragent, 'iPhone') or strpos($useragent, 'iPad') or strpos($useragent, 'iPod')) {
747 // No Apple mobile devices here - editor does not work, course ajax is not touch compatible, etc.
748 return false;
750 if (strpos($useragent, 'Chrome')) {
751 // Reject chrome browsers - it needs to be tested explicitly.
752 // This will also reject Edge, which pretends to be both Chrome, and Safari.
753 return false;
756 if (empty($version)) {
757 return true; // No version specified.
759 if (preg_match("/AppleWebKit\/([0-9.]+)/i", $useragent, $match)) {
760 if (version_compare($match[1], $version) >= 0) {
761 return true;
764 return false;
768 * Checks the user agent is Chrome
770 * @return bool true if chrome
772 public static function is_chrome() {
773 return self::check_chrome_version();
777 * Checks the user agent is Chrome based and that the version is equal to or greater than that specified.
779 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
780 * @return bool
782 public static function check_chrome_version($version = null) {
783 // Chrome.
784 $useragent = self::get_user_agent_string();
785 if ($useragent === false) {
786 return false;
788 if (strpos($useragent, 'Chrome') === false) {
789 return false;
791 if (empty($version)) {
792 return true; // No version specified.
794 if (preg_match("/Chrome\/(.*)[ ]+/i", $useragent, $match)) {
795 if (version_compare($match[1], $version) >= 0) {
796 return true;
799 return false;
803 * Checks the user agent is webkit android based.
805 * @return bool true if webkit based and on Android
807 public static function is_webkit_android() {
808 return self::check_webkit_android_version();
812 * Checks the user agent is Webkit based and on Android and that the version is equal to or greater than that specified.
814 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
815 * @return bool
817 public static function check_webkit_android_version($version = null) {
818 // WebKit browser on Android.
819 $useragent = self::get_user_agent_string();
820 if ($useragent === false) {
821 return false;
823 if (strpos($useragent, 'Android') === false) {
824 return false;
826 if (empty($version)) {
827 return true; // No version specified.
829 if (preg_match("/AppleWebKit\/([0-9]+)/i", $useragent, $match)) {
830 if (version_compare($match[1], $version) >= 0) {
831 return true;
834 return false;
838 * Checks the user agent is Safari on iOS
840 * @return bool true if Safari on iOS
842 public static function is_safari_ios() {
843 return self::check_safari_ios_version();
847 * Checks the user agent is Safari on iOS and that the version is equal to or greater than that specified.
849 * @param string|int $version A version to check for, returns true if its equal to or greater than that specified.
850 * @return bool
852 public static function check_safari_ios_version($version = null) {
853 // Safari on iPhone, iPad and iPod touch.
854 $useragent = self::get_user_agent_string();
855 if ($useragent === false) {
856 return false;
858 if (strpos($useragent, 'AppleWebKit') === false or strpos($useragent, 'Safari') === false) {
859 return false;
861 if (!strpos($useragent, 'iPhone') and !strpos($useragent, 'iPad') and !strpos($useragent, 'iPod')) {
862 return false;
864 if (empty($version)) {
865 return true; // No version specified.
867 if (preg_match("/AppleWebKit\/([0-9]+)/i", $useragent, $match)) {
868 if (version_compare($match[1], $version) >= 0) {
869 return true;
872 return false;
876 * Checks if the user agent is MS Word.
877 * Not perfect, as older versions of Word use standard IE6/7 user agents without any identifying traits.
879 * @return bool true if user agent could be identified as MS Word.
881 public static function is_msword() {
882 $useragent = self::get_user_agent_string();
883 if (!preg_match('/(\bWord\b|ms-office|MSOffice|Microsoft Office)/i', $useragent)) {
884 return false;
885 } else if (strpos($useragent, 'Outlook') !== false) {
886 return false;
887 } else if (strpos($useragent, 'Meridio') !== false) {
888 return false;
890 // It's Office, not Outlook and not Meridio - so it's probably Word, but we can't really be sure in most cases.
891 return true;
895 * Check if the user agent matches a given brand.
897 * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
899 * @param string $brand
900 * @return bool
902 public static function check_browser_operating_system($brand) {
903 $useragent = self::get_user_agent_string();
904 return ($useragent !== false && preg_match("/$brand/i", $useragent));
908 * Gets an array of CSS classes to represent the user agent.
909 * @return array
911 public static function get_browser_version_classes() {
912 $classes = array();
913 if (self::is_edge()) {
914 $classes[] = 'edge';
915 } else if (self::is_ie()) {
916 $classes[] = 'ie';
917 for ($i = 12; $i >= 6; $i--) {
918 if (self::check_ie_version($i)) {
919 $classes[] = 'ie'.$i;
920 break;
923 } else if (self::is_firefox() || self::is_gecko() || self::check_camino_version()) {
924 $classes[] = 'gecko';
925 if (preg_match('/rv\:([1-2])\.([0-9])/', self::get_user_agent_string(), $matches)) {
926 $classes[] = "gecko{$matches[1]}{$matches[2]}";
928 } else if (self::is_chrome()) {
929 $classes[] = 'chrome';
930 if (self::is_webkit_android()) {
931 $classes[] = 'android';
933 } else if (self::is_webkit()) {
934 if (self::is_safari()) {
935 $classes[] = 'safari';
937 if (self::is_safari_ios()) {
938 $classes[] = 'ios';
939 } else if (self::is_webkit_android()) {
940 $classes[] = 'android'; // Old pre-Chrome android browsers.
942 } else if (self::is_opera()) {
943 $classes[] = 'opera';
945 return $classes;
949 * Returns true if the user agent supports the display of SVG images.
951 * @return bool
953 public static function supports_svg() {
954 // IE 5 - 8 don't support SVG at all.
955 $instance = self::instance();
956 if ($instance->supportssvg === null) {
957 if ($instance->useragent === false) {
958 // Can't be sure, just say no.
959 $instance->supportssvg = false;
960 } else if (self::check_ie_version('0') and !self::check_ie_version('9')) {
961 // IE < 9 doesn't support SVG. Say no.
962 $instance->supportssvg = false;
963 } else if (self::is_ie() and !self::check_ie_version('10') and self::check_ie_compatibility_view()) {
964 // IE 9 Compatibility View doesn't support SVG. Say no.
965 $instance->supportssvg = false;
966 } else if (preg_match('#Android +[0-2]\.#', $instance->useragent)) {
967 // Android < 3 doesn't support SVG. Say no.
968 $instance->supportssvg = false;
969 } else if (self::is_opera()) {
970 // Opera 12 still does not support SVG well enough. Say no.
971 $instance->supportssvg = false;
972 } else {
973 // Presumed fine.
974 $instance->supportssvg = true;
977 return $instance->supportssvg;
981 * Returns true if the user agent supports the MIME media type for JSON text, as defined in RFC 4627.
983 * @return bool
985 public static function supports_json_contenttype() {
986 // Modern browsers other than IE correctly supports 'application/json' media type.
987 if (!self::check_ie_version('0')) {
988 return true;
991 // IE8+ supports 'application/json' media type, when NOT in Compatibility View mode.
992 // Refs:
993 // - http://blogs.msdn.com/b/ie/archive/2008/09/10/native-json-in-ie8.aspx;
994 // - MDL-39810: issues when using 'text/plain' in Compatibility View for the body of an HTTP POST response.
995 if (self::check_ie_version(8) && !self::check_ie_compatibility_view()) {
996 return true;
999 // This browser does not support json.
1000 return false;
1004 * Returns true if the client appears to be some kind of web crawler.
1005 * This may include other types of crawler.
1007 * @return bool
1009 public static function is_web_crawler() {
1010 $instance = self::instance();
1011 return (bool) $instance->is_useragent_web_crawler();
1015 * Returns true if the client appears to be a device using iOS (iPhone, iPad, iPod).
1017 * @param scalar $version The version if we need to find out if it is equal to or greater than that specified.
1018 * @return bool true if the client is using iOS
1019 * @since Moodle 3.2
1021 public static function is_ios($version = null) {
1022 $useragent = self::get_user_agent_string();
1023 if ($useragent === false) {
1024 return false;
1026 if (strpos($useragent, 'AppleWebKit') === false) {
1027 return false;
1029 if (strpos($useragent, 'Windows')) {
1030 // Reject Windows Safari.
1031 return false;
1033 if (strpos($useragent, 'Macintosh')) {
1034 // Reject MacOS Safari.
1035 return false;
1037 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SymbianOS and any other mobile devices.
1038 if (strpos($useragent, 'OmniWeb')) {
1039 // Reject OmniWeb.
1040 return false;
1042 if (strpos($useragent, 'Shiira')) {
1043 // Reject Shiira.
1044 return false;
1046 if (strpos($useragent, 'SymbianOS')) {
1047 // Reject SymbianOS.
1048 return false;
1050 if (strpos($useragent, 'Android')) {
1051 // Reject Androids too.
1052 return false;
1054 if (strpos($useragent, 'Chrome')) {
1055 // Reject chrome browsers - it needs to be tested explicitly.
1056 // This will also reject Edge, which pretends to be both Chrome, and Safari.
1057 return false;
1060 if (empty($version)) {
1061 return true; // No version specified.
1063 if (preg_match("/AppleWebKit\/([0-9.]+)/i", $useragent, $match)) {
1064 if (version_compare($match[1], $version) >= 0) {
1065 return true;
1068 return false;
1072 * Checks if current browser supports files with give extension as <video> or <audio> source
1074 * Note, the check here is not 100% accurate!
1076 * First, we do not know which codec is used in .mp4 or .webm files. Not all browsers support
1077 * all codecs.
1079 * Also we assume that users of Firefox/Chrome/Safari do not use the ancient versions of browsers.
1081 * We check the exact version for IE/Edge though. We know that there are still users of very old
1082 * versions that are afraid to upgrade or have slow IT department.
1084 * Resources:
1085 * https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats
1086 * https://en.wikipedia.org/wiki/HTML5_video
1087 * https://en.wikipedia.org/wiki/HTML5_Audio
1089 * @param string $extension extension without leading .
1090 * @return bool
1092 public static function supports_html5($extension) {
1093 $extension = strtolower($extension);
1095 $supportedvideo = array('m4v', 'webm', 'ogv', 'mp4', 'mov');
1096 $supportedaudio = array('ogg', 'oga', 'aac', 'm4a', 'mp3', 'wav');
1097 // TODO MDL-56549 Flac will be supported in Firefox 51 in January 2017.
1099 // Basic extension support.
1100 if (!in_array($extension, $supportedvideo) && !in_array($extension, $supportedaudio)) {
1101 return false;
1104 // MS IE support - version 9.0 or later.
1105 if (self::is_ie() && !self::check_ie_version('9.0')) {
1106 return false;
1109 // MS Edge support - version 12.0 for desktop and 13.0 for mobile.
1110 if (self::is_edge()) {
1111 if (!self::check_edge_version('12.0')) {
1112 return false;
1114 if (self::instance()->is_useragent_mobile() && !self::check_edge_version('13.0')) {
1115 return false;
1119 // Different exceptions.
1121 // Webm is not supported in IE, Edge and in Safari.
1122 if ($extension === 'webm' &&
1123 (self::is_ie() || self::is_edge() || self::is_safari() || self::is_safari_ios())) {
1124 return false;
1126 // Ogg is not supported in IE, Edge and Safari.
1127 $isogg = in_array($extension, ['ogg', 'oga', 'ogv']);
1128 if ($isogg && (self::is_ie() || self::is_edge() || self::is_safari() || self::is_safari_ios())) {
1129 return false;
1131 // Wave is not supported in IE.
1132 if ($extension === 'wav' && self::is_ie()) {
1133 return false;
1135 // Aac is not supported in IE below 11.0.
1136 if ($extension === 'aac' && (self::is_ie() && !self::check_ie_version('11.0'))) {
1137 return false;
1139 // Mpeg is not supported in IE below 10.0.
1140 $ismpeg = in_array($extension, ['m4a', 'mp3', 'm4v', 'mp4']);
1141 if ($ismpeg && (self::is_ie() && !self::check_ie_version('10.0'))) {
1142 return false;
1144 // Mov is not supported in IE.
1145 if ($extension === 'mov' && self::is_ie()) {
1146 return false;
1149 return true;