+// Generator (somewhat getter) for network type options
+function generateNetworkMediaOutputOptions ($mediaOutput) {
+ // Is this an array, then we just came back from edit/delete actions
+ if (is_array($mediaOutput)) {
+ // Set it as empty string
+ $mediaOutput = '';
+ } // END - if
+
+ // Is this cached?
+ if (!isset($GLOBALS[__FUNCTION__][$mediaOutput])) {
+ // Generate output and cache it
+ $GLOBALS[__FUNCTION__][$mediaOutput] = generateOptions(
+ '/ARRAY/',
+ array(
+ '',
+ 'banner',
+ 'html_email',
+ 'layer',
+ 'pagepeel',
+ 'popup',
+ 'popdown',
+ 'text_email',
+ 'textlink'
+ ),
+ array(
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_NONE--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_BANNER--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_HTML_EMAIL--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_LAYER--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_PAGEPEEL--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_POPUP--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_POPDOWN--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_TEXT_EMAIL--}',
+ '{--ADMIN_NETWORK_MEDIA_OUTPUT_TEXTLINK--}'
+ ),
+ $mediaOutput,
+ 'translateNetworkMediaOutputType'
+ );
+ } // END - if
+
+ // Return content
+ return $GLOBALS[__FUNCTION__][$mediaOutput];
+}
+
+// Checks if the given network is configured by looking its API configuration entry up
+function isNetworkApiConfigured ($networkId, $addSql = '') {
+ // Is there cache?
+ if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
+ // Check for an entry in network_api_config
+ $GLOBALS[__FUNCTION__][$networkId] = (countSumTotalData(
+ bigintval($networkId),
+ 'network_api_config',
+ 'network_id',
+ 'network_id',
+ true
+ ) == 1);
+ } // END - if
+
+ // Return cache
+ return $GLOBALS[__FUNCTION__][$networkId];
+}
+
+// Checks whether the given network type handler is configured
+function isNetworkTypeHandlerConfigured ($networkId, $networkTypeId) {
+ // Is there cache?
+ if (!isset($GLOBALS[__FUNCTION__][$networkId][$networkTypeId])) {
+ // Determine it
+ $GLOBALS[__FUNCTION__][$networkId][$networkTypeId] = (countSumTotalData(
+ bigintval($networkTypeId),
+ 'network_handler_config',
+ 'network_data_id',
+ 'network_type_id',
+ true,
+ sprintf(' AND `network_id`=%s', bigintval($networkId))
+ ) == 1);
+ } // END - if
+
+ // Return cache
+ return $GLOBALS[__FUNCTION__][$networkId][$networkTypeId];
+}
+
+// Handles the network-payment-check request
+function handleNetworkPaymentCheckRequest () {
+ // @TODO Implement this function, don't forget to set HTTP status back to '200 OK' if everything went fine
+ reportBug(__FUNCTION__, __LINE__, 'Not yet implemented.');
+}
+
+// Handles the network-delete-url request
+function handleNetworkDeleteUrlRequest () {
+ // @TODO Implement this function, don't forget to set HTTP status back to '200 OK' if everything went fine
+ reportBug(__FUNCTION__, __LINE__, 'Not yet implemented.');
+}
+
+// Handle a single request parameter key by given network type handler id and "internal" key
+function handleRequestParameterKey ($networkTypeId, $networkRequestKey) {
+ // Construct call-back function name
+ $callbackName = 'doHandleNetworkRequest' . capitalizeUnderscoreString($networkRequestKey) . 'Key';
+
+ // Is the function there?
+ if (!function_exists($callbackName)) {
+ // Call-back function does not exist
+ reportBug(__FUNCTION__, __LINE__, 'Call-back function ' . $callbackName . ' does not exist. networkTypeId=' . $networkTypeId . ',networkRequestKey=' . $networkRequestKey);
+ } // END - if
+
+ // Call it with network type id
+ return call_user_func_array($callbackName, array($networkTypeId));
+}
+
+// Handle all keys given request parameter array loaded by getNetworkRequestParametersByTypeId()
+function handleNetworkRequestParameterKeys (&$requestParams) {
+ // Simple check for validity
+ assert(isset($requestParams[0]['network_request_param_key']));
+
+ // "Walk" through all
+ foreach ($requestParams as $key => $params) {
+ // Is the default value not set?
+ if (empty($params['network_request_param_default'])) {
+ // This key needs to be handled, so call it
+ $requestParams[$key]['network_request_param_default'] = handleRequestParameterKey($params['network_type_id'], $params['network_request_param_key']);
+ } // END - if
+ } // END - foreach
+}
+
+/**
+ * Logs given HTTP headers to database for debugging purposes.
+ *
+ * @param $networkId Network's id number
+ * @param $networkTypeId Network type handler's id number
+ * @param $headers All HTTP headers
+ * @param $type Can be only one of 'MANUAL' or 'CRON'
+ * @return void
+ */
+function logNetworkResponseHeaders ($networkId, $networkTypeId, $headers, $type) {
+ // Make sure type is valid
+ assert(in_array($type, array('MANUAL', 'CRON')));
+
+ // Is debug logging enabled or status code not 200 OK?
+ if ((getConfig('network_logging_debug') == 'Y') || (!isHttpStatusOkay($headers[0]))) {
+ // Add entry
+ SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_network_header_logging` (`network_id`, `network_type_id`, `network_http_status_code`, `network_http_headers`, `network_logging_type`) VALUES(%s, %s, '%s', '%s', '%s')",
+ array(
+ bigintval($networkId),
+ bigintval($networkTypeId),
+ trim($headers[0]),
+ serialize($headers),
+ $type
+ ), __FUNCTION__, __LINE__);
+ } // END - if
+}
+
+/**
+ * Caches given reponse body from API into cache, updates existing cache if
+ * found. This function does the charset-convertion, so you don't have to do it
+ * again if you use this cached data.
+ *
+ * @param $networkId Network's id number
+ * @param $networkTypeId Network type handler's id number
+ * @param $responseBody Response body (string)
+ * @param $networkData Network + type handler data as array
+ * @param $type Can be only one of 'MANUAL' or 'CRON'
+ * @return void
+ */
+function saveNetworkResponseBodyInCache ($networkId, $networkTypeId, $responseBody, $networkData, $type) {
+ // Make sure the body is not larger than this value
+ assert(strlen($responseBody) <= 16777215);
+ assert(in_array($type, array('MANUAL', 'CRON')));
+
+ // So is there cache?
+ if (countSumTotalData($networkId, 'network_cache', 'network_cache_id', 'network_id', TRUE, ' AND `network_type_id`=' . bigintval($networkTypeId)) == 1) {
+ // Entry found, so update it
+ SQL_QUERY_ESC("UPDATE
+ `{?_MYSQL_PREFIX?}_network_cache`
+SET
+ `network_cache_data`='%s',
+ `network_cache_body`='%s',
+ `network_cache_type`='%s',
+ `network_cache_admin_id`=%s,
+ `network_cache_updated`=NOW()
+WHERE
+ `network_id`=%s AND
+ `network_type_id`=%s
+LIMIT 1",
+ array(
+ serialize($networkData),
+ compress(convertCharsetToUtf8($responseBody, $networkData['network_charset'])),
+ $type,
+ convertZeroToNull(getCurrentAdminId()),
+ bigintval($networkId),
+ bigintval($networkTypeId)
+ ), __FUNCTION__, __LINE__);
+ } else {
+ // Add entry
+ SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_network_cache` (`network_id`, `network_type_id`, `network_cache_data`, `network_cache_body`, `network_cache_type`, `network_cache_admin_id`) VALUES(%s, %s, '%s', '%s', '%s', %s)",
+ array(
+ bigintval($networkId),
+ bigintval($networkTypeId),
+ serialize($networkData),
+ compress(convertCharsetToUtf8($responseBody, $networkData['network_charset'])),
+ $type,
+ convertZeroToNull(getCurrentAdminId())
+ ), __FUNCTION__, __LINE__);
+ }
+}
+
+// Queries network API with given network data and request data
+function queryNetworkApi ($networkData, $requestData) {
+ // Query it
+ $response = sendHttpRequest($networkData['network_request_type'], $networkData['network_type_api_url'], $requestData, FALSE, FALSE);
+
+ // Did all went fine? (also a 403 is considered as "okay" here)
+ if (count($response) > 3) {
+ // Save response body, remove last empty line if really empty
+ $responseBody = (string) trim($response[count($response) - 1]);
+ unset($response[count($response) - 1]);
+ assert(empty($response[count($response)]));
+ unset($response[count($response) - 1]);
+
+ // Register all HTTP headers for debugging purposes
+ logNetworkResponseHeaders($networkData['network_id'], postRequestElement('network_type_id'), $response, 'MANUAL');
+
+ // Is all fine?
+ if (isHttpStatusOkay($response[0])) {
+ // Count API request
+ countNetworkApiRequest($networkData);
+
+ // Save response in cache
+ saveNetworkResponseBodyInCache($networkData['network_id'], postRequestElement('network_type_id'), $responseBody, $networkData, 'MANUAL');
+ } // END - if
+ } // END - if
+
+ // Return the response
+ return $response;
+}
+
+/**
+ * Counts API request from given network data generated by getNetworkDataByTypeId()
+ *
+ * @param $networkData Array with network data
+ * @return $affectedRows Affected rows (always one or FALSE if unlimited/depleted)
+ */
+function countNetworkApiRequest ($networkData) {
+ // Get API config
+ $apiConfig = getFullNetworkConfigurationByTypeId($networkData['network_type_id']);
+
+ // Is the daily or remaining free amount zero?
+ if (($networkData['network_query_amount'] == 0) || ($apiConfig['network_api_remaining_requests'] == 0)) {
+ // Then abort here
+ return FALSE;
+ } // END - if
+
+ // Okay, so update database
+ $result = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_network_api_config` SET `network_api_remaining_requests`=`network_api_remaining_requests`-1 WHERE `network_id`=%s LIMIT 1",
+ array(
+ bigintval($networkData['network_id'])
+ ), __FUNCTION__, __LINE__);
+
+ // Return affected rows
+ return SQL_AFFECTEDROWS();
+}
+
+/**
+ * Generates a referral link for given network id (including HTML)
+ *
+ * @param $networkId Network id to generate link for
+ * @return $output "Rendered" output
+ */
+function generateMetworkReferralLinkById ($networkId) {
+ // Simple output (no need for template!)
+ $output = '<a href="{%network,getNetworkDataFromId,network_reflink=' . $networkId . '%}" target="_blank" title="{%network,getNetworkDataFromId,network_title=' . $networkId . '%}">{%network,getNetworkDataFromId,network_title=' . $networkId . '%}</a>';
+
+ // Return it
+ return $output;
+}
+
+//------------------------------------------------------------------------------
+// "Translation" functions (can be used in EL code)
+//------------------------------------------------------------------------------
+