MobileComponent.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. App::uses('Component', 'Controller');
  3. App::uses('Router', 'Routing');
  4. /**
  5. * A component to easily serve mobile views to users.
  6. * It allows good default values while not being restrictive as you can always
  7. * overwrite the auto-detection manually to force desktop or mobile version.
  8. *
  9. * Uses Session to remember lookups: User.mobile and User.nomobile
  10. * - mobile is the auto-detection (true/false)
  11. * - nomobile can be set by the user and overrides the default behavior/detection
  12. * (1=true/0=false or -1=null which will remove the override)
  13. * Uses object attributes as well as Configure to store the results for later use.
  14. * It also pushes switch urls to the view.
  15. *
  16. * New:
  17. * - Support for named params has been dropped in favor of query strings.
  18. * - Support for different engines (vendor should be used as this is up to date).
  19. * - Allows Configure setup and auto-start for easy default cases.
  20. * - Accept closures to easily use any custom detection engine.
  21. * - Cleanup and tests
  22. *
  23. * @author Mark Scherer
  24. * @license MIT
  25. */
  26. class MobileComponent extends Component {
  27. public $components = array('Session');
  28. public $Controller = null;
  29. /**
  30. * Stores the result of the auto-detection.
  31. *
  32. * @var boolean
  33. */
  34. public $isMobile = null;
  35. /**
  36. * Stores the final detection result including user preference.
  37. *
  38. * @var boolean
  39. */
  40. public $setMobile = null;
  41. /**
  42. * Default values. Can also be set using Configure.
  43. *
  44. * @param array
  45. */
  46. protected $_defaults = array(
  47. 'on' => 'startup', // initialize (prior to controller's beforeRender) or startup
  48. 'engine' => 'vendor', // cake internal (deprecated), tools (deprecated) or vendor
  49. 'themed' => false, // If false uses subfolders instead of themes: /View/.../mobile/
  50. 'mobile' => array('mobile', 'tablet'), // what is mobile? tablets as well? only for vendor
  51. 'auto' => false, // auto set mobile views
  52. );
  53. /**
  54. * MobileComponent::__construct()
  55. *
  56. * @param ComponentCollection $collection
  57. * @param array $settings
  58. */
  59. public function __construct(ComponentCollection $collection, $settings = array()) {
  60. $settings = array_merge($this->_defaults, (array)Configure::read('Mobile'), $settings);
  61. parent::__construct($collection, $settings);
  62. }
  63. /**
  64. * MobileComponent::initialize()
  65. *
  66. * @param Controller $Controller
  67. * @return void
  68. */
  69. public function initialize(Controller $Controller) {
  70. parent::initialize($Controller);
  71. $this->Controller = $Controller;
  72. if ($this->settings['on'] !== 'initialize') {
  73. return;
  74. }
  75. $this->_init();
  76. }
  77. /**
  78. * MobileComponent::startup()
  79. *
  80. * @param Controller $Controller
  81. * @return void
  82. */
  83. public function startup(Controller $Controller) {
  84. parent::startup($Controller);
  85. if ($this->settings['on'] !== 'startup') {
  86. return;
  87. }
  88. $this->_init();
  89. }
  90. /**
  91. * Main auto-detection logic including session based storage to avoid
  92. * multiple lookups.
  93. *
  94. * Uses "mobile" query string to overwrite the auto-detection.
  95. * -1 clears the fixation
  96. * 1 forces mobile
  97. * 0 forces no-mobile
  98. *
  99. * @return void
  100. */
  101. protected function _init() {
  102. $mobileOverwrite = $this->Controller->request->query('mobile');
  103. if ($mobileOverwrite !== null) {
  104. if ($mobileOverwrite === '-1') {
  105. $noMobile = null;
  106. } else {
  107. $wantsMobile = (bool)$mobileOverwrite;
  108. $noMobile = (int)(!$wantsMobile);
  109. }
  110. $this->Session->write('User.nomobile', $noMobile);
  111. }
  112. $this->isMobile();
  113. if (!$this->settings['auto']) {
  114. return;
  115. }
  116. $this->setMobile();
  117. }
  118. /**
  119. * Serve mobile views if available
  120. *
  121. * can be called from beforeFilter() to automatically serve an alternative mobile view
  122. * if the file exists. If it doesn't exist in `/View/[ViewPath]/mobile/` the normal one
  123. * will be used.
  124. *
  125. * @deprecated in favor of themed solution?
  126. * @return void
  127. */
  128. public function serveMobileIfAvailable() {
  129. $viewDir = App::path('View');
  130. // returns an array
  131. /*
  132. * array(
  133. * (int) 0 => '/var/www/maps-cakephp2/app/View/'
  134. * )
  135. */
  136. $mobileViewFile = $viewDir[0] . $this->viewPath . DS . 'Mobile' . DS . $this->params['action'] . '.ctp';
  137. //Debugger::log($this->viewPath);
  138. // use this to log the output to
  139. // app/tmp/logs/debug.log
  140. if (file_exists($mobileViewFile)) {
  141. // if device is mobile, change layout to mobile
  142. // but only if a view exists for it.
  143. $this->layout = 'mobile';
  144. // and if a mobile view file has been
  145. // created for the action, serve it instead
  146. // of the default view file
  147. $this->viewPath = $this->viewPath . '/Mobile/';
  148. }
  149. }
  150. /**
  151. * Sets mobile views as `Mobile` theme.
  152. *
  153. * Only needs to be called if auto is set to false.
  154. * Then you probably want to call this from your AppController::beforeRender().
  155. *
  156. * @return void
  157. */
  158. public function setMobile() {
  159. if ($this->isMobile === null) {
  160. $this->isMobile();
  161. }
  162. $noMobile = $this->Session->read('User.nomobile');
  163. if (!$this->isMobile && $noMobile === null || $noMobile) {
  164. $this->setMobile = false;
  165. } else {
  166. $this->setMobile = true;
  167. }
  168. $urlParams = Router::getParams(true);
  169. if (!isset($urlParams['named'])) {
  170. $urlParams['named'] = array();
  171. }
  172. if (!isset($urlParams['pass'])) {
  173. $urlParams['pass'] = array();
  174. }
  175. $urlParams = array_merge($urlParams, $urlParams['named'], $urlParams['pass']);
  176. unset($urlParams['named']);
  177. unset($urlParams['pass']);
  178. if (isset($urlParams['prefix'])) {
  179. unset($urlParams['prefix']);
  180. }
  181. if ($this->setMobile) {
  182. $urlParams['?']['mobile'] = 0;
  183. $url = Router::url($urlParams);
  184. $this->Controller->set('desktopUrl', $url);
  185. } else {
  186. $urlParams['?']['mobile'] = 1;
  187. $url = Router::url($urlParams);
  188. $this->Controller->set('mobileUrl', $url);
  189. }
  190. Configure::write('User.isMobile', (int)$this->isMobile);
  191. Configure::write('User.setMobile', (int)$this->setMobile);
  192. if (!$this->setMobile) {
  193. return;
  194. }
  195. if (!$this->settings['themed']) {
  196. $this->serveMobileIfAvailable();
  197. return;
  198. }
  199. $this->Controller->viewClass = 'Theme';
  200. $this->Controller->theme = 'Mobile';
  201. }
  202. /**
  203. * Determines if we need to so serve mobile views based on session preference
  204. * and browser headers.
  205. *
  206. * @return boolean Success
  207. */
  208. public function isMobile() {
  209. if ($this->isMobile !== null) {
  210. return $this->isMobile;
  211. }
  212. $this->isMobile = $this->Session->read('User.mobile');
  213. if ($this->isMobile !== null) {
  214. return $this->isMobile;
  215. }
  216. $this->isMobile = (bool)$this->detect();
  217. $this->Session->write('User.mobile', (int)$this->isMobile);
  218. return $this->isMobile;
  219. }
  220. /**
  221. * Detects if the current request is from a mobile device.
  222. *
  223. * Note that the cake internal way might soon be deprecated:
  224. * https://github.com/cakephp/cakephp/issues/2546
  225. *
  226. * @return boolean Success
  227. */
  228. public function detect() {
  229. // Deprecated - the vendor libs are far more accurate and up to date
  230. if ($this->settings['engine'] === 'cake') {
  231. $this->Controller->request->addDetector('mobile', array('options' => array('OMNIA7')));
  232. return $this->Controller->request->is('mobile');
  233. }
  234. if (is_callable($this->settings['engine'])) {
  235. return call_user_func($this->settings['engine']);
  236. }
  237. if (!in_array($this->settings['engine'], array('tools', 'vendor'))) {
  238. throw new CakeException(__('Engine %s not available', $this->settings['engine']));
  239. }
  240. return $this->detectByVendor($this->settings['engine']);
  241. }
  242. /**
  243. * Simple auto-detection based on Tools plugin or vendor classes.
  244. *
  245. * @param string $engine
  246. * @return boolean Success
  247. */
  248. public function detectByVendor($engine) {
  249. $isMobile = $this->Session->read('Session.mobile');
  250. if ($isMobile !== null) {
  251. return $isMobile;
  252. }
  253. // Deprecated - the vendor libs are far more accurate and up to date
  254. if ($engine === 'tools') {
  255. App::uses('UserAgentLib', 'Tools.Lib');
  256. $UserAgentLib = new UserAgentLib();
  257. return (bool)$UserAgentLib->isMobile();
  258. }
  259. App::import('Vendor', 'Tools.MobileDetect', array('file' => 'MobileDetect/Mobile_Detect.php'));
  260. $MobileDetect = new Mobile_Detect();
  261. $result = empty($this->settings['mobile']) ? 0 : 1;
  262. if (in_array('mobile', $this->settings['mobile'])) {
  263. $result &= $MobileDetect->isMobile();
  264. }
  265. if (in_array('tablet', $this->settings['mobile'])) {
  266. $result |= $MobileDetect->isTablet();
  267. } else {
  268. $result &= !$MobileDetect->isTablet();
  269. }
  270. return (bool)$result;
  271. }
  272. }