/** * {@inheritdoc} */ public function generateIdentifier($account = NULL) { $identifier = ''; $identifier .= $this->getPluginId() . PluginBase::DERIVATIVE_SEPARATOR; $identifier .= empty($account->uid) ? ip_address() : $account->uid; return $identifier; }
protected function updateCreditCardCustomer($params) { require_once "CRM/iATS/iATSService.php"; $credentials = iATS_Service_Request::credentials($params['paymentProcessorId'], $params['is_test']); unset($params['paymentProcessorId']); unset($params['is_test']); unset($params['domain']); $iats_service_params = array('type' => 'customer', 'iats_domain' => $credentials['domain'], 'method' => 'update_credit_card_customer'); $iats = new iATS_Service_Request($iats_service_params); // print_r($iats); die(); $params['updateCreditCardNum'] = 0 < strlen($params['creditCardNum']) && FALSE === strpos($params['creditCardNum'], '*') ? 1 : 0; if (empty($params['updateCreditCardNum'])) { unset($params['creditCardNum']); unset($params['updateCreditCardNum']); } $params['customerIPAddress'] = function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']; foreach (array('qfKey', 'entryURL', 'firstName', 'lastName', '_qf_default', '_qf_IATSCustomerLink_submit') as $key) { if (isset($params[$key])) { unset($params[$key]); } } // make the soap request $response = $iats->request($credentials, $params); $result = $iats->result($response, TRUE); // note: don't log this to the iats_response table return $result; }
function sess_write($key, $value) { global $perfil, $cfg; $mysql = new MYSQL($cfg); // If saving of session data is disabled or if the client doesn't have a session, // and one isn't being created ($value), do nothing. This keeps crawlers out of // the session table. This reduces memory and server load, and gives more useful // statistics. We can't eliminate anonymous session table rows without breaking // the throttle module and the "Who's Online" block. if (!session_save_session() || $perfil->ID_USER == 0 && empty($_COOKIE[session_name()]) && empty($value)) { return TRUE; } $mysql->SqlSelect("UPDATE {sessions} SET ID_USER = %d, cache = %d, hostname = '%s', session = '%s', timestamp = %d WHERE ID_SESSION = '%s'", $perfil->ID_USER, isset($perfil->cache) ? $perfil->cache : '', ip_address(), $value, time(), $key); if (mysql_affected_rows()) { // Last access time is updated no more frequently than once every 180 seconds. // This reduces contention in the users table. if ($perfil->ID_USER && time() - $perfil->access > variable_get('session_write_interval', 180)) { $mysql->SqlSelect("UPDATE {users} SET access = %d WHERE ID_USER = %d", time(), $perfil->ID_USER); } } else { // If this query fails, another parallel request probably got here first. // In that case, any session data generated in this request is discarded. @$mysql->SqlSelect("INSERT INTO {sessions} (ID_SESSION, ID_USER, cache, hostname, session, timestamp) VALUES ('%s', %d, %d, '%s', '%s', %d)", $key, $perfil->ID_USER, isset($perfil->cache) ? $perfil->cache : '', ip_address(), $value, time()); } return TRUE; }
public function write($sessionId, $serializedData) { try { // For performance reasons, do not update the sessions table, unless // $_SESSION has changed or more than 180 has passed since the last update. if ($this->sessionDataHasChanged($sessionId, $serializedData)) { // Either ssid or sid or both will be added from $key below. $fields = array('uid' => $this->uid, 'cache' => 0, 'hostname' => ip_address(), 'session' => $serializedData, 'timestamp' => REQUEST_TIME); $key = array('sid' => $sessionId, 'ssid' => ''); db_merge('sessions')->key($key)->fields($fields)->execute(); } return TRUE; } catch (Exception $exception) { // FIXME: This should never be here, a global try/catch should definitely // be done upper in the code. require_once DRUPAL_ROOT . '/includes/errors.inc'; // If we are displaying errors, then do so with no possibility of a further // uncaught exception being thrown. if (error_displayable()) { print '<h1>Uncaught exception thrown in session handler.</h1>'; print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />'; } return FALSE; } }
public function __construct() { $this->UserIPAdd = ip_address(); $this->UserBrowser = user_agent(); $this->DB =& load_class('Database'); $this->ENC =& load_class('Encryption'); $this->SESS =& load_class('Session'); }
function doDirectPayment(&$params) { if (!$this->_profile) { return self::error('Unexpected error, missing profile'); } // use the iATSService object for interacting with iATS, mostly the same for recurring contributions require_once "CRM/iATS/iATSService.php"; // TODO: force bail if it's not recurring? $isRecur = CRM_Utils_Array::value('is_recur', $params) && $params['contributionRecurID']; $method = $isRecur ? 'acheft_create_customer_code' : 'acheft'; // to add debugging info in the drupal log, assign 1 to log['all'] below $iats = new iATS_Service_Request(array('type' => 'process', 'method' => $method, 'iats_domain' => $this->_profile['iats_domain'], 'currencyID' => $params['currencyID'])); $request = $this->convertParams($params, $method); $request['customerIPAddress'] = function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']; $credentials = array('agentCode' => $this->_paymentProcessor['user_name'], 'password' => $this->_paymentProcessor['password']); // Get the API endpoint URL for the method's transaction mode. // TODO: enable override of the default url in the request object // $url = $this->_paymentProcessor['url_site']; // make the soap request $response = $iats->request($credentials, $request); // process the soap response into a readable result $result = $iats->result($response); if ($result['status']) { $params['contribution_status_id'] = 2; // always pending status $params['payment_status_id'] = 2; // for future versions, the proper key $params['trxn_id'] = trim($result['remote_id']) . ':' . time(); $params['gross_amount'] = $params['amount']; if ($isRecur) { // save the client info in my custom table // Allow further manipulation of the arguments via custom hooks, // before initiating processCreditCard() // CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $iatslink1); $processresult = $response->PROCESSRESULT; $customer_code = (string) $processresult->CUSTOMERCODE; // $exp = sprintf('%02d%02d', ($params['year'] % 100), $params['month']); $exp = '0000'; $email = ''; if (isset($params['email'])) { $email = $params['email']; } elseif (isset($params['email-5'])) { $email = $params['email-5']; } elseif (isset($params['email-Primary'])) { $email = $params['email-Primary']; } $query_params = array(1 => array($customer_code, 'String'), 2 => array($request['customerIPAddress'], 'String'), 3 => array($exp, 'String'), 4 => array($params['contactID'], 'Integer'), 5 => array($email, 'String'), 6 => array($params['contributionRecurID'], 'Integer')); CRM_Core_DAO::executeQuery("INSERT INTO civicrm_iats_customer_codes\n (customer_code, ip, expiry, cid, email, recur_id) VALUES (%1, %2, %3, %4, %5, %6)", $query_params); // also set next_sched_contribution, the field name is civicrm version dependent $field_name = _iats_civicrm_nscd_fid(); $params[$field_name] = strtotime('+' . $params['frequency_interval'] . ' ' . $params['frequency_unit']); } return $params; } else { return self::error($result['reasonMessage']); } }
/** * {@inheritdoc} * * @see user_login_authenticate_validate(). */ public function authenticate(RequestInterface $request) { $username = $request->getUser(); $password = $request->getPassword(); // Do not allow any login from the current user's IP if the limit has been // reached. Default is 50 failed attempts allowed in one hour. This is // independent of the per-user limit to catch attempts from one IP to log // in to many different user accounts. We have a reasonably high limit // since there may be only one apparent IP for all users at an institution. if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) { throw new FloodException(format_string('Rejected by ip flood control.')); } if (filter_var($username, FILTER_VALIDATE_EMAIL)) { if (!($uid = db_query_range("SELECT uid FROM {users} WHERE LOWER(mail) = LOWER(:mail) AND status = 1", 0, 1, array(':mail' => $username))->fetchField())) { // Always register an IP-based failed login event. flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600), ip_address()); return null; } else { $username = db_query_range("SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:mail) AND status = 1", 0, 1, array(':mail' => $username))->fetchField(); } } else { if (!($uid = db_query_range("SELECT uid FROM {users} WHERE name = :name AND status = 1", 0, 1, array(':name' => $username))->fetchField())) { // Always register an IP-based failed login event. flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600), ip_address()); return null; } } if (variable_get('user_failed_login_identifier_uid_only', false)) { // Register flood events based on the uid only, so they apply for any // IP address. This is the most secure option. $identifier = $uid; } else { // The default identifier is a combination of uid and IP address. This // is less secure but more resistant to denial-of-service attacks that // could lock out all users with public user names. $identifier = $uid; // . '-' . ip_address(); } // Don't allow login if the limit for this user has been reached. // Default is to allow 5 failed attempts every 6 hours. if (flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) { // We are not limited by flood control, so try to authenticate. if ($uid = user_authenticate($username, $password)) { // Clear the user based flood control. flood_clear_event('failed_login_attempt_user', $identifier); $user = user_load($uid); return user_load($uid); } flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 3600), $identifier); } else { flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 3600), $identifier); throw new FloodException(format_string('Rejected by user flood control.')); } }
public function _write($session_id, $user_data) { if (!count($this->session_exists($session_id))) { $args = array(':session_id' => $session_id, ':ip_address' => ip_address(), ':user_agent' => user_agent(), ':last_activity' => time(), ':user_data' => serialize($user_data)); $query = "REPLACE INTO sessions (session_id, ip_address, user_agent, last_activity, user_data) VALUES (:session_id, :ip_address, :user_agent, :last_activity, :user_data)"; } else { $args = array(':session_id' => $session_id, ':user_data' => serialize($user_data)); $query = "UPDATE sessions SET user_data = :user_data WHERE session_id = :session_id"; } return $this->db->query($query, $args); }
function run() { // generate json output from iats service calls $request = $_POST; $pp_id = (int) $request['payment_processor_id']; if (empty($pp_id)) { return; } $params = array('version' => 3, 'sequential' => 1, 'id' => $pp_id, 'return' => 'user_name'); $result = civicrm_api('PaymentProcessor', 'getvalue', $params); $request['agentCode'] = $result; $params = array('version' => 3, 'sequential' => 1, 'id' => $pp_id, 'return' => 'url_site'); $result = civicrm_api('PaymentProcessor', 'getvalue', $params); $request['iats_domain'] = parse_url($result, PHP_URL_HOST); foreach (array('reset', 'q', 'IDS_request_uri', 'IDS_user_agent', 'payment_processor_id') as $key) { if (isset($request[$key])) { unset($request[$key]); } } $options = array(); foreach (array('type', 'method', 'iats_domain') as $key) { if (isset($request[$key])) { $options[$key] = $request[$key]; unset($request[$key]); } } $credentials = array(); foreach (array('agentCode', 'password') as $key) { if (isset($request[$key])) { $credentials[$key] = $request[$key]; unset($request[$key]); } } // TODO: bail here if I don't have enough for my service request // use the iATSService object for interacting with iATS require_once "CRM/iATS/iATSService.php"; $iats = new iATS_Service_Request($options); $request['customerIPAddress'] = function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']; // make the soap request $response = $iats->request($credentials, $request); // process the soap response into a readable result if (!empty($response)) { $result = $iats->result($response); } else { $result = array('Invalid request'); } // TODO: fix header // header('Content-Type: text/javascript'); echo json_encode(array_merge($result)); exit; }
/** * Sends usage details to 51Degrees.mobi. * * Sends usage details to 51Degrees.mobi about the request for subsequent * analysis and product improvement. */ function fiftyone_degrees_SendDetails() { if (session_status() == PHP_SESSION_NONE) { session_start(); } $details_sent = FALSE; if (array_key_exists('fiftyone_degrees_details_sent', $_SESSION)) { $details_sent = $_SESSION['fiftyone_degrees_details_sent'] === TRUE; } if (!$details_sent && (extension_loaded('sockets') || extension_loaded('php_sockets'))) { $server_ip = 'udp.devices.51degrees.mobi'; $server_port = 80; // Get the ip address of the requesting client. if (function_exists('ip_address')) { // Used if Drupal (or others) have ip_address method. $ip = ip_address(); } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } $server_ip = $_SERVER['SERVER_ADDR']; // Construct the XML message. $message = '<?xml version="1.0" encoding="utf-16"?> <Device> <DateSent>' . gmdate('c') . '</DateSent> <Product>51degrees - Foundation - PHP</Product> <Version>3.1.2.1</Version> <ClientIP>' . $ip . '</ClientIP> <ServerIP>' . $server_ip . '</ServerIP>'; // Add the headers to the information being sent. $headers = fiftyone_degrees_GetHeaders(); foreach ($headers as $servervar => $val) { if (strtolower($servervar) == "referer" || strtolower($servervar) == "cookie") { $message .= '<Header Name="' . $servervar . '"></Header>'; } else { $message .= '<Header Name="' . $servervar . '"><![CDATA[' . $val . ']]></Header>'; } } $message .= '</Device>'; // Send a UDP packet with the xml content. @($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)); if ($socket) { @socket_sendto($socket, $message, strlen($message), 0, $server_ip, $server_port); } $_SESSION['fiftyone_degrees_details_sent'] = TRUE; } }
public function login($data, $session = true) { // Check if e-mail exists. $member = $this->get_member('email', $data['email']); if (!$member) { // Log unsuccessful logins for sessions. if ($session) { $this->db->insert('logins', array('ip_address' => ip_address(), 'timestamp' => time())); } // That's a negative return false; } // If we're going to set a session, check that member is an admin or boardmember if ($session && !$this->is_boardmember($member->id) && !$this->is_admin($member->id)) { return false; } // Load password library $this->load->library('Pass'); // Verify password $result = $this->pass->verify($data['password'], $member->password); if (!$result) { // Log unsuccessful login to database $this->db->insert('logins', array('member_id' => $member->id, 'ip_address' => ip_address(), 'timestamp' => time())); return false; } // Check if wanna start a session or not if ($session) { // Set session $userdata = array('member_id' => $member->id, 'email' => $data['email'], 'logged_in' => true); if (!empty($data['remember'])) { $userdata['remember_me'] = true; } $this->session->set_userdata($userdata); // Log successful login in database $this->db->insert('logins', array('member_id' => $member->id, 'ip_address' => ip_address(), 'timestamp' => time(), 'valid' => 1)); // Failsafe return is_loggedin(); } else { // No session, but return true return true; } return false; }
public function send_forgot_password($to, $token, $recipient_name = '') { $subject = 'Password recovery for internal.makerspace.se'; $template = 'Hello! A password recovery reset has been sent from IP-address: %s. If you did not ask for a password reset, you can safely ignore this email. To reset your password, please visit this page: https://internal.makerspace.se/auth/reset/%s -- Regards, E-mail Robot Stockholm Makerspace'; // New email $email = $this->new_email($to, $recipient_name); $body = sprintf($template, ip_address(), $token); // Set subject $email->Subject = $subject; // Set body. $email->Body = $body; return $email->Send(); }
/** * Update an existing session * * @access public * @return void */ function sess_update() { // We only update the session every five minutes by default if ($this->userdata['last_activity'] + $this->sess_time_to_update >= $this->now) { return; } // Save the old session id so we know which record to // update in the database if we need it $old_sessid = $this->userdata['session_id']; $new_sessid = ''; while (strlen($new_sessid) < 32) { $new_sessid .= mt_rand(0, mt_getrandmax()); } // To make the session ID even more secure we'll combine it with the user's IP $new_sessid .= ip_address(); // Turn it into a hash $new_sessid = md5(uniqid($new_sessid, TRUE)); // Update the session data in the session data array $this->userdata['session_id'] = $new_sessid; $this->userdata['last_activity'] = $this->now; // _set_cookie() will handle this for us if we aren't using database sessions // by pushing all userdata to the cookie. $cookie_data = NULL; // Write the cookie $this->_set_cookie($cookie_data); }
if (!file_exists('includes/bootstrap.inc')) { exit('Can not find Drupal directory.'); } // Running full Drupal bootstrap include_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); $safety = isset($_GET['safety']) ? $_GET['safety'] : ''; $valid_safety = $safety === variable_get(SUPERCRON_SAFETY_VARIABLE, NULL); // IP authorization check if (variable_get(SUPERCRON_FIREWALL_ENABLED_VARIABLE, FALSE)) { $mode = variable_get(SUPERCRON_FIREWALL_MODE_VARIABLE, 'only'); $ip = ip_address(); if (is_null($ip)) $ip = '127.0.0.1'; // bash calls return a null calling IP $result = db_query('SELECT * FROM {supercron_ips}'); $authorized = $mode === 'except'; while ($dbip = db_fetch_object($result)) { if ($ip == $dbip->ip) { $authorized = $mode === 'only'; break; } } if (!$authorized) { exit("IP '$ip' not authorized!"); } }
/** * Web Service: Build JSON request parameters * * Assumes request has been validated. * * @param $request_state * @see CommerceFirstDataGGE4Controller::resolvePaymentState() * * @return * A name-value pair array for a JSON request */ protected function requestBuild(&$request_state) { // Resolve state $this->controller->resolvePaymentState($request_state); // Set local vars for easy reference $charge = $request_state['charge']; $card = $request_state['card']; $order = $request_state['order']; $billing_address = $request_state['billing_address']; $prev_transaction = $request_state['previous_transaction']; // load transaction type info $txn_type_info = $this->controller->transactionType($request_state['txn_type']); // Add build info with request indicators $request_state['build_info'] = array('zero_amount' => commerce_firstdata_gge4_is_zero($charge['amount'])); // Zero Dollar Pre-Authorizations if ($request_state['txn_type'] != FIRSTDATA_GGE4_CREDIT_PREAUTH_ONLY && $request_state['build_info']['zero_amount'] && !empty($txn_type_info['zero_auth_allowed'])) { $request_state['txn_type'] = FIRSTDATA_GGE4_CREDIT_PREAUTH_ONLY; $txn_type_info = $this->controller->transactionType($request_state['txn_type']); } // Convert Commerce txn type to gateway code $request_state['gateway_txn_type'] = $txn_type_info['gateway_code']; // Set transaction type $txn_type_code = $request_state['txn_type']; // Initialize request parameters $params = array('transaction_type' => $request_state['gateway_txn_type']); // Determine charge context $params += array('amount' => !$request_state['build_info']['zero_amount'] ? commerce_currency_amount_to_decimal($charge['amount'], $charge['currency_code']) : 0, 'currency_code' => $charge['currency_code']); // Parameters required per txn type if (!empty($txn_type_info['requires_card'])) { // Purchase, Pre-auth, Pre-auth only, Refund via credit card // Billing address parameters if (!empty($billing_address)) { $params['zip_code'] = substr($billing_address['postal_code'], 0, 10); // cc_verification_str1: "Street Address|Zip/Postal|City|State/Prov|Country" $billing_address_verify_parts = array($billing_address['street_line'], $billing_address['postal_code'], $billing_address['locality'], $billing_address['administrative_area'], $billing_address['country']); $params['cc_verification_str1'] = implode('|', $billing_address_verify_parts); $params['cc_verification_str1'] = substr($params['cc_verification_str1'], 0, 41); } // Add expiration $params += array('cc_expiry' => str_pad($card->card_exp_month, 2, '0', STR_PAD_LEFT) . substr($card->card_exp_year, -2)); // Add cardholder name $cardholder_name = ''; if (!empty($card->card_name)) { // Set to name on card $cardholder_name = $card->card_name; } elseif (!empty($billing_address['name_line'])) { // Set to billing address name $cardholder_name = $billing_address['name_line']; } $card->card_name = $params['cardholder_name'] = substr($cardholder_name, 0, 30); // Add additional card data $params += array('cc_number' => substr($card->card_number, 0, 16)); // CVV code should only be available during checkout or new cards if (!empty($card->card_code)) { $params['cc_verification_str2'] = substr($card->card_code, 0, 4); $params['cvd_presence_ind'] = "1"; } } elseif (!empty($txn_type_info['transaction_operation'])) { // Pre-auth capture, Void, Refund $params['authorization_num'] = substr($prev_transaction->data['authorization_num'], 0, 8); $params['transaction_tag'] = (int) $prev_transaction->data['transaction_tag']; } // Add order information if (!empty($order->order_number)) { $params['reference_no'] = $order->order_number; } // @todo: Level 2 order info - tax, etc // @todo: Level 3 order info - line items, etc // Add customer params if (isset($request_state['customer']->uid)) { $params['customer_ref'] = substr($request_state['customer']->uid, 0, 20); } if (isset($request_state['customer']->mail)) { $params['client_email'] = substr($request_state['customer']->mail, 0, 255); } $params['client_ip'] = substr(ip_address(), 0, 15); // Common parameters /** @todo use site or get from owner - order or card **/ $params['language'] = $this->controller->convertLanguage(language_default('language')); // Allow other plugins and modules to alter $this->controller->alter('ws_request_build', $params, $request_state); return $params; }
/** * Check basic auth against allowed values. */ function ah_check_basic_auth() { global $conf; $authorized = FALSE; $php_auth_user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : NULL; $php_auth_pw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : NULL; $credentials = isset($conf['ah_basic_auth_credentials']) ? $conf['ah_basic_auth_credentials'] : NULL; if ($php_auth_user && $php_auth_pw && !empty($credentials)) { if (isset($credentials[$php_auth_user]) && $credentials[$php_auth_user] == $php_auth_pw) { $authorized = TRUE; } } if ($authorized) { return; } // Always fall back to 401. ah_page_401(ip_address()); }
/** * {@inheritdoc} */ public function generateIdentifier($account = NULL) { $identifier = $this->resource->getResourceName() . PluginBase::DERIVATIVE_SEPARATOR; if ($this->getPluginId() == 'global') { // Don't split the id by resource if the event is global. $identifier = ''; } $identifier .= $this->getPluginId() . PluginBase::DERIVATIVE_SEPARATOR; $identifier .= empty($account->uid) ? ip_address() : $account->uid; return $identifier; }
function _write($session_id, $user_data) { $args = array(':session_id' => $session_id, ':ip_address' => ip_address(), ':user_agent' => user_agent(), ':last_activity' => time(), ':user_data' => serialize($user_data)); $query = "REPLACE INTO sessions VALUES (:session_id, :ip_address, :user_agent, :last_activity, :user_data)"; return $this->db->query($query, $args); }
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n"; } echo $file; // Record usage statistics. if (isset($_GET['site_key'])) { if (!chdir(BACKDROP_ROOT)) { exit(1); } include_once './core/includes/bootstrap.inc'; backdrop_bootstrap(BACKDROP_BOOTSTRAP_DATABASE); // We can't call module_exists without bootstrapping to a higher level so // we'll settle for checking that the table exists. if (db_table_exists('project_usage_raw')) { $site_key = $_GET['site_key']; $project_version = isset($_GET['version']) ? $_GET['version'] : ''; $ip_address = ip_address(); // Compute a GMT timestamp for beginning of the day. getdate() is // affected by the server's timezone so we need to cancel it out. $now = time(); $time_parts = getdate($now - date('Z', $now)); $timestamp = gmmktime(0, 0, 0, $time_parts['mon'], $time_parts['mday'], $time_parts['year']); $result = db_query("UPDATE {project_usage_raw} SET version_api = :version_api, version = :version, hostname = :hostname WHERE name = :name AND timestamp = :timestamp AND site_key = :site_key", array(':version_api' => $version_api, ':version' => $project_version, ':hostname' => $ip_address, ':name' => $project_name, ':timestamp' => $timestamp, ':site_key' => $site_key)); if ($result->rowCount() === 0) { db_query("INSERT INTO {project_usage_raw} (name, timestamp, site_key, version_api, version, hostname) VALUES (:name, :timestamp, :site_key, :version_api, :version, :hostname)", array(':name' => $project_name, ':timestamp' => $timestamp, ':site_key' => $site_key, ':version_api' => $version_api, ':version' => $project_version, ':hostname' => $ip_address)); } } } /** * Copy of core's check_plain() function. */ function _check_plain($text)
function boost_stats_add_access_log() { global $title, $q, $referer, $session_id, $uid; db_query("INSERT INTO {accesslog} (title, path, url, hostname, uid, sid, timer, timestamp) values('%s', '%s', '%s', '%s', %d, '%s', %d, %d)", $title, $q, $referer, ip_address(), $uid, $session_id, timer_read('page'), time()); }
/** * Check the current session to make sure the user is the same (or else create a new session) * @return unknown_type */ function check() { //On creation store the useragent fingerprint if (empty($_SESSION['fingerprint'])) { $_SESSION['fingerprint'] = $this->generate_fingerprint(); } elseif ($this->match_fingerprint && $_SESSION['fingerprint'] != $this->generate_fingerprint()) { return FALSE; } //If an IP address is present and we should check to see if it matches if (isset($_SESSION['ip_address']) && $this->match_ip) { //If the IP does NOT match if ($_SESSION['ip_address'] != ip_address()) { return FALSE; } } //Set the users IP Address $_SESSION['ip_address'] = ip_address(); //If a token was given for this session to match if ($this->match_token) { if (empty($_SESSION['token']) or $_SESSION['token'] != $this->match_token) { //Remove token check $this->match_token = FALSE; return FALSE; } } //Set the session start time so we can track when to regenerate the session if (empty($_SESSION['last_activity'])) { $_SESSION['last_activity'] = time(); } elseif ($_SESSION['last_activity'] + $this->expiration < time()) { //Generate a new session id and a new cookie with the updated id session_regenerate_id(); //Store new time that the session was generated $_SESSION['last_activity'] = time(); } return TRUE; }
/** * {@inheritdoc} */ public function generateIdentifier(\stdClass $account = NULL) { $identifier = ''; $identifier .= $this->name . '::'; $identifier .= empty($account->uid) ? ip_address() : $account->uid; return $identifier; }
$script_name = $argv[0]; $_SERVER['HTTP_HOST'] = SITE_NAME; $_SERVER['REQUEST_URI'] = '/' . $script_name; $_SERVER['SCRIPT_NAME'] = '/' . $script_name; $_SERVER['PHP_SELF'] = '/' . $script_name; $_SERVER['SCRIPT_FILENAME'] = $_SERVER['PWD'] . '/' . $script_name; $_SERVER['PATH_TRANSLATED'] = $_SERVER['SCRIPT_FILENAME']; // Actually do the bootstrap. include_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE); // We can't call module_exists without bootstrapping to a higher level so // we'll settle for checking that the table exists. if (db_table_exists('project_usage_raw')) { $site_key = $_GET['site_key']; $project_version = isset($_GET['version']) ? $_GET['version'] : ''; $ip_addr = ip_address(); // Compute a GMT timestamp for begining of the day. getdate() is // affected by the server's timezone so we need to cancel it out. $now = time(); $time_parts = getdate($now - date('Z', $now)); $timestamp = gmmktime(0, 0, 0, $time_parts['mon'], $time_parts['mday'], $time_parts['year']); db_query("UPDATE {project_usage_raw} SET api_version = '%s', project_version = '%s', ip_addr = '%s' WHERE project_uri = '%s' AND timestamp = %d AND site_key = '%s'", $api_version, $project_version, $ip_addr, $project_name, $timestamp, $site_key); if (!db_affected_rows()) { db_query("INSERT INTO {project_usage_raw} (project_uri, timestamp, site_key, api_version, project_version, ip_addr) VALUES ('%s', %d, '%s', '%s', '%s', '%s')", $project_name, $timestamp, $site_key, $api_version, $project_version, $ip_addr); } } } /** * Copy of core's check_plain() function. */ function _check_plain($text)
/** * Returns a payment form to be used during checkout or elsewhere */ public function paymentForm($form, &$form_state, &$request_state = array()) { if (!$this->isValid()) { return $form; } // Resolve state $this->controller->resolvePaymentState($request_state); // Get plugin settings $settings = $this->getSettings(); // Set transaction type based on settings. $txn_type = $this->controller->getSettings('txn_type'); $x_type = 'AUTH_CAPTURE'; if ($txn_type == COMMERCE_CREDIT_AUTH_ONLY) { $x_type = 'AUTH_ONLY'; } // Initialize variables $order = $request_state['order']; $description = array(); $card = $request_state['card']; $charge = $request_state['charge']; $cancel_path = ''; // Order data if (!empty($order)) { $order_wrapper = entity_metadata_wrapper('commerce_order', $order); $cancel_path = 'checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key']; // Build a description for the order. /** @todo: create details for x_line_item instead of x_description which is not used ***/ foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) { if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) { $description[] = round($line_item_wrapper->quantity->value(), 2) . 'x ' . $line_item_wrapper->line_item_label->value(); } } } // Card data if (!empty($card)) { if (empty($cancel_path) && !empty($card->uid)) { $cancel_path = 'user/' . $card->uid . '/cards'; } } // Resolve charge - convert to decimal, fallback to 0 if (!empty($charge['amount'])) { $charge['amount_decimal'] = commerce_currency_amount_to_decimal($charge['amount'], $charge['currency_code']); } else { // Fallback to Zero dollar authorization $x_type = 'AUTH_ONLY'; $charge = array('amount' => 0, 'amount_decimal' => 0, 'currency_code' => isset($charge['currency_code']) ? $charge['currency_code'] : commerce_default_currency()); } // Build submit data $data = array('x_login' => $settings['page_id'], 'x_type' => $x_type, 'x_amount' => !empty($charge['amount_decimal']) ? number_format($charge['amount_decimal'], 2, '.', '') : '0', 'x_currency_code' => $charge['currency_code'], 'x_show_form' => 'PAYMENT_FORM', 'x_customer_ip' => ip_address(), 'x_receipt_link_method' => 'AUTO-POST', 'x_receipt_link_url' => $this->getAutoPostURL(), 'x_relay_response' => 'TRUE', 'x_relay_url' => $this->getRelayURL(), 'commerce_payment_method' => $this->controller->payment_instance['instance_id']); // Conditional fields // Order info if (!empty($order->order_id)) { $data += array('commerce_order_id' => $order->order_id, 'x_invoice_num' => $order->order_number, 'x_description' => substr(implode(', ', $description), 0, 255)); } // Customer if (!empty($request_state['customer']->uid)) { $data['x_cust_id'] = substr($request_state['customer']->uid, 0, 20); // Set customer_ref similar to web service // - x_po_num is passed to customer_ref in response $data['x_po_num'] = $data['x_cust_id']; } if (!empty($request_state['customer']->mail)) { $data['x_email'] = substr($request_state['customer']->mail, 0, 255); } // Billing address if (!empty($request_state['billing_address'])) { $billing_address = $request_state['billing_address']; $data += array('x_first_name' => substr($billing_address['first_name'], 0, 50), 'x_last_name' => substr($billing_address['last_name'], 0, 50), 'x_company' => substr($billing_address['organisation_name'], 0, 20), 'x_address' => substr($billing_address['street_line'], 0, 28), 'x_city' => substr($billing_address['locality'], 0, 20), 'x_state' => $this->controller->getStateName($billing_address['administrative_area'], $billing_address['country']), 'x_zip' => substr($billing_address['postal_code'], 0, 9), 'x_country' => $this->controller->getCountryName($billing_address['country'])); } // Allow other plugins and modules to alter $this->controller->alter('hpp_post_data', $data, $request_state); // Create the hash fingerprint $hmac_encryption_type = !empty($settings['hmac_encryption_type']) ? $settings['hmac_encryption_type'] : 'md5'; $data['x_fp_timestamp'] = REQUEST_TIME; $data['x_fp_sequence'] = mt_rand(1, 1000); $hash_seeds = array($data['x_login'], $data['x_fp_sequence'], $data['x_fp_timestamp'], $data['x_amount'], $data['x_currency_code']); $data['x_fp_hash'] = hash_hmac($hmac_encryption_type, implode('^', $hash_seeds), $settings['transaction_key']); // Log "request" $log_settings = $this->controller->getSettings('log'); if ($log_settings['request'] == 'request') { $this->controller->log('First Data GGe4 HPP submit data', $data); } // Set post url and transaction mode $submit_url = $this->getServerUrl(); $data['x_test_request'] = $this->isTestMode() ? 'TRUE' : 'FALSE'; // Build form elements $form['#action'] = $submit_url; $form['#method'] = "post"; foreach ($data as $name => $value) { $form[$name] = array('#type' => 'hidden', '#value' => $value); } $form['actions'] = array('#type' => 'actions', '#weight' => 50); $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Continue')); $form['actions']['cancel'] = array('#type' => 'link', '#title' => t('Cancel'), '#href' => $cancel_path, '#options' => array('absolute' => TRUE, 'html' => FALSE)); // Allow other plugins and modules to alter $this->controller->alter('hpp_payment_form', $form, $request_state); return $form; }
/** * Get logged in user's IP address. * * Get IP address from HTTP REMOTE_ADDR header. If the CMS is Drupal then use * the Drupal function as this also handles reverse proxies (based on proper * configuration in settings.php) * * @param bool $strictIPV4 * (optional) Whether to return only IPv4 addresses. * * @return string * IP address of logged in user. */ public static function ipAddress($strictIPV4 = TRUE) { $address = CRM_Utils_Array::value('REMOTE_ADDR', $_SERVER); $config = CRM_Core_Config::singleton(); if ($config->userSystem->is_drupal && function_exists('ip_address')) { //drupal function handles the server being behind a proxy securely. We still have legacy ipn methods // that reach this point without bootstrapping hence the check that the fn exists $address = ip_address(); } // hack for safari if ($address == '::1') { $address = '127.0.0.1'; } // when we need to have strictly IPV4 ip address // convert ipV6 to ipV4 if ($strictIPV4) { // this converts 'IPV4 mapped IPV6 address' to IPV4 if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && strstr($address, '::ffff:')) { $address = ltrim($address, '::ffff:'); } } return $address; }
if( document.location.search) fn += document.location.search; try { _gaq.push(['loadTracker._setAccount', 'UA-15658414-1']); _gaq.push(['loadTracker._trackEvent','Page Load (ms)',lc + ' Loading Pages',fn,plload]); _gaq.push(['loadTracker._trackPageview']); } catch(err){} } </script> <?php if($set_ok==1) { ?> <script type="text/javascript"> <!--//--><![CDATA[//><!-- BOOMR.init({"user_ip":"59.162.126.17","site_domain":".<?=$base_url?>","BW":{"base_url":"http:\/\/<?=$base_url?>\/sites\/all\/libraries\/boomerang\/images\/"},"beacon_url":"http:\/\/<?=$base_url?>\/beacon","RT":{"cookie":"BOOMR-RT","cookie_exp":120}}); BOOMR.addVar('page_id', '<?=ip_address()?>'); BOOMR.addVar('uid', '<?=$user->uid?>'); BOOMR.addVar('uname', '<?=$user->name?>'); //--><!]]> </script> <div id="boomerang-results"></div> <?php } ?> </body> </html>
/** * Job.IatsACHEFTVerify API * * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception * Look up all pending (status = 2) ACH/EFT contributions and see if they've been approved or rejected * Update the corresponding recurring contribution record to status = 1 (or 4) * This works for both the initial contribution and subsequent contributions of recurring contributions, as well as one offs. * TODO: what kind of alerts should be provided if it fails? * * Also lookup new UK direct debit series, and new contributions from existing series. */ function civicrm_api3_job_iatsacheftverify($iats_service_params) { $settings = CRM_Core_BAO_Setting::getItem('iATS Payments Extension', 'iats_settings'); $receipt_recurring = empty($settings['receipt_recurring']) ? 0 : 1; define('IATS_VERIFY_DAYS', 30); // I've added an extra 2 days when getting candidates from CiviCRM to be sure i've got them all. $civicrm_verify_days = IATS_VERIFY_DAYS + 2; // get all the pending direct debit contributions that still need approval within the last civicrm_verify_days $select = 'SELECT id, trxn_id, invoice_id, contact_id, contribution_recur_id, receive_date FROM civicrm_contribution WHERE contribution_status_id = 2 AND payment_instrument_id = 2 AND receive_date > %1 AND is_test = 0'; $args = array(1 => array(date('c', strtotime('-' . $civicrm_verify_days . ' days')), 'String')); $dao = CRM_Core_DAO::executeQuery($select, $args); $acheft_pending = array(); while ($dao->fetch()) { /* we assume that the iATS transaction id is a unique field for matching, and that it is stored as the first part of the civicrm transaction */ /* this is not unreasonable, assuming that the site doesn't have other active direct debit payment processors with similar patterns */ $key = current(explode(':', $dao->trxn_id, 2)); $acheft_pending[$key] = array('id' => $dao->id, 'trxn_id' => $dao->trxn_id, 'invoice_id' => $dao->invoice_id, 'contact_id' => $dao->contact_id, 'contribution_recur_id' => $dao->contribution_recur_id, 'receive_date' => $dao->receive_date); } // and some recent UK DD recurring contributions $select = 'SELECT c.id, c.contribution_status_id, c.trxn_id, c.invoice_id, icc.customer_code FROM civicrm_contribution c INNER JOIN civicrm_contribution_recur cr ON c.contribution_recur_id = cr.id INNER JOIN civicrm_payment_processor pp ON cr.payment_processor_id = pp.id INNER JOIN civicrm_iats_customer_codes icc ON cr.id = icc.recur_id WHERE c.receive_date > %1 AND pp.class_name = %2 AND pp.is_test = 0'; $args[2] = array('Payment_iATSServiceUKDD', 'String'); $dao = CRM_Core_DAO::executeQuery($select, $args); $ukdd_contribution = array(); while ($dao->fetch()) { if (empty($ukdd_contribution[$dao->customer_code])) { $ukdd_contribution[$dao->customer_code] = array(); } // I want to key on my trxn_id that I can match up with data from iATS, but use the invoice_id for that initial pending one $key = empty($dao->trxn_id) ? $dao->invoice_id : $dao->trxn_id; $ukdd_contribution[$dao->customer_code][$key] = array('id' => $dao->id, 'contribution_status_id' => $dao->contribution_status_id, 'invoice_id' => $dao->invoice_id); } // and now get all the non-completed UKDD sequences, in order to track new contributions from iATS $select = 'SELECT cr.*, icc.customer_code as customer_code, icc.cid as icc_contact_id, iukddv.acheft_reference_num as reference_num, pp.is_test FROM civicrm_contribution_recur cr INNER JOIN civicrm_payment_processor pp ON cr.payment_processor_id = pp.id INNER JOIN civicrm_iats_customer_codes icc ON cr.id = icc.recur_id INNER JOIN civicrm_iats_ukdd_validate iukddv ON cr.id = iukddv.recur_id WHERE pp.class_name = %1 AND pp.is_test = 0 AND (cr.end_date IS NULL OR cr.end_date > NOW())'; $args = array(1 => array('Payment_iATSServiceUKDD', 'String')); $dao = CRM_Core_DAO::executeQuery($select, $args); $ukdd_contribution_recur = array(); while ($dao->fetch()) { $ukdd_contribution_recur[$dao->customer_code] = get_object_vars($dao); } /* get "recent" approvals and rejects from iats and match them up with my pending list, or one-offs, or UK DD via the customer code */ require_once "CRM/iATS/iATSService.php"; // an array of methods => contribution status of the records retrieved $process_methods = array('acheft_journal_csv' => 1, 'acheft_payment_box_journal_csv' => 1, 'acheft_payment_box_reject_csv' => 4); /* initialize some values so I can report at the end */ $error_count = 0; // count the number of each record from iats analysed, and the number of each kind found $processed = array_fill_keys(array_keys($process_methods), 0); $found = array('recur' => 0, 'quick' => 0, 'new' => 0); // save all my api result messages as well $output = array(); /* do this loop for each relevant payment processor of type ACHEFT or UKDD */ /* since test payments are NEVER verified by iATS, don't bother checking them [unless/until they change this?] */ $select = 'SELECT id,url_site,is_test FROM civicrm_payment_processor WHERE (class_name = %1 OR class_name = %2) AND is_test = 0'; $args = array(1 => array('Payment_iATSServiceACHEFT', 'String'), 2 => array('Payment_iATSServiceUKDD', 'String')); $dao = CRM_Core_DAO::executeQuery($select, $args); // watchdog('civicrm_iatspayments_com', 'pending: <pre>!pending</pre>', array('!pending' => print_r($iats_acheft_recur_pending,TRUE)), WATCHDOG_NOTICE); while ($dao->fetch()) { /* get approvals from yesterday, approvals from previous days, and then rejections for this payment processor */ $iats_service_params = array('type' => 'report', 'iats_domain' => parse_url($dao->url_site, PHP_URL_HOST)) + $iats_service_params; /* the is_test below should always be 0, but I'm leaving it in, in case eventually we want to be verifying tests */ $credentials = iATS_Service_Request::credentials($dao->id, $dao->is_test); foreach ($process_methods as $method => $contribution_status_id) { // TODO: this is set to capture approvals and cancellations from the past month, for testing purposes // it doesn't hurt, but on a live environment, this maybe should be limited to the past week, or less? // or, it could be configurable for the job $iats_service_params['method'] = $method; $iats = new iATS_Service_Request($iats_service_params); // I'm now using the new v2 version of the payment_box_journal, so a previous hack here is now removed switch ($method) { case 'acheft_journal_csv': // special case to get today's transactions, so we're as real-time as we can be $request = array('date' => date('Y-m-d') . 'T23:59:59+00:00', 'customerIPAddress' => function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']); break; default: // box journals only go up to the end of yesterday $request = array('fromDate' => date('Y-m-d', strtotime('-' . IATS_VERIFY_DAYS . ' days')) . 'T00:00:00+00:00', 'toDate' => date('Y-m-d', strtotime('-1 day')) . 'T23:59:59+00:00', 'customerIPAddress' => function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']); break; } // make the soap request, should return a csv file $response = $iats->request($credentials, $request); $transactions = $iats->getCSV($response, $method); if ($method == 'acheft_journal_csv') { // also grab yesterday + day before yesterday + day before that + the day before that if it (in case of stat holiday - long weekend) $request = array('date' => date('Y-m-d', strtotime('-1 day')) . 'T23:59:59+00:00', 'customerIPAddress' => function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']); $response = $iats->request($credentials, $request); $transactions = array_merge($transactions, $iats->getCSV($response, $method)); $request = array('date' => date('Y-m-d', strtotime('-2 days')) . 'T23:59:59+00:00', 'customerIPAddress' => function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']); $response = $iats->request($credentials, $request); $transactions = array_merge($transactions, $iats->getCSV($response, $method)); $request = array('date' => date('Y-m-d', strtotime('-3 days')) . 'T23:59:59+00:00', 'customerIPAddress' => function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']); $response = $iats->request($credentials, $request); $transactions = array_merge($transactions, $iats->getCSV($response, $method)); $request = array('date' => date('Y-m-d', strtotime('-4 days')) . 'T23:59:59+00:00', 'customerIPAddress' => function_exists('ip_address') ? ip_address() : $_SERVER['REMOTE_ADDR']); $response = $iats->request($credentials, $request); $transactions = array_merge($transactions, $iats->getCSV($response, $method)); } $processed[$method] += count($transactions); // watchdog('civicrm_iatspayments_com', 'transactions: <pre>!trans</pre>', array('!trans' => print_r($transactions,TRUE)), WATCHDOG_NOTICE); foreach ($transactions as $transaction_id => $transaction) { $contribution = NULL; // use this later to trigger an activity if it's not NULL // first deal with acheft_pending, [and possibly the corresponding recur sequence ? no? ] if (!empty($acheft_pending[$transaction_id])) { /* update the contribution status */ /* todo: additional sanity testing? We're assuming the uniqueness of the iATS transaction id here */ $is_recur = 'quick client' != strtolower($transaction->customer_code); $found[$is_recur ? 'recur' : 'quick']++; $contribution = $acheft_pending[$transaction_id]; // updating a contribution status to complete needs some extra bookkeeping if (1 == $contribution_status_id) { // note that I'm updating the timestamp portion of the transaction id here, since this might be useful at some point // should I update the receive date to when it was actually received? Would that confuse membership dates? $trxn_id = $transaction_id . ':' . time(); $complete = array('version' => 3, 'id' => $contribution['id'], 'trxn_id' => $transaction_id . ':' . time(), 'receive_date' => $contribution['receive_date']); if ($is_recur) { $complete['is_email_receipt'] = $receipt_recurring; /* use my saved setting for recurring completions */ } try { $contributionResult = civicrm_api3('contribution', 'completetransaction', $complete); } catch (Exception $e) { throw new API_Exception('Failed to complete transaction: ' . $e->getMessage() . "\n" . $e->getTraceAsString()); } // restore my source field that ipn irritatingly overwrites, and make sure that the trxn_id is set also civicrm_api3('contribution', 'setvalue', array('version' => 3, 'id' => $contribution['id'], 'value' => $contribution['source'], 'field' => 'source')); civicrm_api3('contribution', 'setvalue', array('version' => 3, 'id' => $contribution['id'], 'value' => $trxn_id, 'field' => 'trxn_id')); } else { $params = array('version' => 3, 'sequential' => 1, 'contribution_status_id' => $contribution_status_id, 'id' => $contribution['id']); $result = civicrm_api3('Contribution', 'create', $params); // update the contribution } // always log these requests in my cutom civicrm table for auditing type purposes // watchdog('civicrm_iatspayments_com', 'contribution: <pre>!contribution</pre>', array('!contribution' => print_r($query_params,TRUE)), WATCHDOG_NOTICE); $query_params = array(1 => array($transaction->customer_code, 'String'), 2 => array($contribution['contact_id'], 'Integer'), 3 => array($contribution['id'], 'Integer'), 4 => array($contribution_status_id, 'Integer'), 5 => array($contribution['contribution_recur_id'], 'Integer')); if (empty($contribution['contribution_recur_id'])) { unset($query_params[5]); CRM_Core_DAO::executeQuery("INSERT INTO civicrm_iats_verify\n (customer_code, cid, contribution_id, contribution_status_id, verify_datetime) VALUES (%1, %2, %3, %4, NOW())", $query_params); } else { CRM_Core_DAO::executeQuery("INSERT INTO civicrm_iats_verify\n (customer_code, cid, contribution_id, contribution_status_id, verify_datetime, recur_id) VALUES (%1, %2, %3, %4, NOW(), %5)", $query_params); } } elseif (isset($ukdd_contribution_recur[$transaction->customer_code])) { // it's a (possibly) new recurring UKDD contribution triggered from iATS // check my existing ukdd_contribution list in case it's the first one that just needs to be updated, or has already been processed // I also confirm that it's got the right ach reference field, which i get from the ukdd_contribution_recur record $contribution_recur = $ukdd_contribution_recur[$transaction->customer_code]; // build the (unique) civicrm trxn id that we can use to match up against civicrm-stored transactions $trxn_id = $transaction->id . ':iATSUKDD:' . $transaction->customer_code; // sanity check against the ACH Reference number, but only if I get it from iATS if (!empty($transaction->achref) && $contribution_recur['reference_num'] != $transaction->achref) { $output[] = ts('Unexpected error: ACH Ref. %1 does not match for customer code %2 (should be %3)', array(1 => $transaction->achref, 2 => $transaction->customer_code, 3 => $contribution_recur['reference_num'])); ++$error_count; } elseif (isset($ukdd_contribution[$transaction->customer_code][$trxn_id])) { // I can ignore it, i've already created this one } else { // save my contribution in civicrm $contribution = array('version' => 3, 'contact_id' => $contribution_recur['contact_id'], 'receive_date' => date('c', $transaction->receive_date), 'total_amount' => $transaction->amount, 'payment_instrument_id' => $contribution_recur['payment_instrument_id'], 'contribution_recur_id' => $contribution_recur['id'], 'trxn_id' => $trxn_id, 'invoice_id' => md5(uniqid(rand(), TRUE)), 'source' => 'iATS UK DD Reference: ' . $contribution_recur['reference_num'], 'contribution_status_id' => $contribution_status_id, 'currency' => $contribution_recur['currency'], 'payment_processor' => $contribution_recur['payment_processor_id'], 'is_test' => 0); if (isset($dao->contribution_type_id)) { // 4.2 $contribution['contribution_type_id'] = $contribution_recur['contribution_type_id']; } else { // 4.3+ $contribution['financial_type_id'] = $contribution_recur['financial_type_id']; } // if I have an outstanding pending contribution for this series, I'll recycle and update it here foreach ($ukdd_contribution[$transaction->customer_code] as $key => $contrib_ukdd) { if ($contrib_ukdd['contribution_status_id'] == 2) { // it's pending $contribution['id'] = $contrib_ukdd['id']; // don't change my invoice id in this case unset($contribution['invoice_id']); // ensure I don't pull this trick more than once somehow unset($ukdd_contribution[$transaction->customer_code][$key]); // and note that I ignore everything else about the pending contribution in civicrm break; } } // otherwise I'll make do with a template if available $contribution_template = array(); if (empty($contribution['id'])) { // populate my contribution from a template if possible $contribution_template = _iats_civicrm_getContributionTemplate(array('contribution_recur_id' => $contribution_recur['id'], 'total_amount' => $transation->amount)); $get_from_template = array('contribution_campaign_id', 'amount_level'); foreach ($get_from_template as $field) { if (isset($contribution_template[$field])) { $contribution[$field] = $contribution_template[$field]; } } if (!empty($contribution_template['line_items'])) { $contribution['skipLineItem'] = 1; $contribution['api.line_item.create'] = $contribution_template['line_items']; } } if ($contribution_status_id == 1) { // create or update as pending and then complete $contribution['contribution_status_id'] = 2; $result = civicrm_api('contribution', 'create', $contribution); $complete = array('version' => 3, 'id' => $result['id'], 'trxn_id' => $trxn_id, 'receive_date' => $contribution['receive_date']); $complete['is_email_receipt'] = $receipt_recurring; /* send according to my configuration */ try { $contributionResult = civicrm_api('contribution', 'completetransaction', $complete); // restore my source field that ipn irritatingly overwrites, and make sure that the trxn_id is set also civicrm_api('contribution', 'setvalue', array('version' => 3, 'id' => $contribution['id'], 'value' => $contribution['source'], 'field' => 'source')); civicrm_api('contribution', 'setvalue', array('version' => 3, 'id' => $contribution['id'], 'value' => $trxn_id, 'field' => 'trxn_id')); } catch (Exception $e) { throw new API_Exception('Failed to complete transaction: ' . $e->getMessage() . "\n" . $e->getTraceAsString()); } } else { // create or update $result = civicrm_api('contribution', 'create', $contribution); } if ($result['is_error']) { $output[] = $result['error_message']; } else { $found['new']++; } } } // if one of the above was true and I've got a new or confirmed contribution: // so log it as an activity for administrative reference if (!empty($contribution)) { $subject_string = empty($contribution['id']) ? 'Found new iATS Payments UK DD contribution for contact id %3' : '%1 iATS Payments ACH/EFT contribution id %2 for contact id %3'; $subject = ts($subject_string, array(1 => $contribution_status_id == 4 ? ts('Cancelled') : ts('Verified'), 2 => $contribution['id'], 3 => $contribution['contact_id'])); $result = civicrm_api('activity', 'create', array('version' => 3, 'activity_type_id' => 6, 'source_contact_id' => $contribution['contact_id'], 'assignee_contact_id' => $contribution['contact_id'], 'subject' => $subject, 'status_id' => 2, 'activity_date_time' => date("YmdHis"))); if ($result['is_error']) { $output[] = ts('An error occurred while creating activity record for contact id %1: %2', array(1 => $contribution['contact_id'], 2 => $result['error_message'])); ++$error_count; } else { $output[] = $subject; } } // otherwise ignore it } } } $message = '<br />' . ts('Completed with %1 errors.', array(1 => $error_count)); $message .= '<br />' . ts('Processed %1 approvals from today and past 4 days, %2 approval and %3 rejection records from the previous ' . IATS_VERIFY_DAYS . ' days.', array(1 => $processed['acheft_journal_csv'], 2 => $processed['acheft_payment_box_journal_csv'], 3 => $processed['acheft_payment_box_reject_csv'])); // If errors .. if ($error_count) { return civicrm_api3_create_error($message . '</br />' . implode('<br />', $output)); } // If no errors and some records processed .. if (array_sum($processed) > 0) { if (count($acheft_pending) > 0) { $message .= '<br />' . ts('For %1 pending ACH/EFT contributions, %2 non-recuring and %3 recurring contribution results applied.', array(1 => count($acheft_pending), 2 => $found['quick'], 3 => $found['recur'])); } if (count($ukdd_contribution_recur) > 0) { $message .= '<br />' . ts('For %1 recurring UK direct debit contribution series, %2 new contributions found.', array(1 => count($ukdd_contribution_recur), 2 => $found['new'])); } return civicrm_api3_create_success($message . '<br />' . implode('<br />', $output)); } // No records processed return civicrm_api3_create_success(ts('No records found to process.')); }
function insertLog($msgerro, $tipo = FALSE) { global $perfil, $cfg, $actualpage; $valores['err_who'] = $perfil['ID_USER']; //$valores['err_where'] = (!$actualpage)?serialize(getIndex()):serialize($this->actualpage); $valores['err_type'] = $tipo == FALSE ? FALSE : TRUE; $valores['err_ip'] = ip_address(); $valores['err_how'] = is_array($msgerro) ? implode("</br>", $msgerro) : $msgerro; $tabela = '{logError}'; $sql = $this->SqlInsert($tabela, $valores); return $request = $this->SqlSelect($sql); }
Page <b><?php echo Url::request(); ?> </b> not found. Your IP is <?php echo ip_address(); ?> , and here is a random string: <?php echo random_string(); ?> .
/** * Generates an identifier for the event and the request. * * @param \stdClass $account * The account object for the user making the request. * * @return string */ public function generateIdentifier(\stdClass $account = NULL) { $identifier = $this->resource . '::'; if ($this->name == 'global') { // Don't split the id by resource if the event is global. $identifier = ''; } $identifier .= $this->name . '::'; $identifier .= empty($account->uid) ? ip_address() : $account->uid; return $identifier; }