[ 'endpoint' => Pipeline::getRestEndpoint(), 'minify' => false ] ]); $error = null; try { $cloud = new CloudRequestEngine(['resourceKey' => $resourceKey]); // Get engines available with the Resource Key $engines = array_keys($cloud->getEngineProperties()); } catch (\Throwable $e) { $error = $e->getMessage(); return [ 'pipeline' => null, 'available_engines' => null, 'error' => $error ]; } // Add CloudRequestEngine to the pipeline. $builder->add($cloud); // Add all the engines, accessible via provided resourceKey, to the // pipeline. 'robotstxt' is excluded — its content is fetched separately // via a direct HTTP call in FiftyOneDegreesRobotsTxt::fetch_from_cloud() // and the CloudEngine library accesses the response key without isset(), // causing a fatal warning when robotstxt data is absent from the response. $engines = array_values(array_filter($engines, fn($e) => $e !== 'robotstxt')); foreach ($engines as $engine) { $cloudEngine = new CloudEngine(); $cloudEngine->dataKey = $engine; $builder->add($cloudEngine); } // Build the pipeline $pipeline = $builder->build(); return [ 'pipeline' => $pipeline, 'available_engines' => $engines, 'error' => $error ]; } /** * Process function sets the evidence from web request in flowData and * runs the process function on each attached FlowElement. * * @return void */ public static function process() { // Only process if the data has not already been populated. if (Pipeline::$data === null) { // Fetch the data from the session if it's enabled and is already // there. if ( session_status() === PHP_SESSION_ACTIVE && isset($_SESSION['fiftyonedegrees_data']) && Pipeline::session_is_invalidated() === false ) { Pipeline::$data = $_SESSION['fiftyonedegrees_data']; return; } require_once dirname(__DIR__) . '/lib/vendor/autoload.php'; // Get the preconstructed pipeline from the cached option. $cachedPipeline = get_option(Options::PIPELINE); if (!$cachedPipeline) { // There is no pipeline, so return null. return; } if (isset($cachedPipeline['error'])) { error_log('Error occurred while initializing the 51Degrees ' . "plugin: '" . $cachedPipeline['error'] . "'"); return; } // Wrap the entire pipeline-processing block in a single // try/catch so any failure (createFlowData, evidence setup, // process(), setResponseHeader, getProperties) leaves // Pipeline::$data null without leaking exceptions to the // public traffic path. try { $pipeline = $cachedPipeline['pipeline']; $engines = $cachedPipeline['available_engines']; $flowData = $pipeline->createFlowData(); $flowData->evidence->setFromWebRequest(); $resolvedIp = ClientIpResolver::resolve(); if ($resolvedIp !== '') { $flowData->evidence->set('query.client-ip', $resolvedIp); } // Suspicious activity detection relies on IdProbLic/IdProbGlobal; // the cloud requires query.id.usage for those to be populated. if (get_option(Options::SUSPICIOUS_ENABLE, 'off') === 'on') { $flowData->evidence->set('query.id.usage', 'non-marketing'); } $flowData->process(); // https://51degrees.com/blog/user-agent-client-hints Utils::setResponseHeader($flowData); $properties = []; foreach ($engines as $engine) { $properties[$engine] = $pipeline->getElement($engine)->getProperties(); } Pipeline::$data = [ 'flowData' => $flowData, 'properties' => $properties, 'errors' => $flowData->errors, 'createdAt' => time() ]; } catch (\Throwable $e) { error_log( 'Error during 51Degrees pipeline initialization or processing: ' . $e->getMessage() ); return; } // If session cache is enabled then store the result in it. if (session_status() == PHP_SESSION_ACTIVE) { $_SESSION['fiftyonedegrees_data'] = Pipeline::$data; } } } /** * Retrieves property by engine and property key. If there is no flow data * available, or it contains errors, then null is returned. * * @param string $engine FlowElementDataKey e.g. device * @param string $key Property Key e.g. browsername * @return null|string Property Value */ public static function get($engine, $key) { $data = Pipeline::$data; if (!$data) { // There is no processed flow data. return null; } if (isset($data['errors']) && count($data['errors'])) { // There were errors from processing. error_log('Errors processing Flow Data' . $data['errors']); return null; } $flowData = $data['flowData']; if ($flowData->{$engine}->{$key}->hasValue ?? false) { return $flowData->{$engine}->{$key}->value; } if ($flowData->{$engine}->{$key}->noValueMessage ?? false) { error_log($flowData->{$engine}->{$key}->noValueMessage); } return null; } /** * Retrieves processed flow data as a JSON object. * * @return null|object flow data as a JSON Object */ public static function getJSON() { $data = Pipeline::$data; if (!$data) { return null; } if (isset($data['errors']) && count($data['errors'])) { error_log('Errors processing Flow Data' . $data['errors']); return null; } $flowData = $data['flowData']; try { return $flowData->jsonbundler->json; } catch (\Exception $e) { error_log($e->getMessage()); return null; } } /** * Retrieves a properties list for the specified category. * * @param string $category the category name to get properties for * @return null|array the list of properties */ public static function getCategory($category) { $data = Pipeline::$data; if (!$data) { return null; } if (isset($data['errors']) && count($data['errors'])) { error_log('Errors processing Flow Data' . $data['errors']); return null; } $flowData = $data['flowData']; $categoryResults = $flowData->getWhere('category', $category); $output = []; foreach ($categoryResults as $key => $property) { $value = null; if ($property->hasValue) { $value = $property->value; } $output[$key] = $value; } return $output; } /** * Gets client side javascript from FlowData. * * @return null|string the Javascript for the requesting device */ public static function getJavaScript() { $data = Pipeline::$data; if (!$data) { return null; } if (isset($data['errors']) && count($data['errors'])) { error_log('Errors processing Flow Data' . $data['errors']); return null; } $flowData = $data['flowData']; try { return $flowData->javascriptbuilder->javascript; } catch (\Exception $e) { error_log($e->getMessage()); return ''; } } /** * Gets AppContext from the URL. * * @param string $url * @return string the app context */ public static function getAppContext($url) { $urlParts = explode( '/', str_replace('https://', '', str_replace('http://', '', $url)) ); if (count($urlParts) > 1) { return '/' . end($urlParts); } return ''; } /** * Gets the REST API endpoint path for the 51Degrees JSON callback. * Uses WordPress rest_url() to support all permalink structures * (pretty permalinks, plain permalinks, subdirectory installs). * * @return string the endpoint path (e.g. "/wp-json/fiftyonedegrees/v4/json" * or "/?rest_route=/fiftyonedegrees/v4/json") */ public static function getRestEndpoint() { $restUrl = rest_url('fiftyonedegrees/v4/json'); $parsed = parse_url($restUrl); $endpoint = $parsed['path'] ?? '/'; if (isset($parsed['query'])) { $endpoint .= '?' . $parsed['query']; } return $endpoint; } /** * Returns true if the data in the session has been invalidated by * another process updating the pipeline. * * @return bool */ public static function session_is_invalidated() { $createdAt = $_SESSION['fiftyonedegrees_data']['createdAt']; $invalidatedAt = get_option(Options::SESSION_INVALIDATED); return $createdAt < $invalidatedAt; } }