public function detection() { Piwik::checkUserHasSomeAdminAccess(); $view = new View('@DevicesDetection/detection'); $this->setBasicVariablesView($view); ControllerAdmin::setBasicVariablesAdminView($view); $userAgent = Common::getRequestVar('ua', $_SERVER['HTTP_USER_AGENT'], 'string'); $uaParser = new DeviceDetector($userAgent); $uaParser->parse(); $view->userAgent = $userAgent; $view->browser_name = $uaParser->getClient('name'); $view->browser_short_name = $uaParser->getClient('short_name'); $view->browser_version = $uaParser->getClient('version'); $view->browser_logo = getBrowserLogo($uaParser->getClient('short_name')); $view->browser_family = \DeviceDetector\Parser\Client\Browser::getBrowserFamily($uaParser->getClient('short_name')); $view->browser_family_logo = getBrowserFamilyLogo($view->browser_family); $view->os_name = $uaParser->getOs('name'); $view->os_logo = getOsLogo($uaParser->getOs('short_name')); $view->os_short_name = $uaParser->getOs('short_name'); $view->os_family = \DeviceDetector\Parser\OperatingSystem::getOsFamily($uaParser->getOs('short_name')); $view->os_family_logo = getOsFamilyLogo($view->os_family); $view->os_version = $uaParser->getOs('version'); $view->device_type = getDeviceTypeLabel($uaParser->getDeviceName()); $view->device_type_logo = getDeviceTypeLogo($uaParser->getDeviceName()); $view->device_model = $uaParser->getModel(); $view->device_brand = getDeviceBrandLabel($uaParser->getBrand()); $view->device_brand_logo = getBrandLogo($uaParser->getBrand()); return $view->render(); }
/** * Parse UA string and fill in other attributes */ public function parse() { $dd = new DeviceDetector($this->user_agent); // only return true if a bot was detected (speeds up detection a bit) $dd->discardBotInformation(); $dd->parse(); if ($dd->isBot()) { $this->bot = 1; } else { $client = $dd->getClient(); if ($this->counts_as_bot($client)) { $this->bot = 1; return $this; } if (isset($client['name'])) { $this->client_name = $client['name']; } if (isset($client['version'])) { $this->client_version = $client['version']; } if (isset($client['type'])) { $this->client_type = $client['type']; } $os = $dd->getOs(); if (isset($os['name'])) { $this->os_name = $os['name']; } if (isset($os['version'])) { $this->os_version = $os['version']; } $this->device_brand = $dd->getBrand(); $this->device_model = $dd->getModel(); } return $this; }
public function detect($userAgent = null, $advanced = false) { $userAgent = $userAgent ?: env('HTTP_USER_AGENT'); DeviceParserAbstract::setVersionTruncation(DeviceParserAbstract::VERSION_TRUNCATION_NONE); $detect = new DeviceDetector($userAgent); $detect->parse(); $return = []; if ($detect->isBot()) { $return['bot'] = $detect->getBot(); return $return; } //device wrapper $devicelist = ['desktop' => 'computer', 'smartphone' => 'phone', 'tablet' => 'tablet', 'feature phone' => 'phone']; $os = $detect->getOs(); $client = $detect->getClient(); $devicename = $detect->getDeviceName(); $devicetype = isset($devicelist[$devicename]) ? $devicelist[$devicename] : 'computer'; //legacy params $return['device'] = $devicename; $return['type'] = $devicetype; $return['brand'] = $detect->getBrandName(); $return['os'] = $os['name']; $return['os_version'] = $os['version']; $return['os_code'] = $os['short_name']; $return['browser'] = $client['name']; $return['browser_version'] = $client['version']; $return['browser_code'] = $client['short_name']; $return['browser_type'] = $client['type']; $return['browser_engine'] = $client['engine']; if (!$advanced) { return array_map('trim', $return); } //advanced params $osFamily = OperatingSystem::getOsFamily($os['short_name']); $return['os_family'] = $osFamily !== false ? $osFamily : 'Unknown'; $return['model'] = $detect->getModel(); $browserFamily = Browser::getBrowserFamily($client['short_name']); $return['browser_family'] = $browserFamily !== false ? $browserFamily : 'Unknown'; $touch = $detect->isTouchEnabled(); $return['touch'] = $touch[0]; unset($os, $client, $osFamily, $browserFamily, $touch); return array_map('trim', $return); }
/** * Parses a useragent and returns the detected data * * ATTENTION: Use that method only for testing or very small applications * To get fast results from DeviceDetector you need to make your own implementation, * that should use one of the caching mechanisms. See README.md for more information. * * @internal * @deprecated * * @param string $ua UserAgent to parse * * @return array */ public static function getInfoFromUserAgent($ua) { $deviceDetector = new DeviceDetector($ua); $deviceDetector->parse(); if ($deviceDetector->isBot()) { return array('user_agent' => $deviceDetector->getUserAgent(), 'bot' => $deviceDetector->getBot()); } $osFamily = OperatingSystem::getOsFamily($deviceDetector->getOs('short_name')); $browserFamily = \DeviceDetector\Parser\Client\Browser::getBrowserFamily($deviceDetector->getClient('short_name')); $processed = array('user_agent' => $deviceDetector->getUserAgent(), 'os' => $deviceDetector->getOs(), 'client' => $deviceDetector->getClient(), 'device' => array('type' => $deviceDetector->getDeviceName(), 'brand' => $deviceDetector->getBrand(), 'model' => $deviceDetector->getModel()), 'os_family' => $osFamily !== false ? $osFamily : 'Unknown', 'browser_family' => $browserFamily !== false ? $browserFamily : 'Unknown'); return $processed; }
/** * @param string|Stat $stat * @param $request * @param bool $viaBrowser */ public function hitEmail($stat, $request, $viaBrowser = false) { if (!$stat instanceof Stat) { $stat = $this->getEmailStatus($stat); } if (!$stat) { return; } $email = $stat->getEmail(); if ((int) $stat->isRead()) { if ($viaBrowser && !$stat->getViewedInBrowser()) { //opened via browser so note it $stat->setViewedInBrowser($viaBrowser); } } $readDateTime = new DateTimeHelper(); $stat->setLastOpened($readDateTime->getDateTime()); $lead = $stat->getLead(); if ($lead !== null) { // Set the lead as current lead $this->leadModel->setCurrentLead($lead); } $firstTime = false; if (!$stat->getIsRead()) { $firstTime = true; $stat->setIsRead(true); $stat->setDateRead($readDateTime->getDateTime()); // Only up counts if associated with both an email and lead if ($email && $lead) { try { $this->getRepository()->upCount($email->getId(), 'read', 1, $email->isVariant()); } catch (\Exception $exception) { error_log($exception); } } } if ($viaBrowser) { $stat->setViewedInBrowser($viaBrowser); } $stat->addOpenDetails(['datetime' => $readDateTime->toUtcString(), 'useragent' => $request->server->get('HTTP_USER_AGENT'), 'inBrowser' => $viaBrowser]); //check for existing IP $ipAddress = $this->ipLookupHelper->getIpAddress(); $stat->setIpAddress($ipAddress); if ($this->dispatcher->hasListeners(EmailEvents::EMAIL_ON_OPEN)) { $event = new EmailOpenEvent($stat, $request, $firstTime); $this->dispatcher->dispatch(EmailEvents::EMAIL_ON_OPEN, $event); } //device granularity $dd = new DeviceDetector($request->server->get('HTTP_USER_AGENT')); $dd->parse(); $deviceRepo = $this->leadModel->getDeviceRepository(); $emailOpenDevice = $deviceRepo->getDevice(null, $lead, $dd->getDeviceName(), $dd->getBrand(), $dd->getModel()); if (empty($emailOpenDevice)) { $emailOpenDevice = new LeadDevice(); $emailOpenDevice->setClientInfo($dd->getClient()); $emailOpenDevice->setDevice($dd->getDeviceName()); $emailOpenDevice->setDeviceBrand($dd->getBrand()); $emailOpenDevice->setDeviceModel($dd->getModel()); $emailOpenDevice->setDeviceOs($dd->getOs()); $emailOpenDevice->setDateOpen($readDateTime->toUtcString()); $emailOpenDevice->setLead($lead); try { $this->em->persist($emailOpenDevice); $this->em->flush($emailOpenDevice); } catch (\Exception $exception) { if (MAUTIC_ENV === 'dev') { throw $exception; } else { $this->logger->addError($exception->getMessage(), ['exception' => $exception]); } } } else { $emailOpenDevice = $deviceRepo->getEntity($emailOpenDevice['id']); } if ($email) { $this->em->persist($email); $this->em->flush($email); } if (isset($emailOpenDevice) and is_object($emailOpenDevice)) { $emailOpenStat = new StatDevice(); $emailOpenStat->setIpAddress($ipAddress); $emailOpenStat->setDevice($emailOpenDevice); $emailOpenStat->setDateOpened($readDateTime->toUtcString()); $emailOpenStat->setStat($stat); $this->em->persist($emailOpenStat); $this->em->flush($emailOpenStat); } $this->em->persist($stat); $this->em->flush(); }
/** * Record page hit. * * @param $page * @param Request $request * @param string $code * @param Lead|null $lead * @param array $query * * @return Hit $hit * * @throws \Exception */ public function hitPage($page, Request $request, $code = '200', Lead $lead = null, $query = []) { // Don't skew results with user hits if (!$this->security->isAnonymous()) { return; } // Process the query if (empty($query)) { $query = $this->getHitQuery($request, $page); } $hit = new Hit(); $hit->setDateHit(new \Datetime()); // Check for existing IP $ipAddress = $this->ipLookupHelper->getIpAddress(); $hit->setIpAddress($ipAddress); // Check for any clickthrough info $clickthrough = []; if (!empty($query['ct'])) { $clickthrough = $query['ct']; if (!is_array($clickthrough)) { $clickthrough = $this->decodeArrayFromUrl($clickthrough); } if (!empty($clickthrough['channel'])) { if (count($clickthrough['channel']) === 1) { $channelId = reset($clickthrough['channel']); $channel = key($clickthrough['channel']); } else { $channel = $clickthrough['channel'][0]; $channelId = (int) $clickthrough['channel'][1]; } $hit->setSource($channel); $hit->setSourceId($channelId); } elseif (!empty($clickthrough['source'])) { $hit->setSource($clickthrough['source'][0]); $hit->setSourceId($clickthrough['source'][1]); } if (!empty($clickthrough['email'])) { $emailRepo = $this->em->getRepository('MauticEmailBundle:Email'); if ($emailEntity = $emailRepo->getEntity($clickthrough['email'])) { $hit->setEmail($emailEntity); } } } // Get lead if required if (null == $lead) { $lead = $this->leadModel->getContactFromRequest($query); } $this->leadModel->saveEntity($lead); // Set info from request $hit->setQuery($query); $hit->setUrl(isset($query['page_url']) ? $query['page_url'] : $request->getRequestUri()); if (isset($query['page_referrer'])) { $hit->setReferer($query['page_referrer']); } if (isset($query['page_language'])) { $hit->setPageLanguage($query['page_language']); } if (isset($query['page_title'])) { $hit->setUrlTitle($query['page_title']); } // Store tracking ID list($trackingId, $trackingNewlyGenerated) = $this->leadModel->getTrackingCookie(); $hit->setTrackingId($trackingId); $hit->setLead($lead); $isUnique = $trackingNewlyGenerated; if (!$trackingNewlyGenerated) { $lastHit = $request->cookies->get('mautic_referer_id'); if (!empty($lastHit)) { //this is not a new session so update the last hit if applicable with the date/time the user left $this->getHitRepository()->updateHitDateLeft($lastHit); } // Check if this is a unique page hit $isUnique = $this->getHitRepository()->isUniquePageHit($page, $trackingId); } if (!empty($page)) { if ($page instanceof Page) { $hit->setPage($page); $hit->setPageLanguage($page->getLanguage()); $isVariant = $isUnique ? $page->getVariantStartDate() : false; try { $this->getRepository()->upHitCount($page->getId(), 1, $isUnique, !empty($isVariant)); } catch (\Exception $exception) { $this->logger->addError($exception->getMessage(), ['exception' => $exception]); } } elseif ($page instanceof Redirect) { $hit->setRedirect($page); try { $this->pageRedirectModel->getRepository()->upHitCount($page->getId(), 1, $isUnique); // If this is a trackable, up the trackable counts as well if (!empty($clickthrough['channel'])) { $channelId = reset($clickthrough['channel']); $channel = key($clickthrough['channel']); $this->pageTrackableModel->getRepository()->upHitCount($page->getId(), $channel, $channelId, 1, $isUnique); } } catch (\Exception $exception) { if (MAUTIC_ENV === 'dev') { throw $exception; } else { $this->logger->addError($exception->getMessage(), ['exception' => $exception]); } } } } //glean info from the IP address if ($details = $ipAddress->getIpDetails()) { $hit->setCountry($details['country']); $hit->setRegion($details['region']); $hit->setCity($details['city']); $hit->setIsp($details['isp']); $hit->setOrganization($details['organization']); } $hit->setCode($code); if (!$hit->getReferer()) { $hit->setReferer($request->server->get('HTTP_REFERER')); } $hit->setUserAgent($request->server->get('HTTP_USER_AGENT')); $hit->setRemoteHost($request->server->get('REMOTE_HOST')); if ($isUnique) { // Add UTM tags entry if a UTM tag exist $queryHasUtmTags = false; if (!is_array($query)) { parse_str($query, $query); } foreach ($query as $key => $value) { if (strpos($key, 'utm_') !== false) { $queryHasUtmTags = true; break; } } if ($queryHasUtmTags) { $utmTags = new UtmTag(); $utmTags->setDateAdded($hit->getDateHit()); $utmTags->setUrl($hit->getUrl()); $utmTags->setReferer($hit->getReferer()); $utmTags->setQuery($hit->getQuery()); $utmTags->setUserAgent($hit->getUserAgent()); $utmTags->setRemoteHost($hit->getRemoteHost()); $utmTags->setLead($lead); if (key_exists('utm_campaign', $query)) { $utmTags->setUtmCampaign($query['utm_campaign']); } if (key_exists('utm_term', $query)) { $utmTags->setUtmTerm($query['utm_term']); } if (key_exists('utm_content', $query)) { $utmTags->setUtmConent($query['utm_content']); } if (key_exists('utm_medium', $query)) { $utmTags->setUtmMedium($query['utm_medium']); } if (key_exists('utm_source', $query)) { $utmTags->setUtmSource($query['utm_source']); } $repo = $this->em->getRepository('MauticLeadBundle:UtmTag'); $repo->saveEntity($utmTags); $this->leadModel->setUtmTags($lead, $utmTags); } } //get a list of the languages the user prefers $browserLanguages = $request->server->get('HTTP_ACCEPT_LANGUAGE'); if (!empty($browserLanguages)) { $languages = explode(',', $browserLanguages); foreach ($languages as $k => $l) { if ($pos = strpos(';q=', $l) !== false) { //remove weights $languages[$k] = substr($l, 0, $pos); } } $hit->setBrowserLanguages($languages); } //device granularity $dd = new DeviceDetector($request->server->get('HTTP_USER_AGENT')); $dd->parse(); $deviceRepo = $this->leadModel->getDeviceRepository(); $device = $deviceRepo->getDevice(null, $lead, $dd->getDeviceName(), $dd->getBrand(), $dd->getModel()); if (empty($device)) { $device = new LeadDevice(); $device->setClientInfo($dd->getClient()); $device->setDevice($dd->getDeviceName()); $device->setDeviceBrand($dd->getBrand()); $device->setDeviceModel($dd->getModel()); $device->setDeviceOs($dd->getOs()); $device->setDateOpen($hit->getDateHit()); $device->setLead($lead); $this->em->persist($device); } else { $device = $deviceRepo->getEntity($device['id']); } $hit->setDeviceStat($device); // Wrap in a try/catch to prevent deadlock errors on busy servers try { $this->em->persist($hit); $this->em->flush($hit); } catch (\Exception $exception) { if (MAUTIC_ENV === 'dev') { throw $exception; } else { $this->logger->addError($exception->getMessage(), ['exception' => $exception]); } } if ($this->dispatcher->hasListeners(PageEvents::PAGE_ON_HIT)) { $event = new PageHitEvent($hit, $request, $code, $clickthrough, $isUnique); $this->dispatcher->dispatch(PageEvents::PAGE_ON_HIT, $event); } //save hit to the cookie to use to update the exit time $this->cookieHelper->setCookie('mautic_referer_id', $hit->getId()); return $hit; }
public function getDeviceModel() { return $this->deviceDetector->getModel(); }
/** * Returns client device details from client browser * * @param class $deviceDetectorClass * @return array */ private function getClientBrowserDevice(\DeviceDetector\DeviceDetector $deviceDetectorClass) { $this->autoPopulateSuperGlobals(); $clientIp = $this->brServerGlobals->getClientIp(); return ['brand' => $deviceDetectorClass->getDeviceName(), 'ip' => $clientIp, 'ip direct' => $this->brServerGlobals->server->get('REMOTE_ADDR'), 'ip type' => $this->checkIpIsPrivate($clientIp), 'ip v4/v6' => $this->checkIpIsV4OrV6($clientIp), 'model' => $deviceDetectorClass->getModel(), 'name' => $deviceDetectorClass->getBrandName()]; }
public function registerDevice($userId = null) { $guid = $this->createTag(); $userAgent = Yii::$app->request->userAgent; $dd = new DeviceDetector($userAgent); $dd->parse(); $os = $dd->getOs(); $client = $dd->getClient(); $device = new DeviceModel(); $device->guid = $guid; $device->device = $dd->getDeviceName(); $device->model = $dd->getModel(); $device->brand = $dd->getBrandName(); $device->os_name = $os['name']; $device->os_version = $os['version']; $device->client_type = $client['type']; $device->client_name = $client['name']; $device->client_version = $client['version']; $device->user_id = $userId; Yii::$app->session->set('deviceId', $device->id); if (!$device->save()) { Yii::error(['info' => 'Проблема создания устройства в БД', 'message' => $device->getErrors()], __LINE__); return $device->getErrors(); } $this->setTag($guid); $this->id = $device->id; $this->tag = $guid; return $device; }
/** * Information about client requesting * cache base on user agent + client ip */ public function getClientInfo($userAgent = '') { if ($this->clientInfo) { return $this->clientInfo; } $userAgent = $userAgent ? $userAgent : @$_SERVER['HTTP_USER_AGENT']; $UAHash = $this->makeUserAgentHash($userAgent); $cacheKey = "ClientInfo:{$UAHash}"; $fromCache = RedisHelper::get($cacheKey); if (!$fromCache) { DeviceParserAbstract::setVersionTruncation(DeviceParserAbstract::VERSION_TRUNCATION_NONE); $dd = new DeviceDetector($userAgent); // OPTIONAL: If called, getBot() will only return true if a bot was detected (speeds up detection a bit) $dd->discardBotInformation(); $dd->parse(); if ($dd->isBot()) { // handle bots,spiders,crawlers,... // $clientInfo = $dd->getBot(); return false; } else { $clientInfo['client'] = $dd->getClient(); // holds information about browser, feed reader, media player, ... $clientInfo['os'] = $dd->getOs(); $clientInfo['device'] = $dd->getDevice(); $clientInfo['brand'] = $dd->getBrand(); $clientInfo['model'] = $dd->getModel(); $piwik = new Common(); $clientInfo['client']['browser_language'] = $piwik::getBrowserLanguage(); } RedisHelper::set($cacheKey, json_encode($clientInfo), Config::get('cache_time.defaultCacheTimeInSeconds')); } else { $clientInfo = json_decode($fromCache, 1); } $this->clientInfo = $clientInfo; return $clientInfo; }
<?php require_once 'vendor/autoload.php'; use DeviceDetector\DeviceDetector; $userAgent = $argv[1]; $dd = new DeviceDetector($userAgent); $dd->parse(); if ($dd->isBot()) { var_dump($botInfo = $dd->getBot()); } else { $clientInfo = $dd->getClient(); // holds information about browser, feed reader, media player, ... $osInfo = $dd->getOs(); $device = $dd->getDevice(); $brand = $dd->getBrand(); $model = $dd->getModel(); var_dump($clientInfo, $osInfo, $device, $brand, $model); }
/** * * @param Model\UserAgent $device * @param DeviceDetector $dd */ private function hydrateDevice(Model\Device $device, DeviceDetector $dd) { $device->setModel($this->getRealResult($dd->getModel())); $device->setBrand($this->getRealResult($dd->getBrandName())); $device->setType($this->getRealResult($dd->getDeviceName())); if ($dd->isMobile() === true) { $device->setIsMobile(true); } if ($dd->isTouchEnabled() === true) { $device->setIsTouch(true); } }