<?php
namespace Website\Widgets\GoogleSearch; use Moto; use Zend; class Service { protected static $_options = [ 'tokenLifeTime' => 600, ]; public static function generateToken($query, $params) { return Moto\System::encrypt([ 'created' => time(), 'query' => $query, 'params' => $params, ]); } public static function parseToken($token) { $payload = Moto\System::decrypt($token); if (!is_array($payload)) { return null; } $created = (int) Moto\Util::getValue($payload, 'created'); if ((time() - $created) > static::$_options['tokenLifeTime']) { return null; } if (!Moto\Util::arrayHas($payload, 'params.engine')) { return null; } return $payload; } public static function getSearchEngine($id) { $collection = Moto\Website\Integration::get('search_provider_google'); if ($collection->count() < 1) { return null; } $first = $collection->first(); $engines = Moto\Util::getValue($first, 'engines'); if (!is_array($engines)) { return null; } foreach ($engines as $engine) { if (Moto\Util::getValue($engine, 'id') === $id) { return $engine; } } return null; } public static function generateApiUrl(array $engine, $query, $params = null) { $url = 'https://www.googleapis.com/customsearch/v1'; if (Moto\Util::getValue($engine, 'apiType') === 'restricted') { $url = 'https://www.googleapis.com/customsearch/v1/siterestrict'; } $url .= '?q=' . urlencode($query); $url .= '&cx=' . $engine['engineId']; $url .= '&key=' . $engine['apiKey']; if (!is_array($params)) { return $url; } if (!empty($params['language'])) { $url .= '&lr=' . $params['language']; } if (!empty($params['perPage']) && $params['perPage'] < 10) { $url .= '&num=' . $params['perPage']; } if (!empty($params['start'])) { $url .= '&start=' . $params['start']; } return $url; } } 