PageRenderTime 25ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/googleads-php-lib/src/Google/Api/Ads/AdWords/Lib/AdWordsUser.php

https://github.com/markvince/CakePHP-GAStats-Plugin
PHP | 410 lines | 184 code | 43 blank | 183 comment | 16 complexity | 37b08ca6988a8229ac8e7269495e1a3f MD5 | raw file
  1. <?php
  2. /**
  3. * User class for the AdWords API to create SOAP clients to the available API
  4. * services.
  5. *
  6. * PHP version 5
  7. *
  8. * Copyright 2011, Google Inc. All Rights Reserved.
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. *
  22. * @package GoogleApiAdsAdWords
  23. * @subpackage Lib
  24. * @category WebServices
  25. * @copyright 2011, Google Inc. All Rights Reserved.
  26. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License,
  27. * Version 2.0
  28. * @see AdsUser
  29. */
  30. require_once dirname(__FILE__) . '/../../Common/Lib/AdsUser.php';
  31. require_once dirname(__FILE__) . '/../../Common/Util/ApiPropertiesUtils.php';
  32. require_once 'AdWordsSoapClientFactory.php';
  33. require_once 'AdWordsConstants.php';
  34. /**
  35. * User class for the AdWords API to create SOAP clients to the available API
  36. * services.
  37. * @package GoogleApiAdsAdWords
  38. * @subpackage Lib
  39. */
  40. class AdWordsUser extends AdsUser {
  41. const OAUTH2_SCOPE = 'https://www.googleapis.com/auth/adwords';
  42. const OAUTH2_HANDLER_CLASS = 'SimpleOAuth2Handler';
  43. const REPORT_LOG_CHANNEL_NAME = 'report';
  44. const REPORT_LOG_FILE_NAME = 'report_download.log';
  45. /**
  46. * The name of the SOAP header that represents the user agent making API
  47. * calls.
  48. * @var string
  49. */
  50. const USER_AGENT_HEADER_NAME = 'userAgent';
  51. const DEFAULT_USER_AGENT = 'unknown';
  52. private $libVersion;
  53. private $libName;
  54. private $userAgent;
  55. private $scopes;
  56. /**
  57. * The AdWordsUser constructor.
  58. * <p>The AdWordsUser class can be configured in one of two ways:
  59. * <ol><li>Using an authenitcation INI file</li>
  60. * <li>Using supplied credentials</li></ol></p>
  61. * <p>If an authentication INI file is provided and successfully loaded, those
  62. * values will be used unless a corresponding parameter overwrites it.
  63. * If the authentication INI file is not provided (e.g. it is <var>null</var>)
  64. * the class will attempt to load the default authentication file at the path
  65. * of "../auth.ini" relative to this file's directory. Any corresponding
  66. * parameter, which is not <var>null</var>, will, however, overwrite any
  67. * parameter loaded from the default INI.</p>
  68. * <p>Likewise, if a custom settings INI file is not provided, the default
  69. * settings INI file will be loaded from the path of "../settings.ini"
  70. * relative to this file's directory.</p>
  71. * @param string|null $authenticationIniPath the absolute path to the
  72. * authentication INI or relative to the current directory (cwd). If
  73. * <var>null</var>, the default authentication INI file will attempt to be
  74. * loaded
  75. * @param string|null $developerToken the developer token (required header).
  76. * Will overwrite the developer token entry loaded from any INI file
  77. * @param string|null $userAgent the user agent name (required header). Will
  78. * be prepended with the library name and version. Will overwrite the
  79. * userAgent entry loaded from any INI file
  80. * @param string|null $clientCustomerId the client customer ID to make the
  81. * request against (optional header). Will overwrite the clientCustomerId
  82. * entry loaded from any INI file
  83. * @param string|null $settingsIniPath the path to the settings INI file. If
  84. * <var>null</var>, the default settings INI file will be loaded
  85. * @param array|null $oauth2Info the OAuth 2.0 information to use for requests
  86. */
  87. public function __construct($authenticationIniPath = null,
  88. $developerToken = null, $userAgent = null, $clientCustomerId = null,
  89. $settingsIniPath = null, $oauth2Info = null) {
  90. parent::__construct();
  91. $buildIniAw = parse_ini_file(dirname(__FILE__) . '/build.ini', false);
  92. $buildIniCommon = parse_ini_file(dirname(__FILE__) .
  93. '/../../Common/Lib/build.ini', false);
  94. $this->libName = $buildIniAw['LIB_NAME'];
  95. $this->libVersion = $buildIniCommon['LIB_VERSION'];
  96. $apiProps = ApiPropertiesUtils::ParseApiPropertiesFile(dirname(__FILE__) .
  97. '/api.properties');
  98. $versions = explode(',', $apiProps['api.versions']);
  99. $defaultVersion = $versions[count($versions) - 1];
  100. $defaultServer = $apiProps['api.server'];
  101. if ($authenticationIniPath === null) {
  102. $authenticationIniPath = dirname(__FILE__) . '/../auth.ini';
  103. }
  104. $authenticationIni =
  105. parse_ini_file(realpath($authenticationIniPath), true);
  106. $developerToken = $this->GetAuthVarValue($developerToken, 'developerToken',
  107. $authenticationIni);
  108. $userAgent = $this->GetAuthVarValue($userAgent,
  109. self::USER_AGENT_HEADER_NAME, $authenticationIni);
  110. $clientCustomerId = $this->GetAuthVarValue($clientCustomerId,
  111. 'clientCustomerId', $authenticationIni);
  112. $oauth2Info = $this->GetAuthVarValue($oauth2Info, 'OAUTH2',
  113. $authenticationIni);
  114. if (isset($oauth2Info['oAuth2AdditionalScopes'])) {
  115. $scopes = explode(',', $oauth2Info['oAuth2AdditionalScopes']);
  116. } else {
  117. $scopes = array();
  118. }
  119. $scopes[] = self::OAUTH2_SCOPE;
  120. $clientId = $this->GetAuthVarValue(null, 'clientId', $authenticationIni);
  121. if ($clientId !== null) {
  122. throw new ValidationException('clientId', $clientId,
  123. 'The authentication key "clientId" has been changed to'
  124. . ' "clientCustomerId", please use that instead.');
  125. }
  126. $this->SetOAuth2Info($oauth2Info);
  127. $this->SetUserAgent($userAgent);
  128. $this->updateClientLibraryUserAgent($userAgent);
  129. $this->SetClientCustomerId($clientCustomerId);
  130. $this->SetDeveloperToken($developerToken);
  131. $this->SetScopes($scopes);
  132. if ($settingsIniPath === null) {
  133. $settingsIniPath = dirname(__FILE__) . '/../settings.ini';
  134. }
  135. $this->LoadSettings($settingsIniPath,
  136. $defaultVersion,
  137. $defaultServer,
  138. getcwd(), dirname(__FILE__));
  139. }
  140. /**
  141. * Overrides AdsUser::InitLogs(), adding an additional log for report
  142. * download requests.
  143. */
  144. protected function InitLogs() {
  145. parent::InitLogs();
  146. Logger::LogToFile(self::REPORT_LOG_CHANNEL_NAME,
  147. $this->GetLogsDirectory() . DIRECTORY_SEPARATOR
  148. . self::REPORT_LOG_FILE_NAME);
  149. Logger::SetLogLevel(self::REPORT_LOG_CHANNEL_NAME, Logger::$FATAL);
  150. }
  151. /**
  152. * Overrides AdsUser::LogDefaults(), setting an additional log level for
  153. * report download requests.
  154. */
  155. public function LogDefaults() {
  156. parent::LogDefaults();
  157. Logger::SetLogLevel(self::REPORT_LOG_CHANNEL_NAME, Logger::$ERROR);
  158. }
  159. /**
  160. * Overrides AdsUser::LogErrors(), setting an additional log level for report
  161. * download requests.
  162. */
  163. public function LogErrors() {
  164. parent::LogErrors();
  165. Logger::SetLogLevel(self::REPORT_LOG_CHANNEL_NAME, Logger::$ERROR);
  166. }
  167. /**
  168. * Overrides AdsUser::LogAll(), setting an additional log level for report
  169. * download requests.
  170. */
  171. public function LogAll() {
  172. parent::LogAll();
  173. Logger::SetLogLevel(self::REPORT_LOG_CHANNEL_NAME, Logger::$INFO);
  174. }
  175. /**
  176. * Gets the service by its service name and group.
  177. * @param string $serviceName the service name
  178. * @param string|null $version the version of the service to get. If
  179. * <var>null</var>, then the default version will be used
  180. * @param string|null $server the server to make the request to. If
  181. * <var>null</var>, then the default server will be used
  182. * @param SoapClientFactory|null $serviceFactory the factory to create the
  183. * client. If <var>null</var>, then the built-in SOAP client factory will
  184. * be used
  185. * @param bool|null $validateOnly if the service should be created in
  186. * validateOnly mode
  187. * @param bool|null $partialFailure if the service should be created in
  188. * partialFailure mode
  189. * @return SoapClient the instantiated service
  190. * @throws ServiceException if an error occurred when getting the service
  191. */
  192. public function GetService($serviceName, $version = null, $server = null,
  193. SoapClientFactory $serviceFactory = null, $validateOnly = null,
  194. $partialFailure = null) {
  195. $this->ValidateUser();
  196. if ($serviceFactory === null) {
  197. if ($version === null) {
  198. $version = $this->GetDefaultVersion();
  199. }
  200. if ($server === null) {
  201. $server = $this->GetDefaultServer();
  202. }
  203. $serviceFactory = new AdWordsSoapClientFactory($this, $version, $server,
  204. $validateOnly, $partialFailure);
  205. }
  206. return parent::GetServiceSoapClient($serviceName, $serviceFactory);
  207. }
  208. /**
  209. * Loads the classes within a service, so they can be used before the service
  210. * is constructed.
  211. * @param string $serviceName the service name
  212. * @param string|null $version the version of the service to get. If
  213. * <var>null</var>, then the default version will be used
  214. */
  215. public function LoadService($serviceName, $version = null) {
  216. if ($version === null) {
  217. $version = $this->GetDefaultVersion();
  218. }
  219. $serviceFactory = new AdWordsSoapClientFactory($this, $version, null, null,
  220. null);
  221. $serviceFactory->DoRequireOnce($serviceName);
  222. }
  223. /**
  224. * Gets the developer token for this user.
  225. * @return string the developer token
  226. */
  227. public function GetDeveloperToken() {
  228. return $this->GetHeaderValue('developerToken');
  229. }
  230. /**
  231. * Sets the developer token for this user.
  232. * @param string $developerToken the developer token
  233. */
  234. public function SetDeveloperToken($developerToken) {
  235. $this->SetHeaderValue('developerToken', $developerToken);
  236. }
  237. /**
  238. * Gets the client customer ID for this user.
  239. * @return string the client customer ID for this user
  240. */
  241. public function GetClientCustomerId() {
  242. return $this->GetHeaderValue('clientCustomerId');
  243. }
  244. /**
  245. * Sets the client customer ID for this user.
  246. * @param string $clientCustomerId the client customer ID for this user
  247. */
  248. public function SetClientCustomerId($clientCustomerId) {
  249. $this->SetHeaderValue('clientCustomerId', $clientCustomerId);
  250. }
  251. /**
  252. * Gets the AdWords Express business ID required for AdWords Express
  253. * PromotionService
  254. */
  255. public function GetExpressBusinessId() {
  256. return $this->GetHeaderValue('expressBusinessId');
  257. }
  258. /**
  259. * Sets the AdWords Express business ID required for AdWords Express
  260. * PromotionService
  261. * @param string AdWords Express business ID
  262. */
  263. public function SetExpressBusinessId($businessId) {
  264. $this->SetHeaderValue('expressBusinessId', $businessId);
  265. }
  266. /**
  267. * Gets the Google My Business page ID used by AdWords Express
  268. * PromotionService
  269. */
  270. public function GetExpressPlusPageId() {
  271. return $this->GetHeaderValue('pageId');
  272. }
  273. /**
  274. * Sets the Google My Business page ID used by AdWords Express
  275. * PromotionService
  276. * @param string Google My Business page ID
  277. */
  278. public function SetExpressPlusPageId($pageId) {
  279. $this->SetHeaderValue('pageId', $pageId);
  280. }
  281. /**
  282. * Gets the raw user agent for this user.
  283. * @return string The raw user agent.
  284. */
  285. public function GetUserAgent() {
  286. return $this->userAgent;
  287. }
  288. /**
  289. * Sets the raw user agent for this user.
  290. * @param string $userAgent The raw user agent.
  291. */
  292. public function SetUserAgent($userAgent) {
  293. $this->userAgent = $userAgent;
  294. }
  295. /**
  296. * @see AdsUser::GetUserAgentHeaderName()
  297. */
  298. public function GetUserAgentHeaderName() {
  299. return self::USER_AGENT_HEADER_NAME;
  300. }
  301. /**
  302. * @see AdsUser::GetClientLibraryNameAndVersion()
  303. */
  304. public function GetClientLibraryNameAndVersion() {
  305. return array($this->libName, $this->libVersion);
  306. }
  307. /**
  308. * Gets OAuth2 scopes.
  309. * @return array the list of OAuth2 scopes
  310. */
  311. public function GetScopes() {
  312. return $this->scopes;
  313. }
  314. /**
  315. * Sets OAuth2 scopes.
  316. * @param array the list of OAuth2 scopes
  317. */
  318. public function SetScopes($scopes) {
  319. $this->scopes = $scopes;
  320. }
  321. /**
  322. * Validates the user and throws a validation error if there are any errors.
  323. * @throws ValidationException if there are any validation errors
  324. */
  325. public function ValidateUser() {
  326. if ($this->GetOAuth2Info() === null) {
  327. throw new ValidationException('OAuth2Info', null,
  328. 'OAuth 2.0 configuration is required.');
  329. }
  330. parent::ValidateOAuth2Info();
  331. if ($this->GetUserAgent() === null || trim($this->GetUserAgent()) === '') {
  332. $this->SetUserAgent(self::DEFAULT_USER_AGENT);
  333. } else if (mb_check_encoding($this->GetUserAgent(), 'ASCII') === false) {
  334. throw new ValidationException('userAgent', $this->GetUserAgent(),
  335. 'The property userAgent must contain only ASCII characters');
  336. }
  337. if ($this->GetDeveloperToken() === null) {
  338. throw new ValidationException('developerToken', null,
  339. 'developerToken is required and cannot be null.');
  340. }
  341. }
  342. /**
  343. * Get the default OAuth2 Handler for this user.
  344. * @param null|string $className the name of the oauth2Handler class or null
  345. * @return mixed the configured OAuth2Handler class
  346. */
  347. public function GetDefaultOAuth2Handler($className = null) {
  348. $className = !empty($className) ? $className : self::OAUTH2_HANDLER_CLASS;
  349. $oauth2Handler = new $className($this->GetScopes());
  350. return $oauth2Handler;
  351. }
  352. /**
  353. * Handles calls to undefined methods.
  354. * @param string $name the name of the method being called
  355. * @param array $arguments the arguments passed to the method
  356. * @return mixed the result of the correct method call, or nothing if there
  357. * is no correct method
  358. */
  359. public function __call($name, $arguments) {
  360. // Handle calls to legacy Get*Service() methods.
  361. if (preg_match('/^Get(\w+Service)$/i', $name, $matches)) {
  362. $serviceName = $matches[1];
  363. array_unshift($arguments, $serviceName);
  364. return call_user_func_array(array($this, 'GetService'), $arguments);
  365. }
  366. }
  367. }