+++ /dev/null
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-require_once 'CRM/Core/Payment.php';
-require_once ('packages/Google/library/googlecart.php');
-require_once ('packages/Google/library/googleitem.php');
-
-/**
- * Class org_civicrm_payment_googlecheckout
- */
-class org_civicrm_payment_googlecheckout extends CRM_Core_Payment {
-
- /**
- * We only need one instance of this object. So we use the singleton
- * pattern and cache the instance in this variable
- *
- * @var object
- */
- static private $_singleton = NULL;
-
- /**
- * mode of operation: live or test
- *
- * @var object
- */
- static protected $_mode = NULL;
-
- /**
- * Constructor
- *
- * @param string $mode the mode of operation: live or test
- *
- * @param $paymentProcessor
- *
- * @return \org_civicrm_payment_googlecheckout
- */
- function __construct($mode, &$paymentProcessor) {
- $this->_mode = $mode;
- $this->_paymentProcessor = $paymentProcessor;
- $this->_processorName = ts('Google Checkout');
- }
-
- /**
- * singleton function used to manage this object
- *
- * @param string $mode the mode of operation: live or test
- *
- * @param object $paymentProcessor
- * @return object
- */
- static
- function &singleton($mode, &$paymentProcessor) {
- $processorName = $paymentProcessor['name'];
- if (self::$_singleton[$processorName] === NULL) {
- self::$_singleton[$processorName] = new org_civicrm_payment_googlecheckout($mode, $paymentProcessor);
- }
- return self::$_singleton[$processorName];
- }
-
- /**
- * This function checks to see if we have the right config values
- *
- * @return string the error message if any
- */
- function checkConfig() {
- $config = CRM_Core_Config::singleton();
-
- $error = array();
-
- if (empty($this->_paymentProcessor['user_name'])) {
- $error[] = ts('User Name is not set in the Administer CiviCRM » Payment Processor.');
- }
-
- if (empty($this->_paymentProcessor['password'])) {
- $error[] = ts('Password is not set in the Administer CiviCRM » Payment Processor.');
- }
-
- if (!empty($error)) {
- return implode('<p>', $error);
- }
- else {
- return NULL;
- }
- }
-
- /**
- * This function collects all the information from a web/api form and invokes
- * the relevant payment processor specific functions to perform the transaction
- *
- * @param array $params assoc array of input parameters for this transaction
- *
- * @return array the result in an nice formatted array (or an error object)
- * @abstract
- */
- function doDirectPayment(&$params) {
- CRM_Core_Error::fatal(ts('This function is not implemented'));
- }
-
- /**
- * Sets appropriate parameters for checking out to google
- *
- * @param array $params name value pair of contribution datat
- *
- * @param $component
- * @throws Exception
- * @return void
- */
- function doTransferCheckout(&$params, $component) {
- $component = strtolower($component);
-
- $url = rtrim($this->_paymentProcessor['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor['user_name'] . '/checkout';
-
- //Create a new shopping cart object
- // Merchant ID
- $merchant_id = $this->_paymentProcessor['user_name'];
- // Merchant Key
- $merchant_key = $this->_paymentProcessor['password'];
- $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
-
- $cart = new GoogleCart($merchant_id, $merchant_key, $server_type);
- $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount'], $params['currencyID']);
- $cart->AddItem($item1);
-
- if ($component == "event") {
- $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}";
- }
- elseif ($component == "contribute") {
- $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}";
-
- $membershipID = CRM_Utils_Array::value('membershipID', $params);
- if ($membershipID) {
- $privateData .= ",membershipID=$membershipID";
- }
-
- $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
- if ($relatedContactID) {
- $privateData .= ",relatedContactID=$relatedContactID";
-
- $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
- if ($onBehalfDupeAlert) {
- $privateData .= ",onBehalfDupeAlert=$onBehalfDupeAlert";
- }
- }
- }
-
- // Allow further manipulation of the arguments via custom hooks ..
- CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $privateData);
-
- $cart->SetMerchantPrivateData($privateData);
-
- if ($component == "event") {
- $returnURL = CRM_Utils_System::url('civicrm/event/register',
- "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
- TRUE, NULL, FALSE
- );
- }
- elseif ($component == "contribute") {
- $returnURL = CRM_Utils_System::url('civicrm/contribute/transact',
- "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
- TRUE, NULL, FALSE
- );
- }
-
- $cart->SetContinueShoppingUrl($returnURL);
-
- $cartVal = base64_encode($cart->GetXML());
- $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML()));
-
- $googleParams = array('cart' => $cartVal,
- 'signature' => $signatureVal,
- );
-
- require_once 'HTTP/Request.php';
- $params = array('method' => HTTP_REQUEST_METHOD_POST,
- 'allowRedirects' => FALSE,
- );
- $request = new HTTP_Request($url, $params);
- foreach ($googleParams as $key => $value) {
- $request->addPostData($key, $value);
- }
-
- $result = $request->sendRequest();
-
- if (PEAR::isError($result)) {
- CRM_Core_Error::fatal($result->getMessage());
- }
-
- if ($request->getResponseCode() != 302) {
- CRM_Core_Error::fatal(ts('Invalid response code received from Google Checkout: %1',
- array(1 => $request->getResponseCode())
- ));
- }
- CRM_Utils_System::redirect($request->getResponseHeader('location'));
-
- exit();
- }
-
- /**
- * hash_call: Function to perform the API call to PayPal using API signature
- * @paymentProcessor is the array of payment processor settings value.
- * @searchParamsnvpStr is the array of search params.
- * returns an associtive array containing the response from the server.
- * @param $paymentProcessor
- * @param $searchParams
- * @return array|object
- * @throws \Exception
- */
- function invokeAPI($paymentProcessor, $searchParams) {
- $merchantID = $paymentProcessor['user_name'];
- $merchantKey = $paymentProcessor['password'];
- $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
-
- $url = "https://{$merchantID}:{$merchantKey}@{$siteURL}/api/checkout/v2/reports/Merchant/{$merchantID}";
- $xml = self::buildXMLQuery($searchParams);
-
- if (!function_exists('curl_init')) {
- CRM_Core_Error::fatal("curl functions NOT available.");
- }
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_VERBOSE, 1);
-
- //turning off the server and peer verification(TrustManager Concept).
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
-
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, 1);
-
- //setting the nvpreq as POST FIELD to curl
- curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
-
- //getting response from server
- $xmlResponse = curl_exec($ch);
-
- // strip slashes if needed
- if (get_magic_quotes_gpc()) {
- $xmlResponse = stripslashes($xmlResponse);
- }
-
- if (curl_errno($ch)) {
- $e = &CRM_Core_Error::singleton();
- $e->push(curl_errno($ch),
- 0, NULL,
- curl_error($ch)
- );
- return $e;
- }
- else {
- curl_close($ch);
- }
-
- return self::getArrayFromXML($xmlResponse);
- }
-
- /**
- * @param $searchParams
- *
- * @return string
- */
- static
- function buildXMLQuery($searchParams) {
- $xml = '<?xml version="1.0" encoding="UTF-8"?>
-<notification-history-request xmlns="http://checkout.google.com/schema/2">';
-
- if (array_key_exists('next-page-token', $searchParams)) {
- $xml .= '
-<next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
- }
- if (array_key_exists('start', $searchParams)) {
- $xml .= '
-<start-time>' . $searchParams['start'] . '</start-time>
-<end-time>' . $searchParams['end'] . '</end-time>';
- }
- if (array_key_exists('notification-types', $searchParams)) {
- $xml .= '
-<notification-types>
-<notification-type>' . implode($searchParams['notification-types'], '</notification-type>
-<notification-type>') . '</notification-type>
-</notification-types>';
- }
- if (array_key_exists('order-numbers', $searchParams)) {
- $xml .= '
-<order-numbers>
-<google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
-<google-order-number>') . '</google-order-number>
-</order-numbers>';
- }
- $xml .= '
-</notification-history-request>';
-
- return $xml;
- }
-
- /**
- * @param $xmlData
- *
- * @return array
- */
- static
- function getArrayFromXML($xmlData) {
- require_once 'Google/library/xml-processing/xmlparser.php';
- $xmlParser = new XmlParser($xmlData);
- $root = $xmlParser->GetRoot();
- $data = $xmlParser->GetData();
-
- return array($root, $data);
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This is the response handler code that will be invoked every time
- * a notification or request is sent by the Google Server
- *
- * To allow this code to receive responses, the url for this file
- * must be set on the seller page under Settings->Integration as the
- * "API Callback URL'
- * Order processing commands can be sent automatically by placing these
- * commands appropriately
- *
- * To use this code for merchant-calculated feedback, this url must be
- * set also as the merchant-calculations-url when the cart is posted
- * Depending on your calculations for shipping, taxes, coupons and gift
- * certificates update parts of the code as required
- *
- */
-
-
-
-require_once 'CRM/Core/Payment/BaseIPN.php';
-
-define('GOOGLE_DEBUG_PP', 1);
-
-/**
- * Class org_civicrm_payment_googlecheckout_GoogleIPN
- */
-class org_civicrm_payment_googlecheckout_GoogleIPN extends CRM_Core_Payment_BaseIPN {
-
- /**
- * We only need one instance of this object. So we use the singleton
- * pattern and cache the instance in this variable
- *
- * @var object
- */
- static private $_singleton = NULL;
-
- /**
- * mode of operation: live or test
- *
- * @var object
- */
- static protected $_mode = NULL;
-
- /**
- * @param $name
- * @param $type
- * @param $object
- * @param bool $abort
- *
- * @return mixed
- */
- static function retrieve($name, $type, $object, $abort = TRUE) {
- $value = CRM_Utils_Array::value($name, $object);
- if ($abort && $value === NULL) {
- CRM_Core_Error::debug_log_message("Could not find an entry for $name");
- echo "Failure: Missing Parameter<p>";
- exit();
- }
-
- if ($value) {
- if (!CRM_Utils_Type::validate($value, $type)) {
- CRM_Core_Error::debug_log_message("Could not find a valid entry for $name");
- echo "Failure: Invalid Parameter<p>";
- exit();
- }
- }
-
- return $value;
- }
-
- /**
- * Constructor
- *
- * @param string $mode the mode of operation: live or test
- *
- * @param $paymentProcessor
- *
- * @return \org_civicrm_payment_googlecheckout_GoogleIPN
- */
- function __construct($mode, &$paymentProcessor) {
- parent::__construct();
-
- $this->_mode = $mode;
- $this->_paymentProcessor = $paymentProcessor;
- }
-
- /**
- * The function gets called when a new order takes place.
- *
- * @param xml $dataRoot response send by google in xml format
- * @param array $privateData contains the name value pair of <merchant-private-data>
- *
- * @param $component
- * @return void
- */
- function newOrderNotify($dataRoot, $privateData, $component) {
- $ids = $input = $params = array();
-
- $input['component'] = strtolower($component);
-
- $ids['contact'] = self::retrieve('contactID', 'Integer', $privateData, TRUE);
- $ids['contribution'] = self::retrieve('contributionID', 'Integer', $privateData, TRUE);
-
- if ($input['component'] == "event") {
- $ids['event'] = self::retrieve('eventID', 'Integer', $privateData, TRUE);
- $ids['participant'] = self::retrieve('participantID', 'Integer', $privateData, TRUE);
- $ids['membership'] = NULL;
- }
- else {
- $ids['membership'] = self::retrieve('membershipID', 'Integer', $privateData, FALSE);
- $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', $privateData, FALSE);
- $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', $privateData, FALSE);
- }
- $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
-
- if (!$this->validateData($input, $ids, $objects)) {
- return FALSE;
- }
-
- // make sure the invoice is valid and matches what we have in the contribution record
- $input['invoice'] = $privateData['invoiceID'];
- $input['newInvoice'] = $dataRoot['google-order-number']['VALUE'];
- $contribution = &$objects['contribution'];
- if ($contribution->invoice_id != $input['invoice']) {
- CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
- echo "Failure: Invoice values dont match between database and IPN request<p>";
- return;
- }
-
- // lets replace invoice-id with google-order-number because thats what is common and unique
- // in subsequent calls or notifications sent by google.
- $contribution->invoice_id = $input['newInvoice'];
-
- $input['amount'] = $dataRoot['order-total']['VALUE'];
-
- if ($contribution->total_amount != $input['amount']) {
- CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
- echo "Failure: Amount values dont match between database and IPN request<p>";
- return;
- }
-
- if (!$this->getInput($input, $ids)) {
- return FALSE;
- }
-
- require_once 'CRM/Core/Transaction.php';
- $transaction = new CRM_Core_Transaction();
-
- // check if contribution is already completed, if so we ignore this ipn
- if ($contribution->contribution_status_id == 1) {
- CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
- echo "Success: Contribution has already been handled<p>";
- }
- else {
- /* Since trxn_id hasn't got any use here,
- * lets make use of it by passing the eventID/membershipTypeID to next level.
- * And change trxn_id to google-order-number before finishing db update */
-
-
- if ($ids['event']) {
- $contribution->trxn_id = $ids['event'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['participant'];
- }
- else {
- $contribution->trxn_id = $ids['membership'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['related_contact'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['onbehalf_dupe_alert'];
- }
- }
-
- $contribution->save();
- $transaction->commit();
- return TRUE;
- }
-
- /**
- * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
- *
- * @param string $status status of the transaction send by google
- * @param $dataRoot
- * @param $component
- * @internal param array $privateData contains the name value pair of <merchant-private-data>
- *
- * @return void
- */
- function orderStateChange($status, $dataRoot, $component) {
- $input = $objects = $ids = array();
-
- $input['component'] = strtolower($component);
-
- $orderNo = $dataRoot['google-order-number']['VALUE'];
-
- require_once 'CRM/Contribute/DAO/Contribution.php';
- $contribution = new CRM_Contribute_DAO_Contribution();
- $contribution->invoice_id = $orderNo;
- if (!$contribution->find(TRUE)) {
- CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: $orderNo");
- echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
- exit();
- }
-
- // Google sends the charged notification twice.
- // So to make sure, code is not executed again.
- if ($contribution->contribution_status_id == 1) {
- CRM_Core_Error::debug_log_message("Contribution already handled (ContributionID = $contribution).");
- exit();
- }
-
- $objects['contribution'] = &$contribution;
- $ids['contribution'] = $contribution->id;
- $ids['contact'] = $contribution->contact_id;
-
- $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
- $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
-
- if ($input['component'] == "event") {
- list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO::VALUE_SEPARATOR,
- $contribution->trxn_id
- );
- }
- else {
- list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO::VALUE_SEPARATOR,
- $contribution->trxn_id
- );
-
- foreach (array('membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) {
- if (!is_numeric($ids[$fld])) {
- unset($ids[$fld]);
- }
- }
- }
-
- $this->loadObjects($input, $ids, $objects);
-
- require_once 'CRM/Core/Transaction.php';
- $transaction = new CRM_Core_Transaction();
-
- if ($status == 'PAYMENT_DECLINED' ||
- $status == 'CANCELLED_BY_GOOGLE' ||
- $status == 'CANCELLED'
- ) {
- return $this->failed($objects, $transaction);
- }
-
- $input['amount'] = $contribution->total_amount;
- $input['fee_amount'] = NULL;
- $input['net_amount'] = NULL;
- $input['trxn_id'] = $orderNo;
- $input['is_test'] = $contribution->is_test;
-
- $this->completeTransaction($input, $ids, $objects, $transaction);
- }
-
- /**
- * singleton function used to manage this object
- *
- * @param string $mode the mode of operation: live or test
- *
- * @param $component
- * @param $paymentProcessor
- * @return object
- */
- static function &singleton($mode, $component, &$paymentProcessor) {
- if (self::$_singleton === NULL) {
- self::$_singleton = new org_civicrm_payment_googlecheckout_GoogleIPN($mode, $paymentProcessor);
- }
- return self::$_singleton;
- }
-
- /**
- * The function retrieves the amount the contribution is for, based on the order-no google sends
- *
- * @param int $orderNo <order-total> send by google
- *
- * @return amount
- */
- function getAmount($orderNo) {
- require_once 'CRM/Contribute/DAO/Contribution.php';
- $contribution = new CRM_Contribute_DAO_Contribution();
- $contribution->invoice_id = $orderNo;
- if (!$contribution->find(TRUE)) {
- CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: $orderNo");
- echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
- exit();
- }
- return $contribution->total_amount;
- }
-
- /**
- * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
- *
- * @param xml $xml_response response send by google in xml format
- * @param array $privateData contains the name value pair of <merchant-private-data>
- * @param int $orderNo <order-total> send by google
- * @param string $root root of xml-response
- *
- * @return array context of this call (test, module, payment processor id)
- */
- static function getContext($xml_response, $privateData, $orderNo, $root) {
- $isTest = NULL;
- $module = NULL;
- if ($root == 'new-order-notification') {
- $contributionID = $privateData['contributionID'];
- $contribution = new CRM_Contribute_DAO_Contribution();
- $contribution->id = $contributionID;
- if (!$contribution->find(TRUE)) {
- CRM_Core_Error::debug_log_message("Could not find contribution record: $contributionID");
- echo "Failure: Could not find contribution record for $contributionID<p>";
- exit();
- }
- if (stristr($contribution->source, ts('Online Contribution'))) {
- $module = 'Contribute';
- }
- elseif (stristr($contribution->source, ts('Online Event Registration'))) {
- $module = 'Event';
- }
- $isTest = $contribution->is_test;
- }
- else {
- $contribution = new CRM_Contribute_DAO_Contribution();
- $contribution->invoice_id = $orderNo;
- if (!$contribution->find(TRUE)) {
- CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: $orderNo");
- echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
- exit();
- }
- if (stristr($contribution->source, ts('Online Contribution'))) {
- $module = 'Contribute';
- }
- elseif (stristr($contribution->source, ts('Online Event Registration'))) {
- $module = 'Event';
- }
- $isTest = $contribution->is_test;
- }
-
- if ($contribution->contribution_status_id == 1) {
- //contribution already handled.
- exit();
- }
-
- if ($module == 'Contribute') {
- if (!$contribution->contribution_page_id) {
- CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: $contributionID");
- echo "Failure: Could not find contribution page for contribution record: $contributionID<p>";
- exit();
- }
-
- // get the payment processor id from contribution page
- $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
- $contribution->contribution_page_id,
- 'payment_processor_id'
- );
- }
- else {
- if ($root == 'new-order-notification') {
- $eventID = $privateData['eventID'];
- }
- else {
- list($eventID, $participantID) = explode(CRM_Core_DAO::VALUE_SEPARATOR,
- $contribution->trxn_id
- );
- }
- if (!$eventID) {
- CRM_Core_Error::debug_log_message("Could not find event ID");
- echo "Failure: Could not find eventID<p>";
- exit();
- }
-
- // we are in event mode
- // make sure event exists and is valid
- require_once 'CRM/Event/DAO/Event.php';
- $event = new CRM_Event_DAO_Event();
- $event->id = $eventID;
- if (!$event->find(TRUE)) {
- CRM_Core_Error::debug_log_message("Could not find event: $eventID");
- echo "Failure: Could not find event: $eventID<p>";
- exit();
- }
-
- // get the payment processor id from contribution page
- $paymentProcessorID = $event->payment_processor_id;
- }
-
- if (!$paymentProcessorID) {
- CRM_Core_Error::debug_log_message("Could not find payment processor for contribution record: $contributionID");
- echo "Failure: Could not find payment processor for contribution record: $contributionID<p>";
- exit();
- }
-
- return array($isTest, $module, $paymentProcessorID);
- }
-
- /**
- * This method is handles the response that will be invoked (from extern/googleNotify) every time
- * a notification or request is sent by the Google Server.
- * @param $xml_response
- */
- static
- function main($xml_response) {
- require_once ('Google/library/googleresponse.php');
- require_once ('Google/library/googlemerchantcalculations.php');
- require_once ('Google/library/googleresult.php');
- require_once ('Google/library/xml-processing/xmlparser.php');
-
- $config = CRM_Core_Config::singleton();
-
- // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
- if (get_magic_quotes_gpc()) {
- $xml_response = stripslashes($xml_response);
- }
-
- require_once 'CRM/Utils/System.php';
- $headers = CRM_Utils_System::getAllHeaders();
-
- if (GOOGLE_DEBUG_PP) {
- CRM_Core_Error::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
- }
-
- // Retrieve the root and data from the xml response
- $xmlParser = new XmlParser($xml_response);
- $root = $xmlParser->GetRoot();
- $data = $xmlParser->GetData();
-
- $orderNo = $data[$root]['google-order-number']['VALUE'];
-
- // lets retrieve the private-data
- $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
- $privateData = $privateData ? self::stringToArray($privateData) : '';
-
- list($mode, $module, $paymentProcessorID) = self::getContext($xml_response, $privateData, $orderNo, $root);
- $mode = $mode ? 'test' : 'live';
-
- require_once 'CRM/Financial/BAO/PaymentProcessor.php';
- $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
- $mode
- );
-
- $ipn = &self::singleton($mode, $module, $paymentProcessor);
-
- // Create new response object
- $merchant_id = $paymentProcessor['user_name'];
- $merchant_key = $paymentProcessor['password'];
- $server_type = ($mode == 'test') ? "sandbox" : '';
-
- $response = new GoogleResponse($merchant_id, $merchant_key,
- $xml_response, $server_type
- );
- if (GOOGLE_DEBUG_PP) {
- CRM_Core_Error::debug_var('RESPONSE-ROOT', $response->root, TRUE, TRUE, 'Google');
- }
-
- //Check status and take appropriate action
- $status = $response->HttpAuthentication($headers);
-
- switch ($root) {
- case "request-received":
- case "error":
- case "diagnosis":
- case "checkout-redirect":
- case "merchant-calculation-callback":
- break;
-
- case "new-order-notification": {
- $response->SendAck();
- $ipn->newOrderNotify($data[$root], $privateData, $module);
- break;
- }
- case "order-state-change-notification": {
- $response->SendAck();
- $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
- $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
-
- switch ($new_financial_state) {
- case 'CHARGEABLE':
- $amount = $ipn->getAmount($orderNo);
- if ($amount) {
- $response->SendChargeOrder($data[$root]['google-order-number']['VALUE'],
- $amount, $message_log
- );
- $response->SendProcessOrder($data[$root]['google-order-number']['VALUE'],
- $message_log
- );
- }
- break;
-
- case 'CHARGED':
- case 'PAYMENT_DECLINED':
- case 'CANCELLED':
- $ipn->orderStateChange($new_financial_state, $data[$root], $module);
- break;
-
- case 'REVIEWING':
- case 'CHARGING':
- case 'CANCELLED_BY_GOOGLE':
- break;
-
- default:
- break;
- }
- }
- case "charge-amount-notification":
- case "chargeback-amount-notification":
- case "refund-amount-notification":
- case "risk-information-notification":
- $response->SendAck();
- break;
-
- default:
- break;
- }
- }
-
- /**
- * @param $input
- * @param $ids
- *
- * @return bool
- */
- function getInput(&$input, &$ids) {
- if (!$this->getBillingID($ids)) {
- return FALSE;
- }
-
- $billingID = $ids['billing'];
- $lookup = array("first_name" => 'contact-name',
- // "last-name" not available with google (every thing in contact-name)
- "last_name" => 'last_name',
- "street_address-{$billingID}" => 'address1',
- "city-{$billingID}" => 'city',
- "state-{$billingID}" => 'region',
- "postal_code-{$billingID}" => 'postal-code',
- "country-{$billingID}" => 'country-code',
- );
-
- foreach ($lookup as $name => $googleName) {
- $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
- $input[$name] = $value ? $value : NULL;
- }
- return TRUE;
- }
-
- /**
- * Converts the comma separated name-value pairs in <merchant-private-data>
- * to an array of name-value pairs.
- * @param $str
- * @return array
- */
- static
- function stringToArray($str) {
- $vars = $labels = array();
- $labels = explode(',', $str);
- foreach ($labels as $label) {
- $terms = explode('=', $label);
- $vars[$terms[0]] = $terms[1];
- }
- return $vars;
- }
- }
-
+++ /dev/null
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-if (defined('PANTHEON_ENVIRONMENT')) {
- ini_set('session.save_handler', 'files');
-}
-session_start();
-
-require_once '../../../civicrm.config.php';
-require_once 'CRM/Core/Config.php';
-
-$config = CRM_Core_Config::singleton();
-
-require_once 'GoogleIPN.php';
-$rawPostData = file_get_contents('php://input');
-org_civicrm_payment_googlecheckout_GoogleIPN::main($rawPostData);
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
- <extension key="org.civicrm.payment.googlecheckout" type="payment">
- <downloadUrl>http://svn.civicrm.org/tools/branches/v3.3/extensions/org.civicrm.payment.googlecheckout.zip</downloadUrl>
- <file>GoogleCheckout</file>
- <name>Google_Checkout</name>
- <description>Google Checkout Payment Processor</description>
- <urls>
- <url desc="Main Extension Page">http://civicrm.org</url>
- <url desc="Documentation">http://wiki.civicrm.org/confluence/display/CRMDOC32/Google+Checkout+Configuration</url>
- <url desc="Support">http://forum.civicrm.org</url>
- <url desc="Licensing">http://civicrm.org/licensing</url>
- </urls>
- <license>AGPL</license>
- <maintainer>
- <author>CiviCRM LLC</author>
- <email>info@civicrm.org</email>
- </maintainer>
- <releaseDate>2010-09-01</releaseDate>
- <version>1.1</version>
- <develStage>stable</develStage>
- <compatibility><ver>3.3</ver></compatibility>
- <comments>For support, please contact project team on the forums.</comments>
- <typeInfo>
- <userNameLabel>Merchant ID</userNameLabel>
- <passwordLabel>Key</passwordLabel>
- <signatureLabel></signatureLabel>
- <subjectLabel></subjectLabel>
- <urlSiteDefault>https://checkout.google.com/</urlSiteDefault>
- <urlApiDefault></urlApiDefault>
- <urlRecurDefault></urlRecurDefault>
- <urlSiteTestDefault>https://sandbox.google.com/checkout/</urlSiteTestDefault>
- <urlApiTestDefault></urlApiTestDefault>
- <urlRecurTestDefault></urlRecurTestDefault>
- <urlButtonDefault><![CDATA[ https://checkout.google.com/buttons/checkout.gif?merchant_id=YOURMERCHANTIDHERE&w=160&h=43&style=white&variant=text&loc=en_US ]]></urlButtonDefault>
- <urlButtonTestDefault><![CDATA[ https://sandbox.google.com/checkout/buttons/checkout.gif?merchant_id=YOURMERCHANTIDHERE&w=160&h=43&style=white&variant=text&loc=en_US ]]></urlButtonTestDefault>
- <billingMode>notify</billingMode>
- <isRecur>0</isRecur>
- <paymentType>1</paymentType>
- </typeInfo>
-</extension>
+++ /dev/null
-Sample PHP code for integration of Google Checkout with the merchant site
---------------------------------------------------------------------------
- File structure and function
- ----------------------------
-
-There are two folders and a log file in the top level directory of
-google-checkout-php-sample.
-
-1. "demo" directory:
-This contains two files cartdemo.php and responsehandlerdemo.php
-
- a)cartdemo.php:
- ---------------
- This file demonstrates the steps required to add items, shipping, taxes and
- merchant-calculations to the cart before it is posted to the Checkout server.
- There are three use case functions defined with different settings for
- shipping and taxes along with different button usages.
-
- b)responsehandler.php:
- ----------------------
- This file will be used to handle the notifications, callbacks and order
- processing steps.
- The path for this file must be specified in the merchant's API callback
- URL in Settings->Integration of the merchant's seller account.
- This file can be used as is and modified by the merchant as per their
- business workflow details.
- Some of the initial steps performed in this file include collecting the
- XML response, request that has been received and get a parsed result in a
- PHP associative array for easy accesibility
- (For details of parse output refer xmlparser.php which has an
- example of how an XML maps to the object).
- Order processing can be done using the SendProcessOrder(..) type of
- methods provided in googleresponse.php. Some sample order processing
- command invocations have been provided as comments in the code
-
-
-2. "library" directory:
-This contains the classes defined to describe the API structure so as to easily
-define and add XML entries by defining objects of these classes.
-
- a) googlecart.php:
- ------------------
- This is the main class which must be instantiated to post a cart.
- It requires a merchant ID and key to be set and there is an option
- to specify which server is to be used for the transactions
- (Sandbox or Production).
- It also has methods to add items, shipping options, tax options and
- merchant-calculation details.
-
- b) googleitem.php:
- ------------------
- This class is instantiated for every item to be added to the cart.
- It requires the item name, description, price and quantity to be specified.
-
- c) googleshipping.php:
- ----------------------
- This class is instantiated for every shipping option that is to be added to the cart.
- It requires the shipping name type an price to be specified.
- Other methods allow specification of the shipping restrictions.
-
- d) googletaxrule.php:
- ---------------------
- This class is used to define all tax rules for the tax tables. These may be
- rules for default or alternate tax tables. Methods have been provided to add
- states and zip patterns for the tax rules.
-
- e) googletaxtable.php:
- ----------------------
- This class is used to aggregate all the defined tax rules to define a tax table.
- This may be a default or alternate tax table identified by the "type" value.
-
- f) googleresponse.php:
- ----------------------
- An instance of this class is created in the responsehandlerdemo.php.
- This again requires the merchant id and merchant key to be specified.
- There are methods provided to send all the different order processing
- commands.
- All notifications are parsed and the merchant can take required action
- when a particular notification is received.
-
- g) googleresult.php:
- --------------------
- This class is used for merchant-calculations and is invoked for
- each result in the merchant-calculations-result sent from the
- merchant in response to a callback.
-
- h) googlemerchantcalculations.php:
- ----------------------------------
- In order to process merchant calculations, an instance of this
- class is created. It is used to aggregate merchant results and
- respond with the XML response for the callback.
-
- f) "xml-processing" directory:
- ------------------------------
-
- i) xmlbuilder.php:
- -----------------
- This class generates XML and consists of "push" and "pop"
- methods to add open and close tags respectively.
- This is used internally by the library classes to generate
- XML file for posting carts.
-
- ii)xmlparser.php:
- -----------------
- This class parses XML documents using the SAX parser and is
- compatible with PHP v4 and 5. It converts them to DOM form
- returning the XML data in a PHP associative array.
- This is used internally by the library classes to parse
- XML requests and responses that are received from the
- Checkout server.
-
-3. googlemessage.log:
-The log file records all the notification and order processing commands that are
-sent and received and can be useful information for debugging purposes.
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//Point to the correct directory
-chdir("..");
-//Include all the required files
-require_once ('library/googlecart.php');
-require_once ('library/googleitem.php');
-require_once ('library/googleshipping.php');
-require_once ('library/googletaxrule.php');
-require_once ('library/googletaxtable.php');
-
-//Invoke any of the provided use cases
-
-UseCase1();
-//UseCase2();
-//UseCase3();
-function UseCase1() {
- //Create a new shopping cart object
- // Your Merchant ID
- $merchant_id = "";
- // Your Merchant Key
- $merchant_key = "";
- $server_type = "sandbox";
- $cart = new GoogleCart($merchant_id, $merchant_key, $server_type);
-
- //Add items to the cart
- $item1 = new GoogleItem("MegaSound 2GB MP3 Player",
- "Portable MP3 player - stores 500 songs", 1, 178
- );
- $item2 = new GoogleItem("AA Rechargeable Battery Pack",
- "Battery pack containing four AA rechargeable batteries", 1, 12
- );
- $cart->AddItem($item1);
- $cart->AddItem($item2);
-
- //Add shipping options
- $ship = new GoogleShipping("Ground", "flat-rate", 5);
- $ship->SetAllowedCountryArea("CONTINENTAL_48");
- $cart->AddShipping($ship);
-
- $ship = new GoogleShipping("2nd Day", "flat-rate", 10);
- $ship->SetAllowedCountryArea("FULL_50_STATES");
- $cart->AddShipping($ship);
-
- //Add tax options
- $tax_rule = new GoogleTaxRule("default", 0.08);
- $tax_rule->SetStateAreas("CA");
- $tax_table = new GoogleTaxTable("default");
- $tax_table->AddTaxRules($tax_rule);
- $cart->AddTaxTables($tax_table);
-
- //Display Google Checkout button
- echo $cart->CheckoutButtonCode("large");
-}
-
-function UseCase2() {
- //Create a new shopping cart object
- // Your Merchant ID
- $merchant_id = "";
- // Your Merchant Key
- $merchant_key = "";
- $server_type = "sandbox";
- $cart = new GoogleCart($merchant_id, $merchant_key, $server_type);
-
- //Add items to the cart
- $item1 = new GoogleItem("Dry Food Pack AA1453",
- " pack of highly nutritious dried food for emergency", 1, 35
- );
- $item2 = new GoogleItem("MegaSound 2GB MP3 Player",
- "Portable MP3 player - stores 500 songs", 1, 178
- );
- $item3 = new GoogleItem("AA Rechargeable Battery Pack",
- "Battery pack containing four AA rechargeable batteries", 1, 12
- );
- $cart->AddItem($item1);
- $cart->AddItem($item2);
- $cart->AddItem($item3);
-
- //Add shipping options
- $ship = new GoogleShipping("flat", "flat-rate", 5);
- $ship->SetAllowedStateAreas(array("NY", "CA"));
- $cart->AddShipping($ship);
-
- $ship = new GoogleShipping("pickup", "pickup", 10);
- $cart->AddShipping($ship);
-
- //Add tax options
- $tax_rule = new GoogleTaxRule("default", 0.02, "FULL_50_STATES");
- $tax_rule->SetStateAreas(array("CA", "NY"));
- $tax_table = new GoogleTaxTable("default");
- $tax_table->AddTaxRules($tax_rule);
- $cart->AddTaxTables($tax_table);
-
- $tax_rule = new GoogleTaxRule("alternate", 0.05);
- $tax_rule->SetZipPatterns(array("54305", "10027"));
- $tax_rule->SetStateAreas("CA");
- $tax_table = new GoogleTaxTable("alternate", "test");
- $tax_table->AddTaxRules($tax_rule);
-
- $tax_rule = new GoogleTaxRule("alternate", 0.1);
- $tax_rule->SetStateAreas(array("CO", "FL"));
- $tax_table->AddTaxRules($tax_rule);
-
- $cart->AddTaxTables($tax_table);
-
- //Display XML data
- echo htmlentities($cart->GetXML());
-
- //Display a medium button with a transparent background
- echo $cart->CheckoutButtonCode("medium", "trans");
-}
-
-function UseCase3() {
- //Create a new shopping cart object
- // Your Merchant ID
- $merchant_id = "";
- // Your Merchant Key
- $merchant_key = "";
- $server_type = "sandbox";
- $cart = new GoogleCart($merchant_id, $merchant_key, $server_type);
-
- //Add items to the cart
- $item1 = new GoogleItem("Dry Food Pack AA1453",
- " pack of highly nutritious dried food for emergency", 1, 35
- );
- $item2 = new GoogleItem("MegaSound 2GB MP3 Player",
- "Portable MP3 player - stores 500 songs", 1, 178
- );
- $item3 = new GoogleItem("AA Rechargeable Battery Pack",
- "Battery pack containing four AA rechargeable batteries", 1, 12
- );
- $cart->AddItem($item1);
- $cart->AddItem($item2);
- $cart->AddItem($item3);
-
- //Set request buyer phone
- $cart->SetRequestBuyerPhone("true");
-
- //Add merchant calculations options
- $cart->SetMerchantCalculations(
- "https://www.example.com/shopping/merchantCalc", "true", "true", "true"
- );
- $ship = new GoogleShipping("merchant-calc",
- "merchant-calculated", 5, "USD", "ALL"
- );
- $ship->SetAllowedStateAreas(array("NY", "CA"));
- $cart->AddShipping($ship);
-
- $tax_rule = new GoogleTaxRule("default", 0.2);
- $tax_rule->SetStateAreas(array("CA", "NY"));
-
- $tax_table = new GoogleTaxTable("default");
- $tax_table->AddTaxRules($tax_rule);
- $cart->AddTaxTables($tax_table);
-
- //Display XML data
- echo htmlentities($cart->GetXML());
-
- //Display a disabled, small button with a white background
- echo $cart->CheckoutButtonCode("small", "white", "disabled");
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This is the response handler code that will be invoked every time
- * a notification or request is sent by the Google Server
- *
- * To allow this code to receive responses, the url for this file
- * must be set on the seller page under Settings->Integration as the
- * "API Callback URL'
- * Order processing commands can be sent automatically by placing these
- * commands appropriately
- *
- * To use this code for merchant-calculated feedback, this url must be
- * set also as the merchant-calculations-url when the cart is posted
- * Depending on your calculations for shipping, taxes, coupons and gift
- * certificates update parts of the code as required
- *
- */
-
-
-
-chdir("..");
-require_once ('library/googleresponse.php');
-require_once ('library/googlemerchantcalculations.php');
-require_once ('library/googleresult.php');
-
-define('RESPONSE_HANDLER_LOG_FILE', 'googlemessage.log');
-
-//Setup the log file
-if (!$message_log = fopen(RESPONSE_HANDLER_LOG_FILE, "a")) {
- error_func("Cannot open " . RESPONSE_HANDLER_LOG_FILE . " file.\n", 0);
- exit(1);
-}
-
-// Retrieve the XML sent in the HTTP POST request to the ResponseHandler
-$xml_response = $HTTP_RAW_POST_DATA;
-if (get_magic_quotes_gpc()) {
- $xml_response = stripslashes($xml_response);
-}
-$headers = getallheaders();
-fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
- $xml_response
- ));
-
-// Create new response object
-// Your Merchant ID
-$merchant_id = "";
-// Your Merchant Key
-$merchant_key = "";
-$server_type = "sandbox";
-
-$response = new GoogleResponse($merchant_id, $merchant_key,
- $xml_response, $server_type
-);
-$root = $response->root;
-$data = $response->data;
-fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
- $response->root
- ));
-
-//Use the following two lines to log the associative array storing the XML data
-//$result = print_r($data,true);
-//fwrite($message_log, sprintf("\n\r%s:- %s\n",date("D M j G:i:s T Y"),$result));
-
-//Check status and take appropriate action
-$status = $response->HttpAuthentication($headers);
-
-/* Commands to send the various order processing APIs
- * Send charge order : $response->SendChargeOrder($data[$root]
- * ['google-order-number']['VALUE'], <amount>, $message_log);
- * Send process order : $response->SendProcessOrder($data[$root]
- * ['google-order-number']['VALUE'], $message_log);
- * Send deliver order: $response->SendDeliverOrder($data[$root]
- * ['google-order-number']['VALUE'], <carrier>, <tracking-number>,
- * <send_mail>, $message_log);
- * Send archive order: $response->SendArchiveOrder($data[$root]
- * ['google-order-number']['VALUE'], $message_log);
- *
- */
-
-
-
-switch ($root) {
- case "request-received": {
- break;
- }
- case "error": {
- break;
- }
- case "diagnosis": {
- break;
- }
- case "checkout-redirect": {
- break;
- }
- case "merchant-calculation-callback": {
- // Create the results and send it
- $merchant_calc = new GoogleMerchantCalculations();
-
- // Loop through the list of address ids from the callback
- $addresses = get_arr_result($data[$root]['calculate']['addresses']['anonymous-address']);
- foreach ($addresses as $curr_address) {
- $curr_id = $curr_address['id'];
- $country = $curr_address['country-code']['VALUE'];
- $city = $curr_address['city']['VALUE'];
- $region = $curr_address['region']['VALUE'];
- $postal_code = $curr_address['region']['VALUE'];
-
- // Loop through each shipping method if merchant-calculated shipping
- // support is to be provided
- if (isset($data[$root]['calculate']['shipping'])) {
- $shipping = get_arr_result($data[$root]['calculate']['shipping']['method']);
- foreach ($shipping as $curr_ship) {
- $name = $curr_ship['name'];
- //Compute the price for this shipping method and address id
- // Modify this to get the actual price
- $price = 10;
- // Modify this as required
- $shippable = "true";
- $merchant_result = new GoogleResult($curr_id);
- $merchant_result->SetShippingDetails($name, $price, "USD",
- $shippable
- );
-
- if ($data[$root]['calculate']['tax']['VALUE'] == "true") {
- //Compute tax for this address id and shipping type
- // Modify this to the actual tax value
- $amount = 15;
- $merchant_result->SetTaxDetails($amount, "USD");
- }
-
- $codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
- ['merchant-code-string']
- );
- foreach ($codes as $curr_code) {
- //Update this data as required to set whether the coupon is valid, the code and the amount
- $coupons = new GoogleCoupons("true", $curr_code['code'], 5, "USD", "test2");
- $merchant_result->AddCoupons($coupons);
- }
- $merchant_calc->AddResult($merchant_result);
- }
- }
- else {
- $merchant_result = new GoogleResult($curr_id);
- if ($data[$root]['calculate']['tax']['VALUE'] == "true") {
- //Compute tax for this address id and shipping type
- // Modify this to the actual tax value
- $amount = 15;
- $merchant_result->SetTaxDetails($amount, "USD");
- }
- $codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
- ['merchant-code-string']
- );
- foreach ($codes as $curr_code) {
- //Update this data as required to set whether the coupon is valid, the code and the amount
- $coupons = new GoogleCoupons("true", $curr_code['code'], 5, "USD", "test2");
- $merchant_result->AddCoupons($coupons);
- }
- $merchant_calc->AddResult($merchant_result);
- }
- }
- fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
- $merchant_calc->GetXML()
- ));
- $response->ProcessMerchantCalculations($merchant_calc);
- break;
- }
- case "new-order-notification": {
- $response->SendAck();
- break;
- }
- case "order-state-change-notification": {
- $response->SendAck();
- $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
- $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
-
- switch ($new_financial_state) {
- case 'REVIEWING': {
- break;
- }
- case 'CHARGEABLE': {
- //$response->SendProcessOrder($data[$root]['google-order-number']['VALUE'],
- // $message_log);
- //$response->SendChargeOrder($data[$root]['google-order-number']['VALUE'],
- // '', $message_log);
- break;
- }
- case 'CHARGING': {
- break;
- }
- case 'CHARGED': {
- break;
- }
- case 'PAYMENT_DECLINED': {
- break;
- }
- case 'CANCELLED': {
- break;
- }
- case 'CANCELLED_BY_GOOGLE': {
- //$response->SendBuyerMessage($data[$root]['google-order-number']['VALUE'],
- // "Sorry, your order is cancelled by Google", true, $message_log);
- break;
- }
- default:
- break;
- }
-
- switch ($new_fulfillment_order) {
- case 'NEW': {
- break;
- }
- case 'PROCESSING': {
- break;
- }
- case 'DELIVERED': {
- break;
- }
- case 'WILL_NOT_DELIVER': {
- break;
- }
- default:
- break;
- }
- }
- case "charge-amount-notification": {
- $response->SendAck();
- //$response->SendDeliverOrder($data[$root]['google-order-number']['VALUE'],
- // <carrier>, <tracking-number>, <send-email>, $message_log);
- //$response->SendArchiveOrder($data[$root]['google-order-number']['VALUE'],
- // $message_log);
- break;
- }
- case "chargeback-amount-notification": {
- $response->SendAck();
- break;
- }
- case "refund-amount-notification": {
- $response->SendAck();
- break;
- }
- case "risk-information-notification": {
- $response->SendAck();
- break;
- }
- default: {
- break;
- }
- }
- /* In case the XML API contains multiple open tags
- with the same value, then invoke this function and
- perform a foreach on the resultant array.
- This takes care of cases when there is only one unique tag
- or multiple tags.
- Examples of this are "anonymous-address", "merchant-code-string"
- from the merchant-calculations-callback API
- */
-/**
- * @param $child_node
- *
- * @return array
- */function get_arr_result($child_node) {
- $result = array();
- if (isset($child_node)) {
- if (is_associative_array($child_node)) {
- $result[] = $child_node;
- }
- else {
- foreach ($child_node as $curr_node) {
- $result[] = $curr_node;
- }
- }
- }
- return $result;
- }
-
- /* Returns true if a given variable represents an associative array */
-/**
- * @param $var
- *
- * @return bool
- */function is_associative_array($var) {
- return is_array($var) && !is_numeric(implode('', array_keys($var)));
- }
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This class is used to create a Google Checkout shopping cart and post it
- * to the Sandbox or Production environment
- * A very useful function is the CheckoutButtonCode() which returns the HTML
- * code to post the cart using the standard technique
- * Refer demo/cartdemo.php for different use case scenarios for this code
- */
-class GoogleCart {
- var $merchant_id;
- var $merchant_key;
- var $server_url;
- var $schema_url;
- var $base_url;
- var $checkout_url;
- var $checkout_diagnose_url;
- var $request_url;
- var $request_diagnose_url;
-
- var $cart_expiration = "";
- var $merchant_private_data = "";
- var $edit_cart_url = "";
- var $continue_shopping_url = "";
- var $request_buyer_phone = "";
- var $merchant_calculated = "";
- var $merchant_calculations_url = "";
- var $accept_merchant_coupons = "";
- var $accept_gift_certificates = "";
- var $default_tax_table;
-
- var $item_arr;
- var $shipping_arr;
- var $alternate_tax_table_arr;
- var $xml_data;
-
- //The Constructor method which requires a merchant id, merchant key
- //and the operation type(sandbox or checkout)
- /**
- * @param $id
- * @param $key
- * @param string $server_type
- */
- function GoogleCart($id, $key, $server_type = "checkout") {
- $this->merchant_id = $id;
- $this->merchant_key = $key;
-
- if (strtolower($server_type) == "sandbox") {
-
- $this->server_url = "https://sandbox.google.com/checkout/";
- }
- else $this->server_url = "https://checkout.google.com/";
-
- $this->schema_url = "http://checkout.google.com/schema/2";
- $this->base_url = $this->server_url . "cws/v2/Merchant/" . $this->merchant_id;
- $this->checkout_url = $this->base_url . "/checkout";
- $this->checkout_diagnose_url = $this->base_url . "/checkout/diagnose";
- $this->request_url = $this->base_url . "/request";
- $this->request_diagnose_url = $this->base_url . "/request/diagnose";
-
- //The item, shipping and tax table arrays are initialized
- $this->item_arr = array();
- $this->shipping_arr = array();
- $this->alternate_tax_table_arr = array();
- }
-
- /**
- * @param $cart_expire
- */
- function SetCartExpiration($cart_expire) {
- $this->cart_expiration = $cart_expire;
- }
-
- /**
- * @param $data
- */
- function SetMerchantPrivateData($data) {
- $this->merchant_private_data = $data;
- }
-
- /**
- * @param $url
- */
- function SetEditCartUrl($url) {
- $this->edit_cart_url = $url;
- }
-
- /**
- * @param $url
- */
- function SetContinueShoppingUrl($url) {
- $this->continue_shopping_url = $url;
- }
-
- /**
- * @param $req
- */
- function SetRequestBuyerPhone($req) {
- $this->_SetBooleanValue('request_buyer_phone', $req, "");
- }
-
- /**
- * @param $url
- * @param string $tax_option
- * @param string $coupons
- * @param string $gift_cert
- */
- function SetMerchantCalculations($url, $tax_option = "false",
- $coupons = "false",
- $gift_cert = "false"
- ) {
- $this->merchant_calculations_url = $url;
- $this->_SetBooleanValue('merchant_calculated', $tax_option, "false");
- $this->_SetBooleanValue('accept_merchant_coupons', $coupons, "false");
- $this->_SetBooleanValue('accept_gift_certificates', $gift_cert, "false");
- }
-
- /**
- * @param $google_item
- */
- function AddItem($google_item) {
- $this->item_arr[] = $google_item;
- }
-
- /**
- * @param $ship
- */
- function AddShipping($ship) {
- $this->shipping_arr[] = $ship;
- }
-
- /**
- * @param $tax
- */
- function AddTaxTables($tax) {
- if ($tax->type == "default") {
- $this->default_tax_table = $tax;
- }
- elseif ($tax->type == "alternate") {
- $this->alternate_tax_table_arr[] = $tax;
- }
- }
-
- /**
- * @return string
- */
- function GetXML() {
- require_once ('xml-processing/xmlbuilder.php');
-
- $xml_data = new XmlBuilder();
-
- $xml_data->Push('checkout-shopping-cart',
- array('xmlns' => $this->schema_url)
- );
- $xml_data->Push('shopping-cart');
-
- //Add cart expiration if set
- if ($this->cart_expiration != "") {
- $xml_data->Push('cart-expiration');
- $xml_data->Element('good-until-date', $this->cart_expiration);
- $xml_data->Pop('cart-expiration');
- }
-
- //Add XML data for each of the items
- $xml_data->Push('items');
- foreach ($this->item_arr as $item) {
- $xml_data->Push('item');
- $xml_data->Element('item-name', $item->item_name);
- $xml_data->Element('item-description', $item->item_description);
- $xml_data->Element('unit-price', $item->unit_price,
- array('currency' => $item->currency)
- );
- $xml_data->Element('quantity', $item->quantity);
- if ($item->merchant_private_data != '') $xml_data->Element('merchant-private-date',
- $item->merchant_private_data
- );
- if ($item->tax_table_selector != '') {
- $xml_data->Element('tax-table-selector', $item->tax_table_selector);
- }
- $xml_data->Pop('item');
- }
- $xml_data->Pop('items');
-
- if ($this->merchant_private_data != '') $xml_data->Element('merchant-private-data',
- $this->merchant_private_data
- );
-
- $xml_data->Pop('shopping-cart');
-
- $xml_data->Push('checkout-flow-support');
- $xml_data->Push('merchant-checkout-flow-support');
- if ($this->edit_cart_url != '') {
- $xml_data->Element('edit-cart-url', $this->edit_cart_url);
- }
- if ($this->continue_shopping_url != '') $xml_data->Element('continue-shopping-url',
- $this->continue_shopping_url
- );
-
- if (count($this->shipping_arr) > 0) {
-
- $xml_data->Push('shipping-methods');
- }
-
- //Add the shipping methods
- foreach ($this->shipping_arr as $ship) {
- //Pickup shipping handled in else part
- if ($ship->type == "flat-rate" ||
- $ship->type == "merchant-calculated"
- ) {
- $xml_data->Push($ship->type . '-shipping',
- array('name' => $ship->name)
- );
- $xml_data->Element('price', $ship->price,
- array('currency' => $ship->currency)
- );
-
- //Check if shipping restrictions have been specifd=ied
- if ($ship->allowed_restrictions ||
- $ship->excluded_restrictions
- ) {
- $xml_data->Push('shipping-restrictions');
-
- //Check if allowed restrictions specified
- if ($ship->allowed_restrictions) {
- $xml_data->Push('allowed-areas');
- if ($ship->allowed_country_area != "") $xml_data->Element('us-country-area', '',
- array('country-area' =>
- $ship->allowed_country_area,
- )
- );
- foreach ($ship->allowed_state_areas_arr as $current) {
- $xml_data->Push('us-state-area');
- $xml_data->Element('state', $current);
- $xml_data->Pop('us-state-area');
- }
- foreach ($ship->allowed_zip_patterns_arr as $current) {
- $xml_data->Push('us-zip-area');
- $xml_data->Element('zip-pattern', $current);
- $xml_data->Pop('us-zip-area');
- }
- $xml_data->Pop('allowed-areas');
- }
-
- if ($ship->excluded_restrictions) {
- $xml_data->Push('allowed-areas');
- $xml_data->Pop('allowed-areas');
- $xml_data->Push('excluded-areas');
- if ($ship->excluded_country_area != "") $xml_data->Element('us-country-area', '',
- array('country-area' =>
- $ship->excluded_country_area,
- )
- );
- foreach ($ship->excluded_state_areas_arr as $current) {
- $xml_data->Push('us-state-area');
- $xml_data->Element('state', $current);
- $xml_data->Pop('us-state-area');
- }
- foreach ($ship->excluded_zip_patterns_arr as $current) {
- $xml_data->Push('us-zip-area');
- $xml_data->Element('zip-pattern', $current);
- $xml_data->Pop('us-zip-area');
- }
- $xml_data->Pop('excluded-areas');
- }
- $xml_data->Pop('shipping-restrictions');
- }
- $xml_data->Pop($ship->type . '-shipping');
- }
- elseif ($ship->type == "pickup") {
- $xml_data->Push('pickup', array('name' => $ship->name));
- $xml_data->Element('price', $ship->price,
- array('currency' => $ship->currency)
- );
- $xml_data->Pop('pickup');
- }
- }
- if (count($this->shipping_arr) > 0) {
- $xml_data->Pop('shipping-methods');
- }
-
- if ($this->request_buyer_phone != "") $xml_data->Element('request-buyer-phone-number',
- $this->request_buyer_phone
- );
-
- if ($this->merchant_calculations_url != "") {
- $xml_data->Push('merchant-calculations');
- $xml_data->Element('merchant-calculations-url',
- $this->merchant_calculations_url
- );
- if ($this->accept_merchant_coupons != "") $xml_data->Element('accept-merchant-coupons',
- $this->accept_merchant_coupons
- );
- if ($this->accept_gift_certificates != "") $xml_data->Element('accept-gift-certificates',
- $this->accept_gift_certificates
- );
- $xml_data->Pop('merchant-calculations');
- }
-
- //Set Default and Alternate tax tables
- if ((count($this->alternate_tax_table_arr) != 0) || (isset($this->default_tax_table))) {
- if ($this->merchant_calculated != "") {
- $xml_data->Push('tax-tables', array('merchant-calculated' => $this->merchant_calculated));
- }
- else $xml_data->Push('tax-tables');
-
- if (isset($this->default_tax_table)) {
- $curr_table = $this->default_tax_table;
- foreach ($curr_table->tax_rules_arr as $curr_rule) {
-
-
- $xml_data->Push('default-tax-table');
- $xml_data->Push('tax-rules');
- foreach ($curr_rule->state_areas_arr as $current) {
- $xml_data->Push('default-tax-rule');
-
- $xml_data->Element('shipping-taxed', $curr_rule->shipping_taxed);
- $xml_data->Element('rate', $curr_rule->tax_rate);
- $xml_data->Push('tax-area');
- if ($curr_rule->country_area != "") {
- $xml_data->Element('us-country-area', '', array('country-area' => $curr_rule->country_area));
- }
- $xml_data->Push('us-state-area');
- $xml_data->Element('state', $current);
- $xml_data->Pop('us-state-area');
-
- $xml_data->Pop('tax-area');
- $xml_data->Pop('default-tax-rule');
- }
- foreach ($curr_rule->zip_patterns_arr as $current) {
- $xml_data->Push('default-tax-rule');
-
- $xml_data->Element('shipping-taxed', $curr_rule->shipping_taxed);
- $xml_data->Element('rate', $curr_rule->tax_rate);
- $xml_data->Push('tax-area');
-
- if ($curr_rule->country_area != "") {
-
- $xml_data->Element('us-country-area', '', array('country-area' => $curr_rule->country_area));
- }
- $xml_data->Push('us-zip-area');
- $xml_data->Element('zip-pattern', $current);
- $xml_data->Pop('us-zip-area');
- $xml_data->Pop('tax-area');
- $xml_data->Pop('default-tax-rule');
- }
- $xml_data->Pop('tax-rules');
- $xml_data->Pop('default-tax-table');
- }
- }
-
- if (count($this->alternate_tax_table_arr) != 0) {
- $xml_data->Push('alternate-tax-tables');
- foreach ($this->alternate_tax_table_arr as $curr_table) {
- foreach ($curr_table->tax_rules_arr as $curr_rule) {
- $xml_data->Push('alternate-tax-table', array('standalone' => $curr_table->standalone, 'name' => $curr_table->name));
- $xml_data->Push('alternate-tax-rules');
- foreach ($curr_rule->state_areas_arr as $current) {
- $xml_data->Push('alternate-tax-rule');
-
- $xml_data->Element('shipping-taxed', $curr_rule->shipping_taxed);
- $xml_data->Element('rate', $curr_rule->tax_rate);
- $xml_data->Push('tax-area');
- if ($curr_rule->country_area != "") {
- $xml_data->Element('us-country-area', '', array('country-area' => $curr_rule->country_area));
- }
- $xml_data->Push('us-state-area');
- $xml_data->Element('state', $current);
- $xml_data->Pop('us-state-area');
-
- $xml_data->Pop('tax-area');
- $xml_data->Pop('alternate-tax-rule');
- }
- foreach ($curr_rule->zip_patterns_arr as $current) {
- $xml_data->Push('alternate-tax-rule');
-
- $xml_data->Element('shipping-taxed', $curr_rule->shipping_taxed);
- $xml_data->Element('rate', $curr_rule->tax_rate);
- $xml_data->Push('tax-area');
-
- if ($curr_rule->country_area != "") {
-
- $xml_data->Element('us-country-area', '', array('country-area' => $curr_rule->country_area));
- }
- $xml_data->Push('us-zip-area');
- $xml_data->Element('zip-pattern', $current);
- $xml_data->Pop('us-zip-area');
- $xml_data->Pop('tax-area');
- $xml_data->Pop('alternate-tax-rule');
- }
- $xml_data->Pop('alternate-tax-rules');
- $xml_data->Pop('alternate-tax-table');
- }
- }
- $xml_data->Pop('alternate-tax-tables');
- }
- $xml_data->Pop('tax-tables');
- }
- $xml_data->Pop('merchant-checkout-flow-support');
- $xml_data->Pop('checkout-flow-support');
- $xml_data->Pop('checkout-shopping-cart');
-
- return $xml_data->GetXML();
- }
-
- //Code for generating Checkout button
- /**
- * @param string $size
- * @param string $style
- * @param string $variant
- * @param string $loc
- *
- * @return string
- */
- function CheckoutButtonCode($size = "large", $style = "white",
- $variant = "text", $loc = "en_US"
- ) {
-
- switch ($size) {
- case "large":
- $width = "180";
- $height = "46";
- break;
-
- case "medium":
- $width = "168";
- $height = "44";
- break;
-
- case "small":
- $width = "160";
- $height = "43";
- break;
-
- default:
- break;
- }
-
- if ($variant == "text") {
- $data = "<p><form method=\"POST\" action=\"" . $this->checkout_url . "\">
- <input type=\"hidden\" name=\"cart\" value=\"" . base64_encode($this->GetXML()) . "\">
- <input type=\"hidden\" name=\"signature\" value=\"" . base64_encode($this->CalcHmacSha1($this->GetXML())) . "\">
- <input type=\"image\" name=\"Checkout\" alt=\"Checkout\"
- src=\"" . $this->server_url . "buttons/checkout.gif?merchant_id=" . $this->merchant_id . "&w=" . $width . "&h=" . $height . "&style=" . $style . "&variant=" . $variant . "&loc=" . $loc . "\"
- height=\"" . $height . "\" width=\"" . $width . "\" />
- </form></p>";
- }
- elseif ($variant == "disabled") {
- $data = "<p><img alt=\"Checkout\"
- src=\"" . $this->server_url . "buttons/checkout.gif?merchant_id=" . $this->merchant_id . "&w=" . $width . "&h=" . $height . "&style=" . $style . "&variant=" . $variant . "&loc=" . $loc . "\"
- height=\"" . $height . "\" width=\"" . $width . "\" /></p>";
- }
- return $data;
- }
-
- //Method which returns the encrypted google cart to make sure that the carts are not tampered with
- /**
- * @param $data
- *
- * @return string
- */
- function CalcHmacSha1($data) {
- $key = $this->merchant_key;
- $blocksize = 64;
- $hashfunc = 'sha1';
- if (strlen($key) > $blocksize) {
- $key = pack('H*', $hashfunc($key));
- }
- $key = str_pad($key, $blocksize, chr(0x00));
- $ipad = str_repeat(chr(0x36), $blocksize);
- $opad = str_repeat(chr(0x5c), $blocksize);
- $hmac = pack(
- 'H*', $hashfunc(
- ($key ^ $opad) . pack(
- 'H*', $hashfunc(
- ($key ^ $ipad) . $data
- )
- )
- )
- );
- return $hmac;
- }
-
- //Method used internally to set true/false cart variables
- /**
- * @param $string
- * @param $value
- * @param $default
- */
- function _SetBooleanValue($string, $value, $default) {
- $value = strtolower($value);
- if ($value == "true" || $value == "false")eval('$this->' . $string . '="' . $value . '";');
- else eval('$this->' . $string . '="' . $default . '";');
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This class is used to create items to be added to the shopping cart
- * Invoke a separate instance of this class for each item to be
- * added to the cart.
- * Required fields are the item name, description, quantity and price
- * The private-data and tax-selector for each item can be set in the
- * constructor call or using individual Set functions
- */
-class GoogleItem {
-
- var $item_name;
- var $item_description;
- var $unit_price;
- var $currency;
- var $quantity;
- var $merchant_private_data;
- var $tax_table_selector;
-
- /**
- * @param $name
- * @param $desc
- * @param $qty
- * @param $price
- * @param string $money
- * @param string $private_data
- * @param string $tax_selector
- */
- function GoogleItem($name, $desc, $qty, $price, $money = "USD",
- $private_data = "", $tax_selector = ""
- ) {
- $this->item_name = $name;
- $this->item_description = $desc;
- $this->unit_price = $price;
- $this->quantity = $qty;
- $this->currency = $money;
- $this->merchant_private_data = $private_data;
- $this->tax_table_selector = $tax_selector;
- }
-
- /**
- * @param $private_data
- */
- function SetMerchantPrivateData($private_data) {
- $this->merchant_private_data = $private_data;
- }
-
- /**
- * @param $tax_selector
- */
- function SetTaxTableSelector($tax_selector) {
- $this->tax_table_selector = $tax_selector;
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This class is used to create the merchant callback results
- * when a merchant-calculated-feedback structure is received
- *
- * Multiple results are generated depending on the possible
- * combinations for shipping options and address ids
- *
- * Refer demo/responsehandler.php for generating these results
- */
-class GoogleMerchantCalculations {
- var $results_arr;
- var $schema_url = "http://checkout.google.com/schema/2";
- function GoogleMerchantCalculations() {
- $this->results_arr = array();
- }
-
- /**
- * @param $results
- */
- function AddResult($results) {
- $this->results_arr[] = $results;
- }
-
- /**
- * @return string
- */
- function GetXML() {
- require_once ('xml-processing/xmlbuilder.php');
-
- $xml_data = new XmlBuilder();
- $xml_data->Push('merchant-calculation-results',
- array('xmlns' => $this->schema_url)
- );
- $xml_data->Push('results');
-
- foreach ($this->results_arr as $result) {
- if ($result->shipping_name != "") {
- $xml_data->Push('result', array('shipping-name' =>
- $result->shipping_name, 'address-id' => $result->address_id,
- ));
- $xml_data->Element('shipping-rate', $result->ship_price,
- array('currency' => $result->ship_currency)
- );
- $xml_data->Element('shippable', $result->shippable);
- }
- else $xml_data->Push('result', array('address-id' => $result->address_id));
-
- if ($result->tax_amount != "") $xml_data->Element('total-tax', $result->tax_amount,
- array('currency' => $result->tax_currency)
- );
-
- if ((count($result->coupon_arr) != 0) ||
- (count($result->giftcert_arr) != 0)
- ) {
- $xml_data->Push('merchant-code-results');
-
- foreach ($result->coupon_arr as $curr_coupon) {
- $xml_data->Push('coupon-result');
- $xml_data->Element('valid', $curr_coupon->coupon_valid);
- $xml_data->Element('code', $curr_coupon->coupon_code);
- $xml_data->Element('calculated-amount', $curr_coupon->coupon_amount,
- array('currency' => $curr_coupon->coupon_currency)
- );
- $xml_data->Element('message', $curr_coupon->coupon_message);
- $xml_data->Pop('coupon-result');
- }
- foreach ($result->giftcert_arr as $curr_gift) {
- $xml_data->Push('gift-result');
- $xml_data->Element('valid', $curr_gift->gift_valid);
- $xml_data->Element('code', $curr_gift->gift_code);
- $xml_data->Element('calculated-amount', $curr_gift->gift_amount,
- array('currency' => $curr_gift->gift_currency)
- );
- $xml_data->Element('message', $curr_gift->gift_message);
- $xml_data->Pop('gift-result');
- }
- $xml_data->Pop('merchant-code-results');
- }
- $xml_data->Pop('result');
- }
- $xml_data->Pop('results');
- $xml_data->Pop('merchant-calculation-results');
- return $xml_data->GetXML();
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This class is instantiated every time any notification or
- * order processing commands are received.
- *
- * It has a SendReq function to post different requests to the Google Server
- * Send functions are provided for most of the commands that are supported
- * by the server
- * Refer demo/responsehandlerdemo.php for different use case scenarios
- * for this code
- */
-class GoogleResponse {
- var $merchant_id;
- var $merchant_key;
- var $server_url;
- var $schema_url;
- var $base_url;
- var $checkout_url;
- var $checkout_diagnose_url;
- var $request_url;
- var $request_diagnose_url;
-
- var $response;
- var $root;
- var $data;
- var $xml_parser;
-
- /**
- * @param $id
- * @param $key
- * @param $response
- * @param string $server_type
- */
- function GoogleResponse($id, $key, $response, $server_type = "checkout") {
- $this->merchant_id = $id;
- $this->merchant_key = $key;
-
- if ($server_type == "sandbox") {
-
- $this->server_url = "https://sandbox.google.com/checkout/";
- }
- else $this->server_url = "https://checkout.google.com/";
-
- $this->schema_url = "http://checkout.google.com/schema/2";
- $this->base_url = $this->server_url . "cws/v2/Merchant/" . $this->merchant_id;
- $this->checkout_url = $this->base_url . "/checkout";
- $this->checkout_diagnose_url = $this->base_url . "/checkout/diagnose";
- $this->request_url = $this->base_url . "/request";
- $this->request_diagnose_url = $this->base_url . "/request/diagnose";
-
- $this->response = $response;
-
- if (strpos(__FILE__, ':') !== FALSE) {
-
- $path_delimiter = ';';
- }
- else $path_delimiter = ':';
-
- ini_set('include_path', ini_get('include_path') . $path_delimiter . '.');
- require_once ('xml-processing/xmlparser.php');
- $this->xml_parser = new XmlParser($response);
- $this->root = $this->xml_parser->GetRoot();
- $this->data = $this->xml_parser->GetData();
- }
-
- /**
- * @param $headers
- *
- * @return bool
- */
- function HttpAuthentication($headers) {
- if (isset($headers['Authorization'])) {
- $auth_encode = $headers['Authorization'];
- $auth = base64_decode(substr($auth_encode,
- strpos($auth_encode, " ") + 1
- ));
- $compare_mer_id = substr($auth, 0, strpos($auth, ":"));
- $compare_mer_key = substr($auth, strpos($auth, ":") + 1);
- }
- else {
- return FALSE;
- }
- if ($compare_mer_id != $this->merchant_id ||
- $compare_mer_key != $this->merchant_key
- ) return FALSE;
- return TRUE;
- }
-
- /**
- * @param $google_order
- * @param string $amount
- * @param $message_log
- */
- function SendChargeOrder($google_order, $amount = '', $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <charge-order xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\">";
- if ($amount != '') {
- $postargs .= "<amount currency=\"USD\">" . $amount . "</amount>";
- }
- $postargs .= "</charge-order>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $amount
- * @param $reason
- * @param $comment
- * @param $message_log
- */
- function SendRefundOrder($google_order, $amount, $reason, $comment, $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <refund-order xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\">
- <reason>" . $reason . "</reason>
- <amount currency=\"USD\">" . htmlentities($amount) . "</amount>
- <comment>" . htmlentities($comment) . "</comment>
- </refund-order>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $reason
- * @param $comment
- * @param $message_log
- */
- function SendCancelOrder($google_order, $reason, $comment, $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <cancel-order xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\">
- <reason>" . htmlentities($reason) . "</reason>
- <comment>" . htmlentities($comment) . "</comment>
- </cancel-order>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $carrier
- * @param $tracking_no
- * @param $message_log
- */
- function SendTrackingData($google_order, $carrier, $tracking_no, $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <add-tracking-data xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\">
- <tracking-data>
- <carrier>" . htmlentities($carrier) . "</carrier>
- <tracking-number>" . $tracking_no . "</tracking-number>
- </tracking-data>
- </add-tracking-data>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $merchant_order
- * @param $message_log
- */
- function SendMerchantOrderNumber($google_order, $merchant_order, $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <add-merchant-order-number xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\">
- <merchant-order-number>" . $merchant_order . "</merchant-order-number>
- </add-merchant-order-number>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $message
- * @param string $send_mail
- * @param $message_log
- */
- function SendBuyerMessage($google_order, $message, $send_mail = "true", $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <send-buyer-message xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\">
- <message>" . $message . "</message>
- <send-mail>" . $send_mail . "</send-mail>
- </send-buyer-message>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $message_log
- */
- function SendProcessOrder($google_order, $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <process-order xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\"/> ";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $carrier
- * @param $tracking_no
- * @param string $send_mail
- * @param $message_log
- */
- function SendDeliverOrder($google_order, $carrier, $tracking_no, $send_mail = "true", $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <deliver-order xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\">
- <tracking-data>
- <carrier>" . htmlentities($carrier) . "</carrier>
- <tracking-number>" . $tracking_no . "</tracking-number>
- </tracking-data>
- <send-email>" . $send_mail . "</send-email>
- </deliver-order>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $message_log
- */
- function SendArchiveOrder($google_order, $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <archive-order xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\"/>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $google_order
- * @param $message_log
- */
- function SendUnarchiveOrder($google_order, $message_log) {
- $postargs = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <unarchive-order xmlns=\"" . $this->schema_url . "\" google-order-number=\"" . $google_order . "\"/>";
- return $this->SendReq($this->request_url, $this->GetAuthenticationHeaders(),
- $postargs, $message_log
- );
- }
-
- /**
- * @param $merchant_calc
- */
- function ProcessMerchantCalculations($merchant_calc) {
- $result = $merchant_calc->GetXML();
- echo $result;
- }
-
- /**
- * @return array
- */
- function GetAuthenticationHeaders() {
- $headers = array();
- $headers[] = "Authorization: Basic " . base64_encode(
- $this->merchant_id . ':' . $this->merchant_key
- );
- $headers[] = "Content-Type: application/xml";
- $headers[] = "Accept: application/xml";
- return $headers;
- }
-
- /**
- * @param $url
- * @param $header_arr
- * @param $postargs
- * @param $message_log
- */
- function SendReq($url, $header_arr, $postargs, $message_log) {
- // Get the curl session object
- $session = curl_init($url);
-
- // Set the POST options.
- curl_setopt($session, CURLOPT_POST, TRUE);
- curl_setopt($session, CURLOPT_HTTPHEADER, $header_arr);
- curl_setopt($session, CURLOPT_POSTFIELDS, $postargs);
- curl_setopt($session, CURLOPT_HEADER, TRUE);
- curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE);
-
- // Do the POST and then close the session
- $response = curl_exec($session);
- if (curl_errno($session)) {
- die(curl_error($session));
- }
- else {
- curl_close($session);
- }
-
- // Get HTTP Status code from the response
- $status_code = array();
- preg_match('/\d\d\d/', $response, $status_code);
-
- // Check for errors
- switch ($status_code[0]) {
- case 200:
- // Success
- break;
-
- case 503:
- die('Error 503: Service unavailable.');
- break;
-
- case 403:
- die('Error 403: Forbidden.');
- break;
-
- case 400:
- die('Error 400: Bad request.');
- break;
-
- default:
- echo $response;
- die('Error :' . $status_code[0]);
- }
- fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
- $response
- ));
- }
-
- function SendAck() {
- $acknowledgment = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "<notification-acknowledgment xmlns=\"" . $this->schema_url . "\"/>";
- echo $acknowledgment;
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This class is used to create a Google Checkout result for merchant
- * as a response to merchant-calculations feedback structure
- * Refer demo/responsehandlerdemo.php for usage of this code
- *
- * Methods are provided to set the shipping, tax, coupons and gift certificate
- * options
- */
-class GoogleResult {
- var $shipping_name;
- var $address_id;
- var $shippable;
- var $ship_price;
- var $ship_currency;
-
- var $tax_currency;
- var $tax_amount;
-
- var $coupon_arr = array();
- var $giftcert_arr = array();
-
- /**
- * @param $address_id
- */
- function GoogleResult($address_id) {
- $this->address_id = $address_id;
- }
-
- /**
- * @param $name
- * @param $price
- * @param string $money
- * @param string $shippable
- */
- function SetShippingDetails($name, $price, $money = "USD",
- $shippable = "true"
- ) {
- $this->shipping_name = $name;
- $this->ship_price = $price;
- $this->ship_currency = $money;
- $this->shippable = $shippable;
- }
-
- /**
- * @param $amount
- * @param string $currency
- */
- function SetTaxDetails($amount, $currency = "USD") {
- $this->tax_amount = $amount;
- $this->tax_currency = $currency;
- }
-
- /**
- * @param $coupon
- */
- function AddCoupons($coupon) {
- $this->coupon_arr[] = $coupon;
- }
-
- /**
- * @param $gift
- */
- function AddGiftCertificates($gift) {
- $this->giftcert_arr[] = $gift;
- }
-}
-
-/* This is a class used to return the results of coupons
- * that the buyer entered code for on the place order page
- */
-
-/**
- * Class GoogleCoupons
- */
-class GoogleCoupons {
- var $coupon_valid;
- var $coupon_code;
- var $coupon_currency;
- var $coupon_amount;
- var $coupon_message;
-
- /**
- * @param $valid
- * @param $code
- * @param $amount
- * @param $currency
- * @param $message
- */
- function googlecoupons($valid, $code, $amount, $currency, $message) {
- $this->coupon_valid = $valid;
- $this->coupon_code = $code;
- $this->coupon_currency = $currency;
- $this->coupon_amount = $amount;
- $this->coupon_message = $message;
- }
-}
-
-/* This is a class used to return the results of gift certificates
- * that the buyer entered code for on the place order page
- */
-
-/**
- * Class GoogleGiftcerts
- */
-class GoogleGiftcerts {
- var $gift_valid;
- var $gift_code;
- var $gift_currency;
- var $gift_amount;
- var $gift_message;
-
- /**
- * @param $valid
- * @param $code
- * @param $amount
- * @param $currency
- * @param $message
- */
- function googlegiftcerts($valid, $code, $amount, $currency, $message) {
- $this->gift_valid = $valid;
- $this->gift_code = $code;
- $this->gift_currency = $currency;
- $this->gift_amount = $amount;
- $this->gift_message = $message;
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This class is used to add the shipping options for the cart
- * There are 3 types of shipping supported
- * 1. Flat (Type:flat-rate)
- * 2. Pickup (Type:pickup)
- * 3. Merchant calculated (Type:merchant-calculated)
- *
- * Invoke a separate instance of this class for each type of shipping
- * to be included
- * Required fields are shipping name, shipping type and price
- * Allowed and excluded country areas can be specified as part of constructor
- * arguments or using individual Set methods. Possible values here are
- * 1. CONTINENTAL_48
- * 2. FULL_50_STATES
- * 3. ALL
- * State and zip patterns must be exclusively updated using their individual Set methods
- */
-class GoogleShipping {
-
- var $type;
- var $price;
- var $currency;
- var $name;
-
- var $allowed_state_areas_arr;
- var $allowed_zip_patterns_arr;
- var $excluded_state_areas_arr;
- var $excluded_zip_patterns_arr;
- var $allowed_country_area;
- var $excluded_country_area;
- var $allowed_restrictions = FALSE;
- var $excluded_restrictions = FALSE;
-
- /**
- * @param $name
- * @param $type
- * @param $price
- * @param string $money
- * @param string $allowed_country_area
- * @param string $excluded_country_area
- */
- function GoogleShipping($name, $type, $price, $money = "USD",
- $allowed_country_area = "",
- $excluded_country_area = ""
- ) {
- $this->price = $price;
- $this->name = $name;
- $this->type = strtolower($type);
- $this->currency = $money;
-
- if ($allowed_country_area != "") {
-
- $this->SetAllowedCountryArea($allowed_country_area);
- }
-
- if ($excluded_country_area != "") {
-
- $this->SetExcludedCountryArea($excluded_country_area);
- }
-
- $this->allowed_state_areas_arr = array();
- $this->allowed_zip_patterns_arr = array();
- $this->excluded_state_areas_arr = array();
- $this->excluded_zip_patterns_arr = array();
- }
-
- /**
- * @param $areas
- */
- function SetAllowedStateAreas($areas) {
- $this->allowed_restrictions = TRUE;
- $this->allowed_state_areas_arr = $areas;
- }
-
- /**
- * @param $zips
- */
- function SetAllowedZipPattens($zips) {
- $this->allowed_restrictions = TRUE;
- $this->allowed_zip_patterns_arr = $zips;
- }
-
- /**
- * @param $areas
- */
- function SetExcludedStateAreas($areas) {
- $this->excluded_restrictions = TRUE;
- $this->excluded_state_areas_arr = $areas;
- }
-
- /**
- * @param $zips
- */
- function SetExcludedZipPatternsStateAreas($zips) {
- $this->excluded_restrictions = TRUE;
- $this->excluded_zip_patterns_arr = $zips;
- }
-
- /**
- * @param $country_area
- */
- function SetAllowedCountryArea($country_area) {
- if ($country_area == "CONTINENTAL_48" ||
- $country_area == "FULL_50_STATES" ||
- $country_area = "ALL"
- ) {
- $this->allowed_country_area = $country_area;
- $this->allowed_restrictions = TRUE;
- }
- else $this->allowed_country_area = "";
- }
-
- /**
- * @param $country_area
- */
- function SetExcludedCountryArea($country_area) {
- if ($country_area == "CONTINENTAL_48" ||
- $country_area == "FULL_50_STATES" ||
- $country_area = "ALL"
- ) {
- $this->excluded_country_area = $country_area;
- $this->excluded_restrictions = TRUE;
- }
- else $this->excluded_country_area = "";
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/* This class is used to create Tax rules to be added to the tax tables
- * in the shopping cart
- * There are two types of tax rules
- * 1. default (should be added to a default tax table)
- * 2. alternate (should be added to an alternate tax table)
- *
- * Invoke a separate instance of this class for each tax rule to be
- * added to the cart
- * Required fields are the rule type and the tax rate
- * Country area can be specified as part of constructor arguments or
- * using individual Set methods. Possible values here are
- * 1. CONTINENTAL_48
- * 2. FULL_50_STATES
- * 3. ALL
- * State and zip patterns must be exclusively updated using their
- * individual Set methods
- */
-class GoogleTaxRule {
-
- var $shipping_taxed;
- var $tax_rule_type;
- var $tax_rate;
-
- var $state_areas_arr;
- var $zip_patterns_arr;
- var $country_area;
-
- /**
- * @param $type
- * @param $tax_rate
- * @param string $country_area
- * @param string $shipping_taxed
- */
- function GoogleTaxRule($type, $tax_rate, $country_area = "",
- $shipping_taxed = "false"
- ) {
- $this->rax_rule_type = strtolower($type);
- $this->shipping_taxed = $shipping_taxed;
- $this->tax_rate = $tax_rate;
-
- if ($country_area != "") {
-
- $this->SetCountryArea($country_area);
- }
-
- $this->state_areas_arr = array();
- $this->zip_patterns_arr = array();
- }
-
- /**
- * @param $areas
- */
- function SetStateAreas($areas) {
- if (is_array($areas)) {
- $this->state_areas_arr = $areas;
- }
- else $this->state_areas_arr = array($areas);
- }
-
- /**
- * @param $zips
- */
- function SetZipPatterns($zips) {
- if (is_array($zips)) {
- $this->zip_patterns_arr = $zips;
- }
- else $this->zip_patterns_arr = array($zips);
- }
-
- /**
- * @param $country_area
- */
- function SetCountryArea($country_area) {
- if ($country_area == "CONTINENTAL_48" || $country_area == "FULL_50_STATES"
- || $country_area = "ALL"
- ) $this->country_area = $country_area;
- else $this->country_area = "";
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Copyright (C) 2006 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This class is used to add tax tables to the shopping cart
- * There are two types of tax tables
- * 1. default (there can be only a single default tax table)
- * 2. alternate
- *
- * Invoke a separate instance of this class for each tax table required
- * Required field is the type
- * Multiple default/alternate tax rules can be added using the AddTaxRulesMethod
- */
-class GoogleTaxTable {
-
- var $type;
- var $name;
- var $tax_rules_arr;
- var $standalone;
-
- /**
- * @param $type
- * @param string $name
- * @param string $standalone
- */
- function GoogleTaxTable($type, $name = "", $standalone = "false") {
- if (($type == "default") || ($type == "alternate" && $name != "")) {
- $this->name = $name;
- $this->type = strtolower($type);
- $this->tax_rules_arr = array();
- $this->standalone = $standalone;
- }
- }
-
- /**
- * @param $rules
- */
- function AddTaxRules($rules) {
- $this->tax_rules_arr[] = $rules;
- }
-}
-
+++ /dev/null
-<?php
-/*
- Copyright (C) 2006 Google Inc.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-
-/*
- * Class used to generate XML data
- * Based on sample code available at http://simon.incutio.com/code/php/XmlWriter.class.php.txt
- */
-
-/**
- * Class XmlBuilder
- */
-class XmlBuilder {
- var $xml;
- var $indent;
- var $stack = array();
-
- /**
- * @param string $indent
- */
- function XmlBuilder($indent = ' ') {
- $this->indent = $indent;
- $this->xml = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
- }
-
- function _indent() {
- for ($i = 0, $j = count($this->stack); $i < $j; $i++) {
- $this->xml .= $this->indent;
- }
- }
-
- //Used when an element has sub-elements
- // This function adds an open tag to the output
- /**
- * @param $element
- * @param array $attributes
- */
- function Push($element, $attributes = array()) {
- $this->_indent();
- $this->xml .= '<' . $element;
- foreach ($attributes as $key => $value) {
- $this->xml .= ' ' . $key . '="' . htmlentities($value) . '"';
- }
- $this->xml .= ">\n";
- $this->stack[] = $element;
- }
-
- //Used when an element has no subelements.
- //Data within the open and close tags are provided with the
- //contents variable
- /**
- * @param $element
- * @param $content
- * @param array $attributes
- */
- function Element($element, $content, $attributes = array()) {
- $this->_indent();
- $this->xml .= '<' . $element;
- foreach ($attributes as $key => $value) {
- $this->xml .= ' ' . $key . '="' . htmlentities($value) . '"';
- }
- $this->xml .= '>' . htmlentities($content) . '</' . $element . '>' . "\n";
- }
-
- /**
- * @param $element
- * @param array $attributes
- */
- function EmptyElement($element, $attributes = array()) {
- $this->_indent();
- $this->xml .= '<' . $element;
- foreach ($attributes as $key => $value) {
- $this->xml .= ' ' . $key . '="' . htmlentities($value) . '"';
- }
- $this->xml .= " />\n";
- }
-
- //Used to close an open tag
- /**
- * @param $pop_element
- */
- function Pop($pop_element) {
- $element = array_pop($this->stack);
- $this->_indent();
- if ($element !== $pop_element)die('XML Error: Tag Mismatch when trying to close "' . $pop_element . '"');
- else $this->xml .= "</$element>\n";
- }
-
- /**
- * @return string
- */
- function GetXML() {
- if (count($this->stack) != 0)die('XML Error: No matching closing tag found for " ' . array_pop($this->stack) { . '"'
- );
- }
- else return $this->xml;
- }
-}
-
+++ /dev/null
-<?php
-/*
- Copyright (C) 2006 Google Inc.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-
-/* This uses SAX parser to convert XML data into PHP associative arrays
- * When invoking the constructor with the input data, strip out the first XML line
- *
- * Member field Description:
- * $params: This stores the XML data. The attributes and contents of XML tags
- * can be accessed as follows
- *
- * <addresses>
- * <anonymous-address id="123"> <test>data 1 </test>
- * </anonymous-address>
- * <anonymous-address id="456"> <test>data 2 </test>
- * </anonymous-address>
- * </addresses>
- *
- * print_r($this->params) will return
- Array
-(
- [addresses] => Array
- (
- [anonymous-address] => Array
- (
- [0] => Array
- (
- [id] => 123
- [test] => Array
- (
- [VALUE] => data 1
- )
-
- )
-
- [1] => Array
- (
- [id] => 456
- [test] => Array
- (
- [VALUE] => data 2
- )
-
- )
-
- )
-
- )
-
-)
- * XmlParser returns an empty params array if it encounters
- * any error during parsing
- */
-
-/**
- * Class XmlParser
- */
-class XmlParser {
-
- // Stores the object representation of XML data
- var $params = array();
- var $root;
- var $global_index = -1;
-
- /* Constructor for the class
- * Takes in XML data as input( do not include the <xml> tag
- */
- /**
- * @param $input
- */
- function XmlParser($input) {
- $xmlp = xml_parser_create();
- xml_parse_into_struct($xmlp, $input, $vals, $index);
- xml_parser_free($xmlp);
- $this->root = strtolower($vals[0]['tag']);
- $this->params = $this->UpdateRecursive($vals);
- }
-
- /* Returns true if a given variable represents an associative array */
- /**
- * @param $var
- *
- * @return bool
- */
- function is_associative_array($var) {
- return is_array($var) && !is_numeric(implode('', array_keys($var)));
- }
-
- /* Converts the output of SAX parser into a PHP associative array similar to the
- * DOM parser output
- */
- /**
- * @param $vals
- *
- * @return array
- */
- function UpdateRecursive($vals) {
- $this->global_index++;
- //Reached end of array
- if ($this->global_index >= count($vals)) {
- return;
- }
-
- $tag = strtolower($vals[$this->global_index]['tag']);
- $value = trim($vals[$this->global_index]['value']);
- $type = $vals[$this->global_index]['type'];
-
- //Add attributes
- if (isset($vals[$this->global_index]['attributes'])) {
- foreach ($vals[$this->global_index]['attributes'] as $key => $val) {
- $key = strtolower($key);
- $params[$tag][$key] = $val;
- }
- }
-
- if ($type == 'open') {
- $new_arr = array();
-
- //Read all elements at the next levels and add to an array
- while ($vals[$this->global_index]['type'] != 'close' &&
- $this->global_index < count($vals)
- ) {
- $arr = $this->UpdateRecursive($vals);
- if (count($arr) > 0) {
- $new_arr[] = $arr;
- }
- }
- $this->global_index++;
- foreach ($new_arr as $arr) {
- foreach ($arr as $key => $val) {
- if (isset($params[$tag][$key])) {
- //If this key already exists
- if ($this->is_associative_array($params[$tag][$key])) {
- //If this is an associative array and not an indexed array
- // remove exisiting value and convert to an indexed array
- $val_key = $params[$tag][$key];
- array_splice($params[$tag][$key], 0);
- $params[$tag][$key][0] = $val_key;
- $params[$tag][$key][] = $val;
- }
- else {
- $params[$tag][$key][] = $val;
- }
- }
- else {
- $params[$tag][$key] = $val;
- }
- }
- }
- }
- elseif ($type == 'complete') {
- if ($value != '') {
- $params[$tag]['VALUE'] = $value;
- }
- }
- else $params = array();
- return $params;
- }
-
- /* Returns the root of the XML data */
- /**
- * @return string
- */
- function GetRoot() {
- return $this->root;
- }
-
- /* Returns the array representing the XML data */
- /**
- * @return array
- */
- function GetData() {
- return $this->params;
- }
-}
-
+++ /dev/null
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-require_once 'CRM/Report/Form.php';
-require_once 'CRM/Contribute/PseudoConstant.php';
-require_once 'CRM/Core/OptionGroup.php';
-require_once 'CRM/Event/BAO/Participant.php';
-require_once 'CRM/Contact/BAO/Contact.php';
-
-/**
- * Class CRM_Report_Form_Contribute_Baykeeper
- */
-class CRM_Report_Form_Contribute_Baykeeper extends CRM_Report_Form {
- protected $_addressField = FALSE;
-
- protected $_emailField = FALSE;
-
- protected $_summary = NULL;
-
- protected $_customGroupExtends = array('Contact', 'Contribution');
-
- /**
- *
- */
- function __construct() {
- $this->_columns = array('civicrm_contact' =>
- array('dao' => 'CRM_Contact_DAO_Contact',
- 'fields' =>
- array('display_name' =>
- array('title' => ts('Contact Name'),
- 'required' => TRUE,
- 'no_repeat' => TRUE,
- ),
- 'id' =>
- array('no_display' => FALSE,
- 'title' => ts('Contact ID'),
- 'required' => TRUE,
- ),
- 'contact_id' =>
- array('title' => ts('Contact ID'),
- 'name' => 'id',
- 'default' => FALSE,
- 'no_repeat' => TRUE,
- 'required' => TRUE,
- ),
- 'addressee_display' => array('title' => ts('Addressee Name')),
- 'postal_greeting_display' => array('title' => ts('Greeting')),
- 'display_name_creditor' =>
- array('title' => ts('Soft Credit Name'),
- 'name' => 'display_name',
- 'alias' => 'soft_credit',
- 'no_repeat' => TRUE,
- ),
- 'id_creditor' =>
- array('title' => ts('Soft Credit Id'),
- 'name' => 'id',
- 'alias' => 'soft_credit',
- ),
- 'employer_name' =>
- array('title' => ts('Employer Name'),
- 'name' => 'display_name',
- 'alias' => 'employer_company',
- ),
- 'employer_id' =>
- array('title' => ts('Employer Id'),
- 'name' => 'employer_id',
- ),
- 'do_not_mail' => array('title' => ts('Do Not Mail')),
- ),
- 'filters' =>
- array('sort_name' =>
- array('title' => ts('Contact Name'),
- 'operator' => 'like',
- ),
- 'id' =>
- array('title' => ts('Contact ID'),
- 'no_display' => TRUE,
- ),
- ),
- 'grouping' => 'contact-fields',
- ),
- 'civicrm_email' =>
- array('dao' => 'CRM_Core_DAO_Email',
- 'fields' =>
- array('email' =>
- array('title' => ts('Email'),
- 'default' => TRUE,
- 'no_repeat' => TRUE,
- ),
- ),
- 'grouping' => 'contact-fields',
- ),
- 'civicrm_phone' =>
- array('dao' => 'CRM_Core_DAO_Phone',
- 'fields' =>
- array('phone' =>
- array('title' => ts('Phone'),
- 'default' => TRUE,
- 'no_repeat' => TRUE,
- ),
- ),
- 'grouping' => 'contact-fields',
- ),
- 'civicrm_address' =>
- array('dao' => 'CRM_Core_DAO_Address',
- 'fields' =>
- array('street_address' => NULL,
- 'supplemental_address_1' => array('title' => ts('Sup Address 1'),
- ),
- 'supplemental_address_2' => array('title' => ts('Sup Address 2'),
- ),
- 'city' => NULL,
- 'postal_code' => NULL,
- 'location_type_id' => array('title' => ts('Location Type ID'),
- ),
- 'state_province_id' =>
- array('title' => ts('State/Province'),
- ),
- 'country_id' =>
- array('title' => ts('Country'),
- 'default' => TRUE,
- ),
- ),
- 'grouping' => 'contact-fields',
- 'filters' =>
- array('country_id' =>
- array('title' => ts('Country'),
- 'type' => CRM_Utils_Type::T_INT,
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Core_PseudoConstant::country(),
- ),
- 'state_province_id' =>
- array('title' => ts('State/Province'),
- 'type' => CRM_Utils_Type::T_INT,
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Core_PseudoConstant::stateProvince(),
- ),
- ),
- ),
- 'civicrm_contribution' =>
- array('dao' => 'CRM_Contribute_DAO_Contribution',
- 'fields' =>
- array(
- 'contribution_id' => array(
- 'name' => 'id',
- 'no_display' => TRUE,
- 'required' => TRUE,
- ),
- 'contribution_type_id' => array('title' => ts('Contribution Type'),
- 'default' => TRUE,
- ),
- 'trxn_id' => NULL,
- 'receive_date' => array('default' => TRUE),
- 'receipt_date' => NULL,
- 'source' => array('title' => ts('Source')),
- 'fee_amount' => NULL,
- 'net_amount' => NULL,
- 'non_deductible_amount' => array('title' => ts('Non Deductible Amount')),
- 'total_amount' => array('title' => ts('Total Amount'),
- 'required' => TRUE,
- ),
- 'honor_contact_id' => array('title' => ts('Honor Contact ID'),
- ),
- 'honor_type_id' => array('title' => ts('Hon/Mem Type')),
- ),
- 'filters' =>
- array('receive_date' =>
- array('operatorType' => CRM_Report_Form::OP_DATE),
- 'contribution_type_id' =>
- array('title' => ts('Contribution Type'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Contribute_PseudoConstant::contributionType(),
- ),
- 'contribution_status_id' =>
- array('title' => ts('Contribution Status'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
- ),
- 'total_amount' =>
- array('title' => ts('Contribution Amount')),
- ),
- 'grouping' => 'contri-fields',
- ),
- 'civicrm_contact_hon_mem' =>
- array('dao' => 'CRM_Contact_DAO_Contact',
- 'alias' => 'hon_mem',
- 'fields' =>
- array('id' => array('title' => ts('Hon/Mem Contact ID'),
- 'required' => TRUE,
- 'no_display' => TRUE,
- ),
- 'display_name' => array('title' => ts('In Honor Of'),
- 'required' => FALSE,
- ),
- ),
- 'grouping' => 'contri-fields',
- ),
- 'civicrm_note' =>
- array('dao' => 'CRM_Core_DAO_Note',
- 'fields' =>
- array(
- 'note' =>
- array('title' => ts('Note'),
- 'default' => TRUE,
- 'no_repeat' => FALSE,
- ),
- ),
- 'grouping' => 'contri-fields',
- ),
- 'civicrm_contribution_soft' =>
- array('dao' => 'CRM_Contribute_DAO_ContributionSoft',
- 'fields' =>
- array('contribution_id' =>
- array('title' => ts('Contribution ID'),
- 'no_display' => TRUE,
- 'default' => TRUE,
- ),
- 'contact_id' =>
- array('title' => ts('Contact ID'),
- 'no_display' => TRUE,
- 'default' => TRUE,
- ),
- 'id' =>
- array('default' => TRUE,
- 'no_display' => TRUE,
- ),
- ),
- 'grouping' => 'softcredit-fields',
- ),
- 'civicrm_group_field' =>
- array('dao' => 'CRM_Contact_DAO_Group',
- 'fields' =>
- array('title' =>
- array('title' => ts('Groups')),
- ),
- ),
- 'civicrm_group' =>
- array('dao' => 'CRM_Contact_DAO_GroupContact',
- 'alias' => 'cgroup',
- 'fields' =>
- array(
- ),
- 'filters' =>
- array('gid' =>
- array('name' => 'group_id',
- 'title' => ts('Group'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'group' => TRUE,
- 'options' => CRM_Core_PseudoConstant::group(),
- ),
- ),
- ),
- 'civicrm_contribution_ordinality' =>
- array('dao' => 'CRM_Contribute_DAO_Contribution',
- 'alias' => 'cordinality',
- 'filters' =>
- array('ordinality' =>
- array('title' => ts('Contribution Ordinality'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => array(0 => 'First by Contributor',
- 1 => 'Second or Later by Contributor',
- ),
- ),
- ),
- ),
- );
-
- $this->_options = array('first_contribution' => array('title' => ts('First Contribution'),
- 'type' => 'checkbox',
- ),
- 'last_contribution' => array('title' => ts('Last Contribution'),
- 'type' => 'checkbox',
- ),
- 'include_nondonors' => array('title' => ts('Include non-donors?'),
- 'type' => 'checkbox',
- ),
- );
-
- $this->_tagFilter = TRUE;
- parent::__construct();
- }
-
- function preProcess() {
- parent::preProcess();
- }
-
- function select() {
- $select = array();
-
- $this->_columnHeaders = array();
- foreach ($this->_columns as $tableName => $table) {
- if (array_key_exists('fields', $table)) {
- foreach ($table['fields'] as $fieldName => $field) {
- if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
- if ($tableName == 'civicrm_address') {
- $this->_addressField = TRUE;
- }
- elseif ($tableName == 'civicrm_email') {
- $this->_emailField = TRUE;
- }
- /*
- if ( $tableName == 'civicrm_group_field' && $fieldName == 'title' ) {
- $select[] = "GROUP_CONCAT(DISTINCT {$field['dbAlias']} ORDER BY {$field['dbAlias']} ) as {$tableName}_{$fieldName}";
- } else {
- $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
- }
- */
-
-
- // only include statistics columns if set
- if (!empty($field['statistics'])) {
- foreach ($field['statistics'] as $stat => $label) {
- switch (strtolower($stat)) {
- case 'sum':
- $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
- $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
- $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
- $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
- break;
-
- case 'count':
- $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
- $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
- $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
- break;
-
- case 'avg':
- $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
- $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
- $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
- $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
- break;
- }
- }
- }
- elseif ($tableName == 'civicrm_group_field' && $fieldName == 'title') {
- $select[] = " GROUP_CONCAT(DISTINCT {$field['dbAlias']} ORDER BY {$field['dbAlias']} SEPARATOR ' | <br>') as {$tableName}_{$fieldName} ";
- $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
- $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
- }
- else {
- $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
- $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
- $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
- }
- }
- }
- }
- }
-
- // insert first and last contribution at end
- if (!empty($this->_params['options']['first_contribution'])) {
- $select[] = " '' as first_contribution";
- $this->_columnHeaders['first_contribution']['title'] = ts('First Contribution');
- }
-
- if (!empty($this->_params['options']['last_contribution'])) {
- $select[] = " '' as last_contribution";
- $this->_columnHeaders['last_contribution']['title'] = ts('Last Contribution');
- }
-
-
- $this->_select = "SELECT " . implode(', ', $select) . " ";
- }
-
- function from() {
- $alias_constituent = 'constituentname';
- $alias_creditor = 'soft_credit';
- $alias_employer = "employer_company";
-
- $this->_from = NULL;
-
- $hackValue = CRM_Utils_Array::value('include_nondonors', $this->_params['options'], 0);
- $contribJoin = $hackValue ? "LEFT" : "INNER";
-
- $this->_from = "
- FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
- $contribJoin JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
- ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
- $contribJoin JOIN (SELECT c.id, IF(COUNT(oc.id) = 0, 0, 1) AS ordinality FROM civicrm_contribution c LEFT JOIN civicrm_contribution oc ON c.contact_id = oc.contact_id AND oc.receive_date < c.receive_date GROUP BY c.id) {$this->_aliases['civicrm_contribution_ordinality']}
- ON {$this->_aliases['civicrm_contribution_ordinality']}.id = {$this->_aliases['civicrm_contribution']}.id
- LEFT JOIN civicrm_note {$this->_aliases['civicrm_note']}
- ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_note']}.contact_id AND
- {$this->_aliases['civicrm_contribution']}.id = {$this->_aliases['civicrm_note']}.entity_id )
- LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
- ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
- {$this->_aliases['civicrm_phone']}.is_primary = 1)
- LEFT JOIN civicrm_contact {$alias_employer}
- ON {$this->_aliases['civicrm_contact']}.employer_id =
- {$alias_employer}.id
- LEFT JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
- ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id =
- {$this->_aliases['civicrm_contribution']}.id
- LEFT JOIN civicrm_contact {$alias_creditor}
- ON {$this->_aliases['civicrm_contribution_soft']}.contact_id =
- {$alias_creditor}.id
- LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact_hon_mem']}
- ON {$this->_aliases['civicrm_contribution']}.honor_contact_id = {$this->_aliases['civicrm_contact_hon_mem']}.id
- ";
- // add group - concatenated
- $this->_from .= " LEFT JOIN civicrm_group_contact gc ON {$this->_aliases['civicrm_contact']}.id = gc.contact_id AND gc.status = 'Added'
- LEFT JOIN civicrm_group {$this->_aliases['civicrm_group_field']} ON {$this->_aliases['civicrm_group_field']}.id = gc.group_id ";
-
- if ($this->_addressField OR (!empty($this->_params['state_province_id_value']) OR !empty($this->_params['country_id_value']))) {
- $this->_from .= "
- LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
- ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
- {$this->_aliases['civicrm_address']}.is_primary = 1\n";
- }
-
- if ($this->_emailField) {
- $this->_from .= "
- LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
- ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
- {$this->_aliases['civicrm_email']}.is_primary = 1\n";
- }
- }
-
- function groupBy() {
- $this->_groupBy = " GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.id ";
- }
-
- function orderBy() {
- $this->_orderBy = " ORDER BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.receive_date ";
- }
-
- /**
- * @param $rows
- *
- * @return array
- */
- function statistics(&$rows) {
- $statistics = parent::statistics($rows);
- // because the query returns groups, the amount is multiplied by the number of groups a contact is in
- // that's why this is disabled
- /* SUM( {$this->_aliases['civicrm_contribution']}.total_amount ) as amount, */
-
-
- $select = "
- SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
- ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg
- ";
- $sql = "{$select} {$this->_from} {$this->_where}";
- $dao = CRM_Core_DAO::executeQuery($sql);
-
- if ($dao->fetch()) {
- // because the query returns groups, the amount is multiplied by the number of groups a contact is in
- // that's why this is disabled
- /* SUM( {$this->_aliases['civicrm_contribution']}.total_amount ) as amount, */
-
-
- /*
- $statistics['counts']['amount'] = array( 'value' => $dao->amount,
- 'title' => 'Total Amount',
- 'type' => CRM_Utils_Type::T_MONEY );
- $statistics['counts']['avg'] = array( 'value' => $dao->avg,
- 'title' => 'Average',
- 'type' => CRM_Utils_Type::T_MONEY );
- */
- }
-
- return $statistics;
- }
-
- function postProcess() {
- // get the acl clauses built before we assemble the query
- $this->buildACLClause($this->_aliases['civicrm_contact']);
- parent::postProcess();
- }
-
- /**
- * @param $rows
- */
- function alterDisplay(&$rows) {
-
- require_once 'CRM/Contribute/BAO/Contribution/Utils.php';
- require_once 'CRM/Utils/Money.php';
- require_once 'CRM/Utils/Date.php';
-
- $config = &CRM_Core_Config::singleton();
-
- // custom code to alter rows
- $checkList = array();
- $entryFound = FALSE;
- $display_flag = $prev_cid = $cid = 0;
- $contributionTypes = CRM_Contribute_PseudoConstant::contributionType();
-
- foreach ($rows as $rowNum => $row) {
- if (!empty($this->_noRepeats) &&
- $this->_outputMode != 'csv'
- ) {
- // don't repeat contact details if its same as the previous row
- if (array_key_exists('civicrm_contact_id', $row)) {
- if ($cid = $row['civicrm_contact_id']) {
- if ($rowNum == 0) {
- $prev_cid = $cid;
- }
- else {
- if ($prev_cid == $cid) {
- $display_flag = 1;
- $prev_cid = $cid;
- }
- else {
- $display_flag = 0;
- $prev_cid = $cid;
- }
- }
-
- if ($display_flag) {
- foreach ($row as $colName => $colVal) {
- if (in_array($colName, $this->_noRepeats)) {
- unset($rows[$rowNum][$colName]);
- }
- }
- }
- $entryFound = TRUE;
- }
- }
- }
-
- if (array_key_exists('first_contribution', $row) ||
- array_key_exists('last_contribution', $row)
- ) {
- $details = CRM_Contribute_BAO_Contribution_Utils::getFirstLastDetails($row['civicrm_contact_id']);
- if ($details['first']) {
- $rows[$rowNum]['first_contribution'] = CRM_Utils_Money::format($details['first']['total_amount']) . ' - ' . CRM_Utils_Date::customFormat($details['first']['receive_date'], $config->dateformatFull);
- }
- if ($details['last']) {
- $rows[$rowNum]['last_contribution'] = CRM_Utils_Money::format($details['last']['total_amount']) . ' - ' . CRM_Utils_Date::customFormat($details['last']['receive_date'], $config->dateformatFull);
- }
- }
-
- // handle state province
- if (array_key_exists('civicrm_address_state_province_id', $row)) {
- if ($value = $row['civicrm_address_state_province_id']) {
- $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
-
- $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
- "reset=1&force=1&" .
- "state_province_id_op=in&state_province_id_value={$value}",
- $this->_absoluteUrl, $this->_id
- );
- $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
- $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("List all contribution(s) for this State.");
- }
- $entryFound = TRUE;
- }
-
- // handle country
- if (array_key_exists('civicrm_address_country_id', $row)) {
- if ($value = $row['civicrm_address_country_id']) {
- $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
-
- $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
- "reset=1&force=1&" .
- "country_id_op=in&country_id_value={$value}",
- $this->_absoluteUrl, $this->_id
- );
- $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
- $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("List all contribution(s) for this Country.");
- }
-
- $entryFound = TRUE;
- }
-
- // convert display name to links
- if (array_key_exists('civicrm_contact_display_name', $row) && !empty($rows[$rowNum]['civicrm_contact_display_name']) &&
- array_key_exists('civicrm_contact_id', $row)
- ) {
- $url = CRM_Utils_System::url("civicrm/contact/view",
- 'reset=1&cid=' . $row['civicrm_contact_id'],
- $this->_absoluteUrl
- );
- $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
- $rows[$rowNum]['civicrm_contact_display_name_hover'] = ts("View Contact Summary for this Contact.");
- }
-
- // convert soft credit id to link
- if (array_key_exists('soft_credit_display_name', $row) && !empty($rows[$rowNum]['soft_credit_display_name']) &&
- array_key_exists('id', $row)
- ) {
- $url = CRM_Utils_System::url("civicrm/contact/view",
- 'reset=1&cid=' . $row['id'],
- $this->_absoluteUrl
- );
- $rows[$rowNum]['soft_credit_display_name_creditor_link'] = $url;
- $rows[$rowNum]['soft_credit_display_name_creditor_hover'] = ts("View Contact Summary for this Soft Credit.");
- }
-
- // convert hon/mem contact to link
- if (array_key_exists('civicrm_contact_hon_mem_display_name', $row) && !empty($rows[$rowNum]['civicrm_contribution_honor_contact_id']) &&
- array_key_exists('civicrm_contribution_honor_contact_id', $row)
- ) {
- $url = CRM_Utils_System::url("civicrm/contact/view",
- 'reset=1&cid=' . $row['civicrm_contribution_honor_contact_id'],
- $this->_absoluteUrl
- );
- $rows[$rowNum]['civicrm_contact_hon_mem_display_name_link'] = $url;
- $rows[$rowNum]['civicrm_contact_hon_mem_display_name_hover'] = ts("View Contact Summary for this Honor/Memory Contribution.");
- }
-
- // honor of/memory of type
- if ($value = CRM_Utils_Array::value('civicrm_contribution_honor_type_id', $row) && !empty($rows[$rowNum]['civicrm_contribution_honor_type_id'])) {
- // rather than do a join, just change the output here, since there these values are pretty static
-
-
- if ($rows[$rowNum]['civicrm_contribution_honor_type_id'] == 1) {
- $rows[$rowNum]['civicrm_contribution_honor_type_id'] = "In Honor Of";
- }
- elseif ($rows[$rowNum]['civicrm_contribution_honor_type_id'] == 2) {
- $rows[$rowNum]['civicrm_contribution_honor_type_id'] = "In Memory Of";
- }
- else {
- $rows[$rowNum]['civicrm_contribution_honor_type_id'] = "n/a";
- }
- }
-
- if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_type_id', $row)) {
- $rows[$rowNum]['civicrm_contribution_contribution_type_id'] = $contributionTypes[$value];
- $entryFound = TRUE;
- }
-
- if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount', $row)) &&
- CRM_Core_Permission::check('access CiviContribute')
- ) {
- $url = CRM_Utils_System::url("civicrm/contact/view/contribution",
- "reset=1&id=" .
- $row['civicrm_contribution_contribution_id'] .
- "&cid=" .
- $row['civicrm_contact_id'] .
- "&action=view&context=contribution&selectedChild=contribute",
- $this->_absoluteUrl
- );
- $rows[$rowNum]['civicrm_contribution_total_amount_link'] = $url;
- $rows[$rowNum]['civicrm_contribution_total_amount_hover'] = ts("View Details of this Contribution.");
- $entryFound = TRUE;
- }
-
- // skip looking further in rows, if first row itself doesn't
- // have the column we need
- if (!$entryFound) {
- break;
- }
- $lastKey = $rowNum;
- }
- }
-}
-
+++ /dev/null
-{*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*}
-{include file="CRM/Report/Form.tpl"}
-
-{literal}
-<script>
-$("th.reports-header:contains('Honor Contact ID')").hide();
-$("td.crm-report-civicrm_contribution_honor_contact_id").hide();
-</script>
-{/literal}
\ No newline at end of file
+++ /dev/null
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-require_once 'CRM/Report/Form.php';
-
-/**
- * Class org_civicrm_report_grant
- */
-class org_civicrm_report_grant extends CRM_Report_Form {
-
- protected $_addressField = FALSE;
-
- /**
- *
- */
- function __construct() {
- $this->_columns = array(
- 'civicrm_contact' =>
- array('dao' => 'CRM_Contact_DAO_Contact',
- 'fields' =>
- array('display_name' =>
- array('title' => ts('Contact Name'),
- 'required' => TRUE,
- 'no_repeat' => TRUE,
- ),
- ),
- 'grouping' => 'contact-fields',
- 'filters' =>
- array('display_name' =>
- array('title' => ts('Contact Name'),
- 'operator' => 'like',
- ),
- 'gender_id' =>
- array('title' => ts('Gender'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
- ),
- ),
- ),
- 'civicrm_address' =>
- array('dao' => 'CRM_Core_DAO_Address',
- 'filters' =>
- array('country_id' =>
- array('title' => ts('Country'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Core_PseudoConstant::country(),
- ),
- 'state_province_id' =>
- array('title' => ts('State/Province'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Core_PseudoConstant::stateProvince(),
- ),
- ),
- ),
- 'civicrm_grant' =>
- array('dao' => 'CRM_Grant_DAO_Grant',
- 'fields' =>
- array(
- 'grant_type_id' =>
- array(
- 'name' => 'grant_type_id',
- 'title' => ts('Grant Type'),
- ),
- 'status_id' =>
- array(
- 'name' => 'status_id',
- 'title' => ts('Grant Status'),
- ),
- 'amount_requested' =>
- array(
- 'name' => 'amount_requested',
- 'title' => ts('Amount Requested'),
- 'type' => CRM_Utils_Type::T_MONEY,
- ),
- 'amount_granted' =>
- array(
- 'name' => 'amount_granted',
- 'title' => ts('Amount Granted'),
- ),
- 'application_received_date' =>
- array(
- 'name' => 'application_received_date',
- 'title' => ts('Application Received Date'),
- 'default' => TRUE,
- ),
- 'money_transfer_date' =>
- array(
- 'name' => 'money_transfer_date',
- 'title' => ts('Money Transfer Date'),
- 'type' => CRM_Utils_Type::T_DATE,
- ),
- 'grant_due_date' =>
- array(
- 'name' => 'grant_due_date',
- 'title' => ts('Grant Due Date'),
- 'type' => CRM_Utils_Type::T_DATE,
- ),
- 'rationale' =>
- array(
- 'name' => 'rationale',
- 'title' => ts('Rationale'),
- ),
- 'grant_report_received' =>
- array(
- 'name' => 'grant_report_received',
- 'title' => ts('Grant Report Received'),
- ),
- ),
- 'filters' =>
- array('grant_type' =>
- array(
- 'name' => 'grant_type_id',
- 'title' => ts('Grant Type'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'grant_type_id'),
- ),
- 'status_id' =>
- array(
- 'name' => 'status_id',
- 'title' => ts('Grant Status'),
- 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
- 'options' => CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'status_id'),
- ),
- 'amount_granted' =>
- array(
- 'title' => ts('Amount Granted'),
- 'operatorType' => CRM_Report_Form::OP_INT,
- ),
- 'amount_requested' =>
- array(
- 'title' => ts('Amount Requested'),
- 'operatorType' => CRM_Report_Form::OP_INT,
- ),
- 'application_received_date' =>
- array(
- 'title' => ts('Application Received Date'),
- 'operatorType' => CRM_Report_Form::OP_DATE,
- ),
- 'money_transfer_date' =>
- array(
- 'title' => ts('Money Transfer Date'),
- 'operatorType' => CRM_Report_Form::OP_DATE,
- ),
- 'grant_due_date' =>
- array(
- 'title' => ts('Grant Due Date'),
- 'operatorType' => CRM_Report_Form::OP_DATE,
- 'type' => CRM_Report_Form::OP_DATE,
- ),
- ),
- 'group_bys' =>
- array(
- 'grant_type_id' =>
- array(
- 'title' => ts('Grant Type'),
- ),
- 'status_id' =>
- array(
- 'title' => ts('Grant Status'),
- ),
- 'amount_requested' =>
- array(
- 'title' => ts('Amount Requested'),
- ),
- 'amount_granted' =>
- array(
- 'title' => ts('Amount Granted'),
- ),
- 'application_received_date' =>
- array(
- 'title' => ts('Application Received Date'),
- ),
- 'money_transfer_date' =>
- array(
- 'title' => ts('Money Transfer Date'),
- ),
- ),
- ),
- );
-
- parent::__construct();
- }
-
- function select() {
- $select = array();
-
- $this->_columnHeaders = array();
- foreach ($this->_columns as $tableName => $table) {
- if ($tableName == 'civicrm_address') {
- $this->_addressField = TRUE;
- }
- if (array_key_exists('fields', $table)) {
- foreach ($table['fields'] as $fieldName => $field) {
- if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
-
- $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
-
- $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
- $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
- }
- }
- }
- }
-
- $this->_select = "SELECT " . implode(', ', $select) . " ";
- }
-
- function from() {
- $this->_from = "
- FROM civicrm_grant {$this->_aliases['civicrm_grant']}
- LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
- ON ({$this->_aliases['civicrm_grant']}.contact_id = {$this->_aliases['civicrm_contact']}.id ) ";
- if ($this->_addressField) {
- $this->_from .= "
- LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
- ON {$this->_aliases['civicrm_contact']}.id =
- {$this->_aliases['civicrm_address']}.contact_id AND
- {$this->_aliases['civicrm_address']}.is_primary = 1\n";
- }
- }
-
- function where() {
- $clauses = array();
- foreach ($this->_columns as $tableName => $table) {
- if (array_key_exists('filters', $table)) {
- foreach ($table['filters'] as $fieldName => $field) {
-
- $clause = NULL;
- if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
- $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
- $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
- $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
-
- if ($relative || $from || $to) {
- $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
- }
- }
- else {
- $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
- if ($op) {
- $clause = $this->whereClause($field,
- $op,
- CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
- CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
- CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
- );
- }
- }
- if (!empty($clause)) {
- $clauses[] = $clause;
- $this->_where = "WHERE" . implode(' AND ', $clauses);
- }
- }
- }
- }
- }
-
- function groupBy() {
- $this->_groupBy = "";
- if (!empty($this->_params['group_bys']) &&
- is_array($this->_params['group_bys']) &&
- !empty($this->_params['group_bys'])
- ) {
- foreach ($this->_columns as $tableName => $table) {
- if (array_key_exists('group_bys', $table)) {
- foreach ($table['group_bys'] as $fieldName => $field) {
- if (!empty($this->_params['group_bys'][$fieldName])) {
- $this->_groupBy[] = $field['dbAlias'];
- }
- }
- }
- }
- }
- if (!empty($this->_groupBy)) {
- $this->_groupBy = "ORDER BY " . implode(', ', $this->_groupBy) . ", {$this->_aliases['civicrm_contact']}.sort_name";
- }
- }
-
- /**
- * @param $rows
- */
- function alterDisplay(&$rows) {
- // custom code to alter rows
- $entryFound = FALSE;
- foreach ($rows as $rowNum => $row) {
- if (array_key_exists('civicrm_grant_grant_type_id', $row)) {
- if ($value = $row['civicrm_grant_grant_type_id']) {
- $rows[$rowNum]['civicrm_grant_grant_type_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Grant_DAO_Grant', 'grant_type_id', $value);
- }
- $entryFound = TRUE;
- }
- if (array_key_exists('civicrm_grant_status_id', $row)) {
- if ($value = $row['civicrm_grant_status_id']) {
- $rows[$rowNum]['civicrm_grant_status_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Grant_DAO_Grant', 'status_id', $value);
- }
- $entryFound = TRUE;
- }
- if (array_key_exists('civicrm_grant_grant_report_received', $row)) {
- if ($value = $row['civicrm_grant_grant_report_received']) {
- if ($value == 1) {
- $value = 'Yes';
- }
- else {
- $value = 'No';
- }
- $rows[$rowNum]['civicrm_grant_grant_report_received'] = $value;
- }
- $entryFound = TRUE;
- }
- if (!$entryFound) {
- break;
- }
- }
- }
-}
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
- <extension key="org.civicrm.report.grant" type="report">
- <downloadUrl>http://svn.civicrm.org/tools/branches/v3.3/extensions/org.civicrm.report.grant.zip</downloadUrl>
- <file>Grant</file>
- <name>Grant Report</name>
- <description>Grant Report allows you to see the summary of grants that
- have been admitted to your consitutents by your organisation.</description>
- <urls>
- <url desc="Main Extension Page">http://civicrm.org</url>
- <url desc="Support">http://forum.civicrm.org</url>
- <url desc="Licensing">http://civicrm.org/licensing</url>
- </urls>
- <license>AGPL</license>
- <maintainer>
- <author>CiviCRM LLC</author>
- <email>info@civicrm.org</email>
- </maintainer>
- <releaseDate>2010-09-01</releaseDate>
- <version>1.1</version>
- <develStage>stable</develStage>
- <compatibility><ver>3.3</ver></compatibility>
- <comments>For support, please contact project team on the forums. (http://forum.civicrm.org)</comments>
- <typeInfo>
- <reportUrl>grant/summary</reportUrl>
- <component>CiviGrant</component>
- </typeInfo>
-</extension>
+++ /dev/null
-{*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*}
-{include file="CRM/Report/Form.tpl"}
\ No newline at end of file
+++ /dev/null
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-require_once 'CRM/Contact/Form/Search/Interface.php';
-
-/**
- * Class org_civicrm_search_activityimplementsCRM_Contact_Form_Search_Interface
- */
-class org_civicrm_search_activityimplementsCRM_Contact_Form_Search_Interface {
-
- protected $_formValues;
-
- /**
- * @param $formValues
- */
- function __construct(&$formValues) {
- $this->_formValues = $formValues;
-
- /**
- * Define the columns for search result rows
- */
- $this->_columns = array(
- ts('Name') => 'sort_name',
- ts('Status') => 'activity_status',
- ts('Activity Type') => 'activity_type',
- ts('Activity Subject') => 'activity_subject',
- ts('Scheduled By') => 'source_contact',
- ts('Scheduled Date') => 'activity_date',
- ' ' => 'activity_id',
- ' ' => 'activity_type_id',
- ' ' => 'case_id',
- ts('Location') => 'location',
- ts('Duration') => 'duration',
- ts('Details') => 'details',
- ts('Assignee') => 'assignee',
- );
-
- $this->_groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
- 'activity_status',
- 'id',
- 'name'
- );
-
- //Add custom fields to columns array for inclusion in export
- require_once 'CRM/Core/BAO/CustomGroup.php';
- $groupTree = &CRM_Core_BAO_CustomGroup::getTree('Activity', $form, NULL,
- NULL, '', NULL
- );
-
-
- //use simplified formatted groupTree
- $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $form);
-
- //cycle through custom fields and assign to _columns array
- foreach ($groupTree as $key) {
- foreach ($key['fields'] as $field) {
- $fieldlabel = $key['title'] . ": " . $field['label'];
- $this->_columns[$fieldlabel] = $field['column_name'];
- }
- }
- //end custom fields
- }
-
- /**
- * @param CRM_Core_Form $form
- */
- function buildForm(&$form) {
-
- /**
- * You can define a custom title for the search form
- */
- $this->setTitle('Find Latest Activities');
-
- /**
- * Define the search form fields here
- */
- // Allow user to choose which type of contact to limit search on
- $form->add('select', 'contact_type', ts('Find...'), CRM_Core_SelectValues::contactType());
-
- // Text box for Activity Subject
- $form->add('text',
- 'activity_subject',
- ts('Activity Subject')
- );
-
- // Select box for Activity Type
- $activityType = array('' => ' - select activity - ') + CRM_Core_PseudoConstant::activityType();
-
- $form->add('select', 'activity_type_id', ts('Activity Type'),
- $activityType,
- FALSE
- );
-
- // textbox for Activity Status
- $activityStatus = array('' => ' - select status - ') + CRM_Core_PseudoConstant::activityStatus();
-
- $form->add('select', 'activity_status_id', ts('Activity Status'),
- $activityStatus,
- FALSE
- );
-
- // Activity Date range
- $form->addDate('start_date', ts('Activity Date From'), FALSE, array('formatType' => 'custom'));
- $form->addDate('end_date', ts('...through'), FALSE, array('formatType' => 'custom'));
-
-
- // Contact Name field
- $form->add('text', 'sort_name', ts('Contact Name'));
-
- /**
- * If you are using the sample template, this array tells the template fields to render
- * for the search form.
- */
- $form->assign('elements', array('contact_type', 'activity_subject', 'activity_type_id',
- 'activity_status_id', 'start_date', 'end_date', 'sort_name',
- ));
- }
-
- /**
- * Define the smarty template used to layout the search form and results listings.
- */
- function templateFile() {
- return 'ActivitySearch.tpl';
- }
-
- /**
- * Construct the search query
- * @param int $offset
- * @param int $rowcount
- * @param null $sort
- * @param bool $includeContactIDs
- * @param bool $onlyIDs
- * @return string
- */
- function all($offset = 0, $rowcount = 0, $sort = NULL,
- $includeContactIDs = FALSE, $onlyIDs = FALSE
- ) {
-
- // SELECT clause must include contact_id as an alias for civicrm_contact.id
- if ($onlyIDs) {
- $select = 'contact_a.id as contact_id';
- }
- else {
- $select = '
- contact_a.id as contact_id,
- contact_a.sort_name as sort_name,
- contact_a.contact_type as contact_type,
- activity.id as activity_id,
- activity.activity_type_id as activity_type_id,
- contact_b.sort_name as source_contact,
- ov1.label as activity_type,
- activity.subject as activity_subject,
- activity.activity_date_time as activity_date,
- ov2.label as activity_status,
- cca.case_id as case_id,
- activity.location as location,
- activity.duration as duration,
- activity.details as details,
- assignment.activity_id as assignment_activity,
- contact_c.display_name as assignee
- ';
- }
-
- $from = $this->from();
-
- $where = $this->where($includeContactIDs);
-
- if (!empty($where)) {
- $where = "WHERE $where";
- }
-
- // add custom group fields to SELECT and FROM clause
- require_once 'CRM/Core/BAO/CustomGroup.php';
- $groupTree = &CRM_Core_BAO_CustomGroup::getTree('Activity', $form, NULL, NULL, '', NULL);
-
- foreach ($groupTree as $key) {
- if ($key['extends'] == 'Activity') {
- $select .= ", " . $key['table_name'] . ".*";
- $from .= " LEFT JOIN " . $key['table_name'] . " ON " . $key['table_name'] . ".entity_id = activity.id";
- }
- }
- // end custom groups add
-
- $sql = " SELECT $select FROM $from $where ";
-
- //no need to add order when only contact Ids.
- if (!$onlyIDs) {
- // Define ORDER BY for query in $sort, with default value
- if (!empty($sort)) {
- if (is_string($sort)) {
- $sql .= " ORDER BY $sort ";
- }
- else {
- $sql .= ' ORDER BY ' . trim($sort->orderBy());
- }
- }
- else {
- $sql .= 'ORDER BY contact_a.sort_name, activity.activity_date_time DESC, activity.activity_type_id, activity.status_id, activity.subject';
- }
- }
-
- if ($rowcount > 0 && $offset >= 0) {
- $sql .= " LIMIT $offset, $rowcount ";
- }
- return $sql;
- }
-
- // Alters the date display in the Activity Date Column. We do this after we already have
- // the result so that sorting on the date column stays pertinent to the numeric date value
- /**
- * @param $row
- */
- function alterRow(&$row) {
- $row['activity_date'] = CRM_Utils_Date::customFormat($row['activity_date'], '%B %E%f, %Y %l:%M %P');
- }
-
- // Regular JOIN statements here to limit results to contacts who have activities.
- /**
- * @return string
- */
- function from() {
- return "
- civicrm_contact contact_a
- JOIN civicrm_activity activity
- ON contact_a.id = activity.source_contact_id
- JOIN civicrm_option_value ov1
- ON activity.activity_type_id = ov1.value AND ov1.option_group_id = 2
- JOIN civicrm_option_value ov2
- ON activity.status_id = ov2.value AND ov2.option_group_id = {$this->_groupId}
- JOIN civicrm_contact contact_b
- ON activity.source_contact_id = contact_b.id
- LEFT JOIN civicrm_case_activity cca
- ON activity.id = cca.activity_id
- LEFT JOIN civicrm_activity_assignment assignment
- ON activity.id = assignment.activity_id
- LEFT JOIN civicrm_contact contact_c
- ON assignment.assignee_contact_id = contact_c.id ";
- }
-
- /**
- * WHERE clause is an array built from any required JOINS plus conditional filters based on search criteria field values
- *
- * @param bool $includeContactIDs
- *
- * @return string
- */
- function where($includeContactIDs = FALSE) {
- $clauses = array();
-
- // add contact name search; search on primary name, source contact, assignee
- $contactname = $this->_formValues['sort_name'];
- if (!empty($contactname)) {
- $dao = new CRM_Core_DAO();
- $contactname = $dao->escape($contactname);
- $clauses[] = "(contact_a.sort_name LIKE '%{$contactname}%' OR
- contact_b.sort_name LIKE '%{$contactname}%' OR
- contact_c.display_name LIKE '%{$contactname}%')";
- }
-
- $subject = $this->_formValues['activity_subject'];
-
- if (!empty($this->_formValues['contact_type'])) {
- $clauses[] = "contact_a.contact_type LIKE '%{$this->_formValues['contact_type']}%'";
- }
-
- if (!empty($subject)) {
- $dao = new CRM_Core_DAO();
- $subject = $dao->escape($subject);
- $clauses[] = "activity.subject LIKE '%{$subject}%'";
- }
-
- if (!empty($this->_formValues['activity_status_id'])) {
- $clauses[] = "activity.status_id = {$this->_formValues['activity_status_id']}";
- }
-
- if (!empty($this->_formValues['activity_type_id'])) {
- $clauses[] = "activity.activity_type_id = {$this->_formValues['activity_type_id']}";
- }
-
- $startDate = $this->_formValues['start_date'];
- if (!empty($startDate)) {
- $startDate .= '00:00:00';
- $startDateFormatted = CRM_Utils_Date::processDate($startDate);
- if ($startDateFormatted) {
- $clauses[] = "activity.activity_date_time >= $startDateFormatted";
- }
- }
-
- $endDate = $this->_formValues['end_date'];
- if (!empty($endDate)) {
- $endDate .= '23:59:59';
- $endDateFormatted = CRM_Utils_Date::processDate($endDate);
- if ($endDateFormatted) {
- $clauses[] = "activity.activity_date_time <= $endDateFormatted";
- }
- }
-
- if ($includeContactIDs) {
- $contactIDs = array();
- foreach ($this->_formValues as $id => $value) {
- if ($value &&
- substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX
- ) {
- $contactIDs[] = substr($id, CRM_Core_Form::CB_PREFIX_LEN);
- }
- }
-
- if (!empty($contactIDs)) {
- $contactIDs = implode(', ', $contactIDs);
- $clauses[] = "contact_a.id IN ( $contactIDs )";
- }
- }
-
- return implode(' AND ', $clauses);
- }
-
- /*
- * Functions below generally don't need to be modified
- */
-
- /**
- * @return mixed
- */
- function count() {
- $sql = $this->all();
-
- $dao = CRM_Core_DAO::executeQuery($sql);
- return $dao->N;
- }
-
- /**
- * @param int $offset
- * @param int $rowcount
- * @param null $sort
- *
- * @return string
- */
- function contactIDs($offset = 0, $rowcount = 0, $sort = NULL) {
- return $this->all($offset, $rowcount, $sort, FALSE, TRUE);
- }
-
- /**
- * @return array
- */
- function &columns() {
- return $this->_columns;
- }
-
- /**
- * @param $title
- */
- function setTitle($title) {
- if ($title) {
- CRM_Utils_System::setTitle($title);
- }
- else {
- CRM_Utils_System::setTitle(ts('Search'));
- }
- }
-
- /**
- * @return null
- */
- function summary() {
- return NULL;
- }
-}
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
- <extension key="org.civicrm.search.activity" type="search">
- <downloadUrl>http://svn.civicrm.org/tools/branches/v3.3/extensions/org.civicrm.search.activity.zip</downloadUrl>
- <file>ActivitySearch</file>
- <name>Activity Search</name>
- <description>This custom search allows to search through activities and returns activities as results (not contacts as regular search).</description>
- <urls>
- <url desc="Main Extension Page">http://civicrm.org</url>
- <url desc="Support">http://forum.civicrm.org</url>
- <url desc="Licensing">http://civicrm.org/licensing</url>
- </urls>
- <license>AGPL</license>
- <maintainer>
- <author>CiviCRM LLC</author>
- <email>info@civicrm.org</email>
- </maintainer>
- <releaseDate>2010-09-01</releaseDate>
- <version>1.2</version>
- <develStage>beta</develStage>
- <compatibility><ver>3.3</ver><ver>3.4</ver></compatibility>
- <comments>For support, please contact project team on the forums. (http://forum.civicrm.org)</comments>
-</extension>
+++ /dev/null
-{*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*}
-{* Template for "Sample" custom search component. *}
-<div class="crm-form-block crm-search-form-block">
-<div class="crm-accordion-wrapper crm-activity_search-accordion {if $rows}crm-accordion-closed{else}crm-accordion-open{/if}">
- <div class="crm-accordion-header crm-master-accordion-header">
- <div class="icon crm-accordion-pointer"></div>
- {ts}Edit Search Criteria{/ts}
-</div><!-- /.crm-accordion-header -->
-<div class="crm-accordion-body">
-<div id="searchForm" class="crm-block crm-form-block crm-contact-custom-search-activity-search-form-block">
- <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
- <table class="form-layout-compressed">
- {* Loop through all defined search criteria fields (defined in the buildForm() function). *}
- {foreach from=$elements item=element}
- <tr class="crm-contact-custom-search-activity-search-form-block-{$element}">
- <td class="label">{$form.$element.label}</td>
- <td>
- {if $element eq 'start_date' OR $element eq 'end_date'}
- {include file="CRM/common/jcalendar.tpl" elementName=$element}
- {else}
- {$form.$element.html}
- {/if}
- </td>
- </tr>
- {/foreach}
- </table>
- <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="bottom"}</div>
- </table>
-</div>
-</div><!-- /.crm-accordion-body -->
-</div><!-- /.crm-accordion-wrapper -->
-</div><!-- /.crm-form-block -->
-
-{if $rowsEmpty || $rows}
-
-<div class="crm-content-block">
- {if $rowsEmpty}
- <div class="crm-results-block crm-results-block-empty">
- {include file="CRM/Contact/Form/Search/Custom/EmptyResults.tpl"}
- </div>
-{/if}
-
-{if $rows}
- <div class="crm-results-block">
- {* Search request has returned 1 or more matching rows. Display results and collapse the search criteria fieldset. *}
-
- {* This section handles form elements for action task select and submit *}
- <div class="crm-search-tasks">
- {include file="CRM/Contact/Form/Search/ResultTasks.tpl"}
- </div>
- {* This section displays the rows along and includes the paging controls *}
- <div class="crm-search-results">
-
- {include file="CRM/common/pager.tpl" location="top"}
-
- {include file="CRM/common/pagerAToZ.tpl"}
-
- {strip}
- <table summary="{ts}Search results listings.{/ts}">
- <thead class="sticky">
- <th scope="col" title="Select All Rows">{$form.toggleSelect.html}</th>
- {foreach from=$columnHeaders item=header}
- {if ($header.sort eq 'activity_id') or ($header.sort eq 'activity_type_id') or ($header.sort eq 'case_id') }
- {elseif ($header.sort eq 'sort_name') or ($header.sort eq 'activity_status') or ($header.sort eq 'activity_type') or ($header.sort eq 'activity_subject') or ($header.sort eq 'source_contact') or ($header.SORT eq 'activity_date') or ($header.name eq null) }
- <th scope="col">
- {if $header.sort}
- {assign var='key' value=$header.sort}
- {$sort->_response.$key.link}
- {else}
- {$header.name}
- {/if}
- </th>
- {/if}
- </th>
- {/foreach}
- <th> </th>
- </thead>
-
- {counter start=0 skip=1 print=false}
- {foreach from=$rows item=row}
- <tr id='rowid{counter}' class="{cycle values="odd-row,even-row"}">
- {assign var=cbName value=$row.checkbox}
- <td>{$form.$cbName.html}</td>
- {foreach from=$columnHeaders item=header}
- {if ($header.sort eq 'sort_name') or ($header.sort eq 'activity_status') or ($header.sort eq 'activity_type') or ($header.sort eq 'activity_subject') or ($header.sort eq 'source_contact') or ($header.SORT eq 'activity_date') or ($header.name eq null) }
- {assign var=fName value=$header.sort}
- {if $fName eq 'sort_name'}
- <td><a href="{crmURL p='civicrm/contact/view' q="reset=1&cid=`$row.contact_id`"}">{$row.sort_name}</a></td>
- {elseif $fName eq 'activity_subject'}
- <td>
- {if $row.case_id }
- <a href="{crmURL p='civicrm/case/activity/view' q="reset=1&aid=`$row.activity_id`&cid=`$row.contact_id`&caseID=`$row.case_id`"}" title="{ts}View activity details{/ts}">
- {else}
- <a href="{crmURL p='civicrm/contact/view/activity' q="atype=`$row.activity_type_id`&action=view&reset=1&id=`$row.activity_id`&cid=`$row.contact_id`"}" title="{ts}View activity details{/ts}">
- {/if}
- {if isset($row.activity_subject) AND $row.activity_subject NEQ 'NULL'}{$row.activity_subject}{else}{ts}(no subject){/ts}{/if}</a>
- </td>
- {elseif ($fName eq 'activity_id') or ($fName eq 'activity_type_id') or ($fName eq 'case_id')}
- {else}
- <td>{$row.$fName}</td>
- {/if}
- {/if}
- {/foreach}
- <td>{$row.action}</td>
- </tr>
- {/foreach}
- </table>
- {/strip}
-
-{include file="CRM/common/pager.tpl" location="bottom"}
-
-
- </div>
- {* END Actions/Results section *}
- </div>
-{/if}
-</div>
-{/if}
+++ /dev/null
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-require_once 'CRM/Contact/Form/Search/Custom/Base.php';
-
-/**
- * Class org_civicrm_search_basic
- */
-class org_civicrm_search_basic extends CRM_Contact_Form_Search_Custom_BaseimplementsCRM_Contact_Form_Search_Interface {
-
- protected $_query;
-
- /**
- * @param $formValues
- */
- function __construct(&$formValues) {
- parent::__construct($formValues);
-
- $this->normalize();
- $this->_columns = array(
- '' => 'contact_type',
- '' => 'contact_sub_type',
- ts('Name') => 'sort_name',
- ts('Address') => 'street_address',
- ts('City') => 'city',
- ts('State') => 'state_province',
- ts('Postal') => 'postal_code',
- ts('Country') => 'country',
- ts('Email') => 'email',
- ts('Phone') => 'phone',
- );
-
- $params = &CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
- $returnProperties = array();
- foreach ($this->_columns as $name => $field) {
- $returnProperties[$field] = 1;
- }
-
- $this->_query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
- FALSE, FALSE, 1, FALSE, FALSE
- );
- }
-
- /**
- * normalize the form values to make it look similar to the advanced form values
- * this prevents a ton of work downstream and allows us to use the same code for
- * multiple purposes (queries, save/edit etc)
- *
- * @return void
- * @access private
- */
- function normalize() {
- $contactType = CRM_Utils_Array::value('contact_type', $this->_formValues);
- if ($contactType && !is_array($contactType)) {
- unset($this->_formValues['contact_type']);
- $this->_formValues['contact_type'][$contactType] = 1;
- }
-
- $group = CRM_Utils_Array::value('group', $this->_formValues);
- if ($group && !is_array($group)) {
- unset($this->_formValues['group']);
- $this->_formValues['group'][$group] = 1;
- }
-
- $tag = CRM_Utils_Array::value('tag', $this->_formValues);
- if ($tag && !is_array($tag)) {
- unset($this->_formValues['tag']);
- $this->_formValues['tag'][$tag] = 1;
- }
-
- return;
- }
-
- /**
- * @param CRM_Core_Form $form
- */
- function buildForm(&$form) {
-
- //@todo FIXME - using the CRM_Core_DAO::VALUE_SEPARATOR creates invalid html - if you can find the form
- // this is loaded onto then replace with something like '__' & test
- $separator = CRM_Core_DAO::VALUE_SEPARATOR;
- $contactTypes = array('' => ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, $separator);
- $form->add('select', 'contact_type', ts('Find...'), $contactTypes);
-
- // add select for groups
- $group = array('' => ts('- any group -')) + CRM_Core_PseudoConstant::group();
- $form->addElement('select', 'group', ts('in'), $group);
-
- // add select for categories
- $tag = array('' => ts('- any tag -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
- $form->addElement('select', 'tag', ts('Tagged'), $tag);
-
- // text for sort_name
- $form->add('text', 'sort_name', ts('Name'));
-
- $form->assign('elements', array('sort_name', 'contact_type', 'group', 'tag'));
- }
-
- /**
- * @return CRM_Contact_DAO_Contact
- */
- function count() {
- return $this->_query->searchQuery(0, 0, NULL, TRUE);
- }
-
- /**
- * @param int $offset
- * @param int $rowCount
- * @param null $sort
- * @param bool $includeContactIDs
- *
- * @return CRM_Contact_DAO_Contact
- */
- function all($offset = 0, $rowCount = 0, $sort = NULL,
- $includeContactIDs = FALSE
- ) {
- return $this->_query->searchQuery($offset, $rowCount, $sort,
- FALSE, $includeContactIDs,
- FALSE, FALSE, TRUE
- );
- }
-
- /**
- * @return string
- */
- function from() {
- return $this->_query->_fromClause;
- }
-
- /**
- * @param bool $includeContactIDs
- *
- * @return string
- */
- function where($includeContactIDs = FALSE) {
- if ($whereClause = $this->_query->whereClause()) {
- return $whereClause;
- }
- return ' (1) ';
- }
-
- /**
- * @return string
- */
- function templateFile() {
- return 'CRM/Contact/Form/Search/Basic.tpl';
- }
-}
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
- <extension key="org.civicrm.search.basic" type="search">
- <file>Basic</file>
- <name>Basic Search</name>
- <description>This custom search allows to search contacts through basic criteria like contact type, groups, tags.</description>
- <urls>
- <url desc="Main Extension Page">http://civicrm.org</url>
- <url desc="Support">http://forum.civicrm.org</url>
- <url desc="Licensing">http://civicrm.org/licensing</url>
- </urls>
- <license>AGPL</license>
- <maintainer>
- <author>CiviCRM LLC</author>
- <email>info@civicrm.org</email>
- </maintainer>
- <releaseDate>2010-09-01</releaseDate>
- <version>1.0</version>
- <develStage>beta</develStage>
- <compatibility><ver>3.3</ver><ver>3.4</ver></compatibility>
- <comments>For support, please contact project team on the forums. (http://forum.civicrm.org)</comments>
-</extension>
+++ /dev/null
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-require_once 'CRM/Contact/Form/Search/Custom/Base.php';
-
-/**
- * Class org_civicrm_search_multivalue
- */
-class org_civicrm_search_multivalue extends CRM_Contact_Form_Search_Custom_BaseimplementsCRM_Contact_Form_Search_Interface {
-
- protected $_groupTree;
- protected $_tables;
- protected $_options;
-
- /**
- * @param $formValues
- */
- function __construct(&$formValues) {
- parent::__construct($formValues);
-
- require_once 'CRM/Core/BAO/CustomGroup.php';
- $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree("'Contact', 'Individual', 'Organization', 'Household'",
- CRM_Core_DAO::$_nullObject,
- NULL, -1
- );
-
- $this->_columns = array(ts('Contact ID') => 'contact_id',
- ts('Contact Type') => 'contact_type',
- ts('Name') => 'sort_name',
- );
-
- $this->_customGroupIDs = CRM_Utils_Array::value('custom_group', $formValues);
-
- if (!empty($this->_customGroupIDs)) {
- $this->addColumns();
- }
- }
-
- function addColumns() {
- // add all the fields for chosen groups
- $this->_tables = $this->_options = array();
- foreach ($this->_groupTree as $groupID => $group) {
- if (empty($this->_customGroupIDs[$groupID])) {
- continue;
- }
-
- // now handle all the fields
- foreach ($group['fields'] as $fieldID => $field) {
- $this->_columns[$field['label']] = "custom_{$field['id']}";
- if (!array_key_exists($group['table_name'], $this->_tables)) {
- $this->_tables[$group['table_name']] = array();
- }
- $this->_tables[$group['table_name']][$field['id']] = $field['column_name'];
-
- // also build the option array
- $this->_options[$field['id']] = array();
- CRM_Core_BAO_CustomField::buildOption($field,
- $this->_options[$field['id']]
- );
- }
- }
- }
-
- /**
- * @param CRM_Core_Form $form
- */
- function buildForm(&$form) {
-
- /**
- * You can define a custom title for the search form
- */
- $this->setTitle('Multiple Value Custom Group Search and Export');
-
- $form->add('text',
- 'sort_name',
- ts('Contact Name'),
- TRUE
- );
- if (empty($this->_groupTree)) {
- CRM_Core_Error::statusBounce(ts("At least one Custom Group must be present, for Custom Group search."),
- CRM_Utils_System::url('civicrm/contact/search/custom/list',
- 'reset=1'
- )
- );
- }
- // add the checkbox for custom_groups
- foreach ($this->_groupTree as $groupID => $group) {
- if ($groupID == 'info') {
- continue;
- }
- $form->addElement('checkbox', "custom_group[$groupID]", NULL, $group['title']);
- }
- }
-
- /**
- * @return null
- */
- function summary() {
- return NULL;
- }
-
- /**
- * @param int $offset
- * @param int $rowcount
- * @param null $sort
- * @param bool $includeContactIDs
- *
- * @return mixed
- */
- function all($offset = 0, $rowcount = 0, $sort = NULL,
- $includeContactIDs = FALSE
- ) {
- //redirect if custom group not select in search criteria
- if (empty($this->_formValues['custom_group'])) {
- CRM_Core_Error::statusBounce(ts("You must select at least one Custom Group as a search criteria."),
- CRM_Utils_System::url('civicrm/contact/search/custom',
- "reset=1&csid={$this->_formValues['customSearchID']}",
- FALSE, NULL, FALSE, TRUE
- )
- );
- }
- $selectClause = "
-contact_a.id as contact_id ,
-contact_a.contact_type as contact_type,
-contact_a.sort_name as sort_name,
-";
-
- $customClauses = array();
- foreach ($this->_tables as $tableName => $fields) {
- foreach ($fields as $fieldID => $fieldName) {
- $customClauses[] = "{$tableName}.{$fieldName} as custom_{$fieldID}";
- }
- }
- $selectClause .= implode(',', $customClauses);
-
- return $this->sql($selectClause,
- $offset, $rowcount, $sort,
- $includeContactIDs, NULL
- );
- }
-
- /**
- * @return string
- */
- function from() {
- $from = "FROM civicrm_contact contact_a";
- $customFrom = array();
- if (!empty($this->_tables)) {
- foreach ($this->_tables as $tableName => $fields) {
- $customFrom[] = " LEFT JOIN $tableName ON {$tableName}.entity_id = contact_a.id ";
- }
- return $from . implode(' ', $customFrom);
- }
- return $from;
- }
-
- /**
- * @param bool $includeContactIDs
- *
- * @return mixed
- */
- function where($includeContactIDs = FALSE) {
- $count = 1;
- $clause = array();
- $params = array();
- $name = CRM_Utils_Array::value('sort_name',
- $this->_formValues
- );
- if ($name != NULL) {
- if (strpos($name, '%') === FALSE) {
- $name = "%{$name}%";
- }
- $params[$count] = array($name, 'String');
- $clause[] = "contact_a.sort_name LIKE %{$count}";
- $count++;
- }
-
- $where = '( 1 )';
- if (!empty($clause)) {
- $where .= ' AND ' . implode(' AND ', $clause);
- }
-
- return $this->whereClause($where, $params);
- }
-
- /**
- * @return string
- */
- function templateFile() {
- return 'MultipleValues.tpl';
- }
-
- /**
- * @return array
- */
- function setDefaultValues() {
- return array();
- }
-
- /**
- * @param $row
- */
- function alterRow(&$row) {
- foreach ($this->_options as $fieldID => $values) {
- $customVal = $valueSeparatedArray = array();
- if (in_array($values['attributes']['html_type'],
- array('Radio', 'Select', 'Autocomplete-Select')
- )) {
- if ($values['attributes']['data_type'] == 'ContactReference' && $row["custom_{$fieldID}"]) {
- $row["custom_{$fieldID}"] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', (int)$row["custom_{$fieldID}"], 'display_name');
- }
- elseif ($row["custom_{$fieldID}"] &&
- array_key_exists($row["custom_{$fieldID}"],
- $values
- )
- ) {
- $row["custom_{$fieldID}"] = $values[$row["custom_{$fieldID}"]];
- }
- }
- elseif (in_array($values['attributes']['html_type'],
- array('CheckBox', 'Multi-Select', 'AdvMulti-Select')
- )) {
- $valueSeparatedArray = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $row["custom_{$fieldID}"]));
- foreach ($valueSeparatedArray as $val) {
- $customVal[] = $values[$val];
- }
- $row["custom_{$fieldID}"] = implode(', ', $customVal);
- }
- elseif (in_array($values['attributes']['html_type'],
- array('Multi-Select State/Province', 'Select State/Province')
- )) {
- $valueSeparatedArray = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $row["custom_{$fieldID}"]));
- $stateName = CRM_Core_PseudoConstant::stateProvince();
- foreach ($valueSeparatedArray as $val) {
- $customVal[] = $stateName[$val];
- }
- $row["custom_{$fieldID}"] = implode(', ', $customVal);
- }
- elseif (in_array($values['attributes']['html_type'],
- array('Multi-Select Country', 'Select Country')
- )) {
- $valueSeparatedArray = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $row["custom_{$fieldID}"]));
- CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country',
- TRUE, 'name', 'is_active'
- );
- foreach ($valueSeparatedArray as $val) {
- $customVal[] = $countryNames[$val];
- }
- $row["custom_{$fieldID}"] = implode(', ', $customVal);
- }
- }
- }
-
- /**
- * @param $title
- */
- function setTitle($title) {
- CRM_Utils_System::setTitle($title);
- }
-}
-
+++ /dev/null
-<?xml version="1.0" encoding="iso-8859-1" ?>
- <extension key="org.civicrm.search.multivalue" type="search">
- <downloadUrl>http://svn.civicrm.org/tools/branches/v3.3/extensions/org.civicrm.search.multivalue.zip</downloadUrl>
- <file>MultiValue</file>
- <name>Multiple Values Search</name>
- <description>desc</description>
- <urls>
- <url desc="Main Extension Page">http://civicrm.org</url>
- <url desc="Documentation">http://wiki.civicrm.org/confluence/display/CRMDOC32/Google+Checkout+Configuration</url>
- <url desc="Support">http://forum.civicrm.org</url>
- <url desc="Licensing">http://civicrm.org/licensing</url>
- </urls>
- <license>AGPL</license>
- <maintainer>
- <author>CiviCRM LLC</author>
- <email>info@civicrm.org</email>
- </maintainer>
- <releaseDate>2010-09-01</releaseDate>
- <version>1.1</version>
- <develStage>beta</develStage>
- <compatibility><ver>3.3</ver><ver>3.4</ver></compatibility>
- <comments>For support, please contact project team on the forums. (http://forum.civicrm.org)</comments>
-</extension>
+++ /dev/null
-{*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License and the CiviCRM Licensing Exception along |
- | with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*}
-{* Template for "Sample" custom search component. *}
-{assign var="showBlock" value="'searchForm'"}
-{assign var="hideBlock" value="'searchForm_show','searchForm_hide'"}
-
-<div id="searchForm_show" class="form-item">
- <a href="#" onclick="hide('searchForm_show'); show('searchForm'); return false;"><img src="{$config->resourceBase}i/TreePlus.gif" class="action-icon" alt="{ts}open section{/ts}" /></a>
- <label>{ts}Edit Search Criteria{/ts}</label>
-</div>
-
-<div id="searchForm" class="crm-block crm-form-block crm-contact-custom-search-multipleValues-form-block">
- <fieldset>
- <legend><span id="searchForm_hide"><a href="#" onclick="hide('searchForm','searchForm_hide'); show('searchForm_show'); return false;"><img src="{$config->resourceBase}i/TreeMinus.gif" class="action-icon" alt="{ts}close section{/ts}" /></a></span>{ts}Search Criteria{/ts}</legend>
- <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
- <table class="form-layout-compressed">
- <tr class="crm-contact-custom-search-multipleValues-form-block-sort_name">
- <td><label>{$form.sort_name.label}</label></td>
- <td>{$form.sort_name.html}</td>
- </tr>
- {* Choose regular or 'tall' listing-box class for Group select box based on # of groups. *}
- {if $form.custom_group|@count GT 8}
- {assign var="boxClass" value="listing-box-tall"}
- {else}
- {assign var="boxClass" value="listing-box"}
- {/if}
- <tr class="crm-contact-custom-search-multipleValues-form-block-custom_group">
- <td><label>{ts}Group(s){/ts}</label></td>
- <td>
- <div class="{$boxClass}">
- {foreach from=$form.custom_group item="group_val"}
- <div class="{cycle values="even-row,odd-row"}">
- {$group_val.html}
- </div>
- {/foreach}
- </div>
- </td>
- </tr>
- </table>
- <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="bottom"}</div>
- </fieldset>
-</div>
-
-{if $rowsEmpty}
- {include file="CRM/Contact/Form/Search/Custom/EmptyResults.tpl"}
-{/if}
-
-{if $summary}
- {$summary.summary}: {$summary.total}
-{/if}
-
-{if $rows}
- {* Search request has returned 1 or more matching rows. Display results and collapse the search criteria fieldset. *}
- {assign var="showBlock" value="'searchForm_show'"}
- {assign var="hideBlock" value="'searchForm'"}
-
- <fieldset>
-
- {* This section handles form elements for action task select and submit *}
- {include file="CRM/Contact/Form/Search/ResultTasks.tpl"}
-
- {* This section displays the rows along and includes the paging controls *}
- <p>
-
- {include file="CRM/common/pager.tpl" location="top"}
-
- {include file="CRM/common/pagerAToZ.tpl"}
-
- {strip}
- <table class="selector" summary="{ts}Search results listings.{/ts}">
- <thead class="sticky">
- <th scope="col" title="Select All Rows">{$form.toggleSelect.html}</th>
- {foreach from=$columnHeaders item=header}
- <th scope="col">
- {if $header.sort}
- {assign var='key' value=$header.sort}
- {$sort->_response.$key.link}
- {else}
- {$header.name}
- {/if}
- </th>
- {/foreach}
- <th> </th>
- </thead>
-
- {counter start=0 skip=1 print=false}
- {foreach from=$rows item=row}
- <tr id='rowid{$row.contact_id}' class="{cycle values="odd-row,even-row"}">
- {assign var=cbName value=$row.checkbox}
- <td>{$form.$cbName.html}</td>
- {foreach from=$columnHeaders item=header}
- {assign var=fName value=$header.sort}
- {if $fName eq 'sort_name'}
- <td><a href="{crmURL p='civicrm/contact/view' q="reset=1&cid=`$row.contact_id`"}">{$row.sort_name}</a></td>
- {else}
- <td>{$row.$fName}</td>
- {/if}
- {/foreach}
- <td>{$row.action}</td>
- </tr>
- {/foreach}
- </table>
- {/strip}
-
- {include file="CRM/common/pager.tpl" location="bottom"}
-
- </p>
- </fieldset>
- {* END Actions/Results section *}
-{/if}
-
-<script type="text/javascript">
- var showBlock = new Array({$showBlock});
- var hideBlock = new Array({$hideBlock});
-
- {* hide and display the appropriate blocks *}
- on_load_init_blocks( showBlock, hideBlock );
-</script>
-
+++ /dev/null
-<?php
-/**
- * @param $query
- *
- * @return array
- */
-function compare($query) { $compares = array();
-$result = mysql_query($query);
-while ($row = mysql_fetch_object($result)) {
- if (!$_GET['current'] and $row->year == date('Y') and $row->month == date('m')) {
- continue;
- }$data[$row->month . '’' . substr($row->year, 2)][$row->compare] = $row->data;
- $compares[] = $row->compare;
- }
- $compares = array_unique($compares);
- sort($compares);
-
- $keys = array_keys($data);
- $key = $keys[count($data) - 1];
- $recent = array_pop($data);
- $data = array_merge($data, array($key => $recent));
-
- foreach ($data as $label => $values) {
- foreach ($values as $compare => $value) {
- $data[$label][$compare] = round($value / array_sum($values) * 100, 1);
- }
- }
-
- $lines = array();
- foreach (array_keys($data) as $label) {
- $rolling = 0;
- foreach ($compares as $compare) {
- $rolling += $data[$label][$compare];
- $lines[$compare][$label] = $rolling;
- }
- }
-
- foreach ($lines as $line => $values) $lines[$line] = implode(',', $values);
-
- $colours = array();
- while (count($colours) < count($compares)) {
- $colours[] = str_pad(dechex(rand(0, 16777215)), 6, '0', STR_PAD_LEFT);
- }
-
- $fill = array();
- foreach ($colours as $i => $colour) {
- $j = $i + 1;
- $fill[] = "b,$colour,$i,$j,0";
- }
-
- $params = array(
- 'chs' => '500x200',
- 'cht' => 'lc',
- 'chd' => 't:0,0|' . implode('|', $lines),
- 'chm' => implode('|', $fill),
- 'chco' => '00000000',
- 'chxt' => 'x,y',
- 'chxl' => '0:|' . implode('|', array_keys($data)) . '|1:|0%|25%|50%|75%|100%',
- );
-
- $trend = 'http://chart.apis.google.com/chart?';
- foreach ($params as $key => $value) $trend .= "&{$key}={$value}";
-
- $last = array();
- $tail = array_pop($data);
- foreach ($compares as $compare) {
- $last[$compare] = $tail[$compare] ? $tail[$compare] : 0;
- }
-
- $labels = array();
- foreach ($last as $label => $value) {
- $lab = $label ? $label : 'unknown';
- $num = $recent[$label] ? $recent[$label] : 0;
- $labels[] = "$lab ($num, {$value}%)";
- }
-
- $params = array(
- 'chs' => '450x200',
- 'cht' => 'p',
- 'chd' => 't:' . implode(',', $last),
- 'chl' => implode('|', $labels),
- 'chco' => implode(',', $colours),
- );
-
- $pie = 'http://chart.apis.google.com/chart?';
- foreach ($params as $key => $value) $pie .= "&{$key}={$value}";
-
- return array('url' => $trend, 'last' => $pie);
-}
-
-/**
- * @param $query
- *
- * @return array
- */
-function trend($query) {
- $data = array();
- $result = mysql_query($query);
- while ($row = mysql_fetch_object($result)) {
- if (!$_GET['current'] and $row->year == date('Y') and $row->month == date('m')) {
- continue;
- }
- $data[$row->month . '’' . substr($row->year, 2)] = $row->data;
- }
-
- $max = max($data);
-
- $params = array(
- 'chs' => '500x200',
- 'cht' => 'lc',
- 'chd' => 't:' . implode(',', $data),
- 'chds' => '0,' . $max,
- 'chxt' => 'x,y',
- 'chxl' => '0:|' . implode('|', array_keys($data)) . '|1:|0|' . implode('|', array($max * 0.25, $max * 0.5, $max * 0.75, $max)),
- );
-
- $url = 'http://chart.apis.google.com/chart?';
- foreach ($params as $key => $value) $url .= "&{$key}={$value}";
- return array('url' => $url, 'last' => array_pop($data));
-}
-
+++ /dev/null
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
- <title>CiviCRM usage statistics</title>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <meta http-equiv="Content-Language" content="en" />
- <meta name="Author" content="Piotr Szotkowski" />
-</head>
-<body>
-<h1>CiviCRM usage statistics</h1>
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License along with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-$user = $pass = FALSE;
-require_once 'config.php';
-mysql_connect('localhost', $user, $pass);
-mysql_select_db('stats');
-
-require_once 'graphs.php';
-
-$charts = array(
- array('title' => 'Distinct installations',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month FROM stats GROUP BY year, month ORDER BY year, month',
- 'type' => 'trend',
- ),
- array('title' => 'UF usage',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, uf compare FROM stats GROUP BY year, month, uf ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'CiviCRM versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(version, 1, 3) compare FROM stats WHERE version LIKE "_.%" GROUP BY year, month, SUBSTR(version, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'Drupal versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(ufv, 1, 1) compare FROM stats WHERE uf = "Drupal" GROUP BY year, month, SUBSTR(ufv, 1, 1) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'Joomla versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(ufv, 1, 3) compare FROM stats WHERE uf = "Joomla" GROUP BY year, month, SUBSTR(ufv, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'MySQL versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(MySQL, 1, 3) compare FROM stats GROUP BY year, month, SUBSTR(MySQL, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'PHP versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(PHP, 1, 3) compare FROM stats GROUP BY year, month, SUBSTR(PHP, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'Default languages',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, lang compare FROM stats GROUP BY year, month, lang ORDER BY year, month',
- 'type' => 'compare',
- ),
-);
-
-switch ($_GET['current']) {
- case FALSE:
- print '<p><a href="?current=1">include partial data for current month</a></p>';
- break;
-
- case TRUE:
- print '<p><a href="?">drop partial data for current month</a></p>';
- break;
-}
-
-// $fields = array('Activity', 'Case', 'Contact', 'Contribution', 'ContributionPage', 'ContributionProduct', 'Discount', 'Event', 'Friend', 'Grant', 'Mailing', 'Membership', 'MembershipBlock', 'Participant', 'Pledge', 'PledgeBlock', 'PriceSetEntity', 'Relationship', 'UFGroup', 'Widget');
-
-$fields = array('Contact' => array('skip' => array(102),
- 'min' => 10,
- ),
- 'Contribution' => array('skip' => array(13), 'min' => 10),
- 'ContributionPage' => array('skip' => array(3), 'min' => 0),
- 'Membership' => array('skip' => array(30), 'min' => 10),
- 'MembershipBlock' => array('skip' => array(1), 'min' => 0),
- 'Pledge' => array('skip' => array(3), 'min' => 0),
- 'Friend' => array('skip' => array(2), 'min' => 0),
- 'Event' => array('skip' => array(3), 'min' => 0),
- 'Participant' => array('skip' => array(50), 'min' => 10),
- 'Mailing' => array('skip' => NULL, 'min' => 3),
- 'Case' => array('skip' => NULL, 'min' => 5),
- 'UFGroup' => array('skip' => array(1), 'min' => 0),
-);
-
-
-
-print '<p>jump to comonent stats: ';
-foreach ($fields as $field => $dontCare) print "<a href='#$field'>$field</a> ";
-print '</p>';
-
-/**
- foreach ($charts as $chart) {
- switch ($chart['type']) {
- case 'trend':
- $result = trend($chart['query']);
- print "<h2>{$chart['title']} (last: {$result['last']})</h2>";
- print "<p><img src='{$result['url']}' /></p>"; break;
- case 'compare':
- $result = compare($chart['query']);
- print "<h2>{$chart['title']}</h2>";
- print "<p><img src='{$result['url']}' /> <img src='{$result['last']}' /></p>"; break;
- }
- }
- **/
-
-$year = date('Y');
-$month = date('n');
-
-if (!$_GET['current']) {
- $month--;
- if ($month == 0) {
- $year--;
- $month = 12;
- }
-}
-
-// mysql_query("CREATE TEMPORARY TABLE latest_ids SELECT MAX(id) id FROM stats WHERE YEAR(time) = $year AND MONTH(time) = $month GROUP BY hash");
-mysql_query("CREATE TEMPORARY TABLE latest_ids SELECT MAX(id) id FROM stats WHERE substr(version,1,3) = '2.1' GROUP BY hash");
-mysql_query('CREATE INDEX latest_ids_id ON latest_ids (id)');
-mysql_query('CREATE TEMPORARY TABLE latest_stats SELECT * FROM stats WHERE id IN (SELECT * FROM latest_ids)');
-foreach ($fields as $field => $dontCare) {
- mysql_query("CREATE INDEX latest_stats_$field ON latest_stats (`$field`)");
-}
-
-foreach ($fields as $field => $values) {
- print "<h2 id='$field'>$field</h2>";
-
- $clauses = array("( `$field` IS NOT NULL )");
-
- if ($values['skip']) {
- $skip = implode(',', $values['skip']);
- $clauses[] = "( `$field` NOT IN ( $skip ) )";
- }
-
- if ($values['min']) {
- $clauses[] = "( `$field` > {$values['min']} )";
- }
- else {
- $clauses[] = "( `$field` > 0 )";
- }
- $clause = implode(' AND ', $clauses);
-
- $total = mysql_fetch_object(mysql_query("SELECT COUNT(*) count FROM latest_stats WHERE $clause"));
- $total = $total->count;
- print "Total: $total<p>";
-
- $tops = mysql_query("SELECT `$field` field, COUNT(*) count FROM latest_stats WHERE $clause GROUP BY field ORDER BY count DESC LIMIT 5");
- print '<p>five most popular counts: ';
- $first = $second = NULL;
- while ($top = mysql_fetch_object($tops)) {
- if ($first !== NULL and $second === NULL) {
- $second = $top->field;
- }
- if ($first === NULL) {
- $first = $top->field;
- }
- print "{$top->field} " . strtolower($field) . "s ({$top->count} installs), ";
- }
- print '</p>';
-
- $stat = mysql_fetch_object(mysql_query("SELECT MAX(`$field`) max, ROUND(AVG(`$field`)) avg FROM latest_stats"));
- print "<h3>$field with all counts – max: {$stat->max}, avg: {$stat->avg}</h3>";
- print '<table><tr><th>low</th><th>high</th><th>count</th></tr>';
-
- $high = -1;
- $pieces = 20;
- $lowCount = round($total / ($pieces + 2));
- $highCount = round($total / ($pieces - 2));
- for ($i = 1; $i <= $pieces; $i++) {
- $low = $high + 1;
- $high = round($i * $stat->max / $pieces);
-
- $loop = 0;
- while (1) {
- $count = mysql_fetch_object(mysql_query("SELECT COUNT(*) count FROM latest_stats WHERE `$field` BETWEEN $low AND $high AND $clause"));
- $currentCount = $count->count;
- if ($currentCount >= $lowCount &&
- $currentCount <= $highCount
- ) {
- break;
- }
- // echo "$currentCount, $lowCount, $highCount, $low, $high<p>";
-
- if ($currentCount < $lowCount) {
- $high = round($high + ($high - $low) / 2);
- if ($high > $stat->max) {
- $high = $stat->max;
- }
- }
-
- if ($currentCount > $highCount) {
- $high = round($low + ($high - $low) / 2);
- }
-
- $loop++;
- if ($loop > 20) {
- break;
- }
- }
- // echo "RESULT: $low, $high, $currentCount<p>";
-
- if ($currentCount) {
- print "<tr style='text-align: right'><td>$low</td><td>$high</td><td>$currentCount</td></tr>";
- }
- }
- print '</table>';
-}
-
-?>
-</body>
-</html>
-
+++ /dev/null
-User-agent: *
-Disallow: /
+++ /dev/null
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
- <title>CiviCRM usage statistics</title>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <meta http-equiv="Content-Language" content="en" />
- <meta name="Author" content="Piotr Szotkowski" />
-</head>
-<body>
-<h1>CiviCRM usage statistics</h1>
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015 |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM. |
- | |
- | CiviCRM is free software; you can copy, modify, and distribute it |
- | under the terms of the GNU Affero General Public License |
- | Version 3, 19 November 2007. |
- | |
- | CiviCRM is distributed in the hope that it will be useful, but |
- | WITHOUT ANY WARRANTY; without even the implied warranty of |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
- | See the GNU Affero General Public License for more details. |
- | |
- | You should have received a copy of the GNU Affero General Public |
- | License along with this program; if not, contact CiviCRM LLC |
- | at info[AT]civicrm[DOT]org. If you have questions about the |
- | GNU Affero General Public License or the licensing of CiviCRM, |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing |
- +--------------------------------------------------------------------+
-*/
-
-/**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
- * $Id$
- *
- */
-
-$user = $pass = FALSE;
-require_once 'config.php';
-mysql_connect('localhost', $user, $pass);
-mysql_select_db('stats');
-
-require_once 'graphs.php';
-
-$charts = array(
- array('title' => 'Distinct installations',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month FROM stats GROUP BY year, month ORDER BY year, month',
- 'type' => 'trend',
- ),
- array('title' => 'UF usage',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, uf compare FROM stats GROUP BY year, month, uf ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'CiviCRM versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(version, 1, 3) compare FROM stats WHERE version LIKE "_.%" GROUP BY year, month, SUBSTR(version, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'Drupal versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(ufv, 1, 1) compare FROM stats WHERE uf = "Drupal" GROUP BY year, month, SUBSTR(ufv, 1, 1) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'Joomla versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(ufv, 1, 3) compare FROM stats WHERE uf = "Joomla" GROUP BY year, month, SUBSTR(ufv, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'MySQL versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(MySQL, 1, 3) compare FROM stats GROUP BY year, month, SUBSTR(MySQL, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'PHP versions',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, SUBSTR(PHP, 1, 3) compare FROM stats GROUP BY year, month, SUBSTR(PHP, 1, 3) ORDER BY year, month',
- 'type' => 'compare',
- ),
- array('title' => 'Default languages',
- 'query' => 'SELECT COUNT(DISTINCT hash) data, YEAR(time) year, MONTH(time) month, lang compare FROM stats GROUP BY year, month, lang ORDER BY year, month',
- 'type' => 'compare',
- ),
-);
-
-switch ($_GET['current']) {
- case FALSE:
- print '<p><a href="?current=1">include partial data for current month</a></p>';
- break;
-
- case TRUE:
- print '<p><a href="?">drop partial data for current month</a></p>';
- break;
-}
-
-$fields = array('Activity', 'Case', 'Contact', 'Contribution', 'ContributionPage', 'ContributionProduct', 'Discount', 'Event', 'Friend', 'Grant', 'Mailing', 'Membership', 'MembershipBlock', 'Participant', 'Pledge', 'PledgeBlock', 'PriceSetEntity', 'Relationship', 'UFGroup', 'Widget');
-
-print '<p>jump to comonent stats: ';
-foreach ($fields as $field) print "<a href='#$field'>$field</a> ";
-print '</p>';
-
-foreach ($charts as $chart) {
- switch ($chart['type']) {
- case 'trend':
- $result = trend($chart['query']);
- print "<h2>{$chart['title']} (last: {$result['last']})</h2>";
- print "<p><img src='{$result['url']}' /></p>";
- break;
-
- case 'compare':
- $result = compare($chart['query']);
- print "<h2>{$chart['title']}</h2>";
- print "<p><img src='{$result['url']}' /> <img src='{$result['last']}' /></p>";
- break;
- }
-}
-
-$year = date('Y');
-$month = date('n');
-
-if (!$_GET['current']) {
- $month--;
- if ($month == 0) {
- $year--;
- $month = 12;
- }
-}
-
-mysql_query("CREATE TEMPORARY TABLE latest_ids SELECT MAX(id) id FROM stats WHERE YEAR(time) = $year AND MONTH(time) = $month GROUP BY hash");
-mysql_query('CREATE INDEX latest_ids_id ON latest_ids (id)');
-mysql_query('CREATE TEMPORARY TABLE latest_stats SELECT * FROM stats WHERE id IN (SELECT * FROM latest_ids)');
-foreach ($fields as $field) {
- mysql_query("CREATE INDEX latest_stats_$field ON latest_stats (`$field`)");
-}
-
-foreach ($fields as $field) {
- print "<h2 id='$field'>$field</h2>";
-
- $clauses = array("( `$field` IS NOT NULL )");
- $clauses[] = "( `$field` > 0 )";
- $clause = implode(' AND ', $clauses);
-
- $totals = mysql_query("SELECT COUNT(*) count FROM latest_stats WHERE $clause");
- while ($total = mysql_fetch_object($totals)) {
- print "Total: {$total->count}<p>";
- }
-
- $tops = mysql_query("SELECT `$field` field, COUNT(*) count FROM latest_stats WHERE $clause GROUP BY field ORDER BY count DESC LIMIT 5");
- print '<p>five most popular counts: ';
- $first = $second = NULL;
- while ($top = mysql_fetch_object($tops)) {
- if ($first !== NULL and $second === NULL) {
- $second = $top->field;
- }
- if ($first === NULL) {
- $first = $top->field;
- }
- print "{$top->field} " . strtolower($field) . "s ({$top->count} installs), ";
- }
- print '</p>';
-
- $stat = mysql_fetch_object(mysql_query("SELECT MAX(`$field`) max, ROUND(AVG(`$field`)) avg FROM latest_stats"));
- print "<h3>$field with all counts – max: {$stat->max}, avg: {$stat->avg}</h3>";
- print '<table><tr><th colspan="4">range</th><th>count</th></tr>';
- $high = -1;
- $pieces = $stat->max > 100 ? 100 : $stat->max;
- for ($i = 1; $i <= $pieces; $i++) {
- $low = $high + 1;
- $high = round($i * $stat->max / $pieces);
- $count = mysql_fetch_object(mysql_query("SELECT COUNT(*) count FROM latest_stats WHERE `$field` BETWEEN $low AND $high AND $clause"));
- if ($count->count) {
- print "<tr style='text-align: right'><td>$low</td><td>–</td><td>$high</td><td>(" . $i * 100 / $pieces . "%)</td><td>$count->count</td></tr>";
- }
- }
- print '</table>';
-
- $stat = mysql_fetch_object(mysql_query("SELECT MAX(`$field`) max, ROUND(AVG(`$field`)) avg FROM latest_stats WHERE `$field` != $first"));
- print "<h3>$field sans the $first count – max: {$stat->max}, avg: {$stat->avg}</h3>";
- print '<table><tr><th colspan="4">range</th><th>count</th></tr>';
- $high = -1;
- $pieces = $stat->max > 100 ? 100 : $stat->max;
- for ($i = 1; $i <= $pieces; $i++) {
- $low = $high + 1;
- $high = round($i * $stat->max / $pieces);
- $count = mysql_fetch_object(mysql_query("SELECT COUNT(*) count FROM latest_stats WHERE `$field` BETWEEN $low AND $high AND `$field` != $first"));
- if ($count->count) {
- print "<tr style='text-align: right'><td>$low</td><td>–</td><td>$high</td><td>(" . $i * 100 / $pieces . "%)</td><td>$count->count</td></tr>";
- }
- }
- print '</table>';
-
- $stat = mysql_fetch_object(mysql_query("SELECT MAX(`$field`) max, ROUND(AVG(`$field`)) avg FROM latest_stats WHERE `$field` != $first AND `$field` != $second"));
- print "<h3>$field sans the $first and $second counts – max: {$stat->max}, avg: {$stat->avg}</h3>";
- print '<table><tr><th colspan="4">range</th><th>count</th></tr>';
- $high = -1;
- $pieces = $stat->max > 100 ? 100 : $stat->max;
- for ($i = 1; $i <= $pieces; $i++) {
- $low = $high + 1;
- $high = round($i * $stat->max / $pieces);
- $count = mysql_fetch_object(mysql_query("SELECT COUNT(*) count FROM latest_stats WHERE `$field` BETWEEN $low AND $high AND `$field` != $first AND `$field` != $second"));
- if ($count->count) {
- print "<tr style='text-align: right'><td>$low</td><td>–</td><td>$high</td><td>(" . $i * 100 / $pieces . "%)</td><td>$count->count</td></tr>";
- }
- }
- print '</table>';
-}
-
-?>
-</body>
-</html>
-
+++ /dev/null
-<html>
-<body>
-<h1>CiviCRM test reports site</h1>
-<ul>
-<li>Test result reports</li>
-<ul>
-<li><a href="results-Web">Webtest results report</a></li>
-<li><a href="results-CRM">BAO results report</a></li>
-<li><a href="results-api_v2">API v2 results report</a></li>
-<li><a href="results-api_v3">API v3 results report</a></li>
-</ul>
-</body>
-</html>
\ No newline at end of file