Commit 66df13c9 authored by everykittysdaydream's avatar everykittysdaydream

Merge branch 'master' of https://github.com/4ndygu/civicrm_osdi

parents 875ccc25 7b3bcd46
<?php
/**
 * This is a helper class for the queue functionality.
 * It is a singleton class because it will hold the queue object for our extension
 *
 *
 */
*  * This is a helper class for the queue functionality.
*  * It is a singleton class because it will hold the queue object for our extension
*  *
*  *
 .*/
/*foreach (glob(__DIR__ . '/../../../../CRM/Core/*.php') as $filename)
{
require_once $filename;
}*/
/*set_include_path(get_include_path() . PATH_SEPARATOR . "/home/student/buildkit/build/my-drupal-civi47/sites/all/modules/civicrm");
require_once __DIR__ . '/../../../../CRM/Core/DAO.php';
foreach (glob(__DIR__ . '/../../../../CRM/Queue/*.php') as $filename)
{
require_once $filename;
}*/
//eval(`cv php:boot`);
class CRM_OSDIQueue_Helper
{
const QUEUE_NAME = 'com.civicrm.osdiqueue';
private $queue;
static $singleton;
private function __construct()
{
$this->queue = CRM_Queue_Service::singleton()->create(array(
'type' => 'Sql',
'name' => self::QUEUE_NAME,
'reset' => false, //do not flush queue upon creation
));
/**
*
*/
class CRM_OSDIQueue_Helper {
const QUEUE_NAME = 'com.civicrm.osdiqueue';
private $queue;
static $singleton;
/**
*
*/
private function __construct() {
$this->queue = CRM_Queue_Service::singleton()->create(array(
'type' => 'Sql',
'name' => self::QUEUE_NAME,
// Do not flush queue upon creation.
'reset' => FALSE,
));
}
/**
*
*/
public static function singleton() {
if (!self::$singleton) {
self::$singleton = new CRM_OSDIQueue_Helper();
}
return self::$singleton;
}
public static function singleton() {
if (!self::$singleton) self::$singleton = new CRM_OSDIQueue_Helper();
return self::$singleton;
}
/**
*
*/
public function getQueue() {
return $this->queue;
}
public function getQueue()
{
return $this->queue;
}
}
?>
This diff is collapsed.
<?php
return array(
'AL' => 'Alabama',
'AK' => 'Alaska',
'AZ' => 'Arizona',
'AR' => 'Arkansas',
'CA' => 'California',
'CO' => 'Colorado',
'CT' => 'Connecticut',
'DE' => 'Delaware',
'DC' => 'Washington DC',
'FL' => 'Florida',
'GA' => 'Georgia',
'HI' => 'Hawaii',
'ID' => 'Idaho',
'IL' => 'Illinois',
'IN' => 'Indiana',
'IA' => 'Iowa',
'KS' => 'Kansas',
'KY' => 'Kentucky',
'LA' => 'Louisiana',
'ME' => 'Maine',
'MD' => 'Maryland',
'MA' => 'Massachusetts',
'MI' => 'Michigan',
'MN' => 'Minnesota',
'MS' => 'Mississippi',
'MO' => 'Missouri',
'MT' => 'Montana',
'NE' => 'Nebraska',
'NV' => 'Nevada',
'NH' => 'New Hampshire',
'NJ' => 'New Jersey',
'NM' => 'New Mexico',
'NY' => 'New York',
'NC' => 'North Carolina',
'ND' => 'North Dakota',
'OH' => 'Ohio',
'OK' => 'Oklahoma',
'OR' => 'Oregon',
'PA' => 'Pennsylvania',
'PR' => 'Puerto Rico',
'RI' => 'Rhode Island',
'SC' => 'South Carolina',
'SD' => 'South Dakota',
'TN' => 'Tennessee',
'TX' => 'Texas',
'UT' => 'Utah',
'VT' => 'Vermont',
'VI' => 'Virgin Islands',
'VA' => 'Virginia',
'WA' => 'Washington',
'WV' => 'West Virginia',
'WI' => 'Wisconsin',
'WY' => 'Wyoming',
);
?>
<?php
use CRM_Osdi_ExtensionUtil as E;
/**
*
*/
class CRM_Osdi_Page_Configure extends CRM_Core_Page {
/**
*
*/
public function run() {
// Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml.
CRM_Utils_System::setTitle(E::ts('Configure'));
parent::run();
}
}
<?php
use CRM_Osdi_ExtensionUtil as E;
/**
*
*/
class CRM_Osdi_Page_Mapping extends CRM_Core_Page {
/**
*
*/
public function run() {
// Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml.
CRM_Utils_System::setTitle(E::ts('Mapping'));
// Grab fields for column1.
$names = array();
$firstitemid = civicrm_api3('Mapping', 'get', array(
'name' => "osdi_contact",
));
$firstitem = civicrm_api3('MappingField', 'get', array(
'mapping_id' => $firstitemid["id"],
'sequential' => 1,
'options' => ['limit' => 0],
));
foreach ($firstitem["values"] as $key => $value) {
$addOn = "";
if (substr($value["name"], 0, 6) == "custom") {
// Grab the actual name too.
$result = civicrm_api3('CustomField', 'get', array(
'sequential' => 1,
'id' => (int) substr($value["name"], 7),
));
if (isset($result["values"][0])) {
$addOn = "/" . $result["values"][0]["name"];
}
}
$item = array();
$item["first"] = $value["name"];
$item["firstname"] = $value["name"] . $addOn;
$item["second"] = $value["value"];
$item["id"] = $value["id"];
$names[] = $item;
}
$this->assign('names', $names);
parent::run();
}
}
<?php
// include the importer classes
//require_once __DIR__ . '/OSDIQueueHelper.php';
// Include the importer classes
// require_once __DIR__ . '/OSDIQueueHelper.php';.
require_once __DIR__ . '/../../../importers/ActionNetworkContactImporter.php';
use CRM_Osdi_ExtensionUtil as E;
/**
*
*/
class CRM_Osdi_Page_OSDI extends CRM_Core_Page {
/**
*
*/
public function run() {
// Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml
// Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml.
CRM_Utils_System::setTitle(E::ts('OSDI'));
$configs = include('config.php');
$configs = include 'config.php';
$this->assign('taskNumber', '0');
$importer = new ActionNetworkContactImporter("https://actionnetwork.org/api/v2", "x", $configs["key"]);
$count = $importer->pull_endpoint_data();
$this->assign('taskNumber', '0');
$this->assign('taskNumber', $count);
$this->assign('completed', "yes");
$result = civicrm_api3('Importer', 'import', array(
'key' => $configs["key"],
));
$this->assign('taskNumber', $result["values"]["count"]);
// $importer = new ActionNetworkContactImporter("https://actionnetwork.org/api/v2", "x", $configs["key"]);
// $count = $importer->pull_endpoint_data();
$this->assign('completed', "yes");
parent::run();
}
......
<?php
use CRM_Osdi_ExtensionUtil as E;
class CRM_Osdi_Page_OSDIJob extends CRM_Core_Page {
public function run() {
$jobresults = civicrm_api3('Job', 'get', [
'sequential' => 1,
'name' => ['LIKE' => "OSDISYNC_IMPORT_%"]
]);
$jobs = array();
foreach ($jobresults["values"] as $job) {
$metadata = array();
// split and extract name
$metadata["name"] = substr($job["name"], 16);
// extract jobID
$metadata["id_import"] = $job["id"];
// extract joblog
$metadata["id_import_log"] = "No runs yet!";
$joblogresults = civicrm_api3("JobLog", "get", array(
"job_id" => $job["id"],
"options" => array("sort" => "run_time DESC"),
"sequential" => 1
));
if (sizeof($joblogresults["values"]) != 0) {
$metadata["id_import_log"] = substr($joblogresults["values"][0]["data"], 0, 500);
}
// extract groupID, ruleID
$metadata["group_id"] = "N/A";
$metadata["group_name"] = "";
// extract ruleID
$metadata["rule_id"] = "N/A";
$metadata["rule_fields"] = "";
$parameters = explode("\n", $job["parameters"]);
foreach($parameters as $parameter) {
$params = explode("=", $parameter);
if ($params[0] == "group") {
if ($params[1] != "") {
$results = civicrm_api3("Group", "get", [
"sequential" => 1,
"id" => $params[1]
]);
if (sizeof($results["values"] != 0)) {
$metadata["group_id"] = $results["values"][0]["id"];
$metadata["group_name"] = $results["values"][0]["name"];
}
}
}
if ($params[0] == "rule") {
if ($params[1] != "") {
$rulegetresults = civicrm_api3("Rule", "get", [
"sequential" => 1,
"dedupe_rule_group_id" => $params[1]
]);
if (sizeof($rulegetresults["values"]) != 0) {
$metadata["rule_id"] = $rulegetresults["values"][0]["id"];
foreach ($rulegetresults["values"] as $rulegetresult) {
$metadata["rule_fields"] = $metadata["rule_fields"] . $rulegetresult["rule_field"];
$metadata["rule_fields"] = $metadata["rule_fields"] . ", ";
}
}
}
}
if ($params[0] == "endpoint") {
$metadata["endpointname"] = $params[1];
}
}
// load the export value
$exportjobresults = civicrm_api3('Job', 'get', [
'sequential' => 1,
'name' => "OSDISYNC_EXPORT_" . $metadata["name"]
]);
if (sizeof($exportjobresults["values"]) != 0) {
$metadata["id_export"] = $exportjobresults["values"][0]["id"];
}
$metadata["id_export_log"] = "No runs yet!";
$joblogresults = civicrm_api3("JobLog", "get", array(
"job_id" => $metadata["id_export"],
"options" => array("sort" => "run_time DESC"),
"sequential" => 1
));
if (sizeof($joblogresults["values"]) != 0) {
$metadata["id_export_log"] = substr($joblogresults["values"][0]["data"], 0, 500);
}
// load all the metadata into the array
$jobs[] = $metadata;
}
$this->assign('jobs', $jobs);
parent::run();
}
}
<?php
use CRM_Osdi_ExtensionUtil as E;
/**
*
*/
class CRM_Osdi_Page_OSDIRunner extends CRM_Core_Page {
public function run() {
// Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml
CRM_Utils_System::setTitle(E::ts('OSDIRunner'));
//retrieve the queue
$queue = CRM_OSDIQueue_Helper::singleton()->getQueue();
$runner = new CRM_Queue_Runner(array(
'title' => ts('OSDI Queue Page runner'), //title fo the queue
'queue' => $queue, //the queue object
'errorMode' => CRM_Queue_Runner::ERROR_ABORT, //abort upon error and keep task in queue
'onEnd' => array('CRM_OSDIQueue_Runner', 'onEnd'), //method which is called as soon as the queue is finished
'onEndUrl' => CRM_Utils_System::url('civicrm/xxxx', 'reset=0'), //go to page after all tasks are finished
));
$runner->runAll(); // does not return
parent::run();
}
static function onEnd(CRM_Queue_TaskContext $ctx) {
//set a status message for the user
CRM_Core_Session::setStatus('All tasks in queue are executes', 'Queue', 'success');
}
/**
*
*/
public function run() {
// Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml.
CRM_Utils_System::setTitle(E::ts('OSDIRunner'));
// Retrieve the queue.
$queue = CRM_OSDIQueue_Helper::singleton()->getQueue();
$runner = new CRM_Queue_Runner(array(
// Title fo the queue.
'title' => ts('OSDI Queue Page runner'),
// The queue object.
'queue' => $queue,
// Abort upon error and keep task in queue.
'errorMode' => CRM_Queue_Runner::ERROR_ABORT,
// Method which is called as soon as the queue is finished.
'onEnd' => array('CRM_OSDIQueue_Runner', 'onEnd'),
// Go to page after all tasks are finished.
'onEndUrl' => CRM_Utils_System::url('civicrm/xxxx', 'reset=0'),
));
// Does not return.
$runner->runAllViaWeb();
parent::run();
}
/**
*
*/
public static function onEnd(CRM_Queue_TaskContext $ctx) {
// Set a status message for the user.
CRM_Core_Session::setStatus('All tasks in queue are executes', 'Queue', 'success');
}
}
<?php
/**
* @file
*/
require_once __DIR__ . '/../../../api/v3/Exporter/Export.php';
require_once __DIR__ . '/../../../importers/ActionNetworkContactImporter.php';
require_once __DIR__ . '/../../../vendor/autoload.php';
use Ekino\HalClient\Resource;
use Ekino\HalClient\HttpClient\FileGetContentsHttpClient;
if (!function_exists('getallheaders')) {
/**
*
*/
function getallheaders() {
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
/**
*
*/
class CRM_Osdi_Page_Webhook extends CRM_Core_Page {
/**
*
*/
public function run() {
// Check CMS's permission for (presumably) anonymous users.
if (CRM_Core_Config::singleton()->userPermissionClass->isModulePermissionSupported() && !CRM_Osdi_Permission::check('allow webhook posts')) {
header('Content-Type:application/hal+json', TRUE, 500);
print "Missing allow webhook posts permission.";
CRM_Utils_System::civiExit();
return;
}
// Check key and header in values.
$headers = getallheaders();
$apikey = isset($headers["Osdi-Api-Token"]) ? $headers["Osdi-Api-Token"] : NULL;
if ($apikey == NULL) {
$apikey = isset($headers["OSDI-API-Token"]) ? $headers["OSDI-API-Token"] : NULL;
}
$object = isset($headers["Object"]) ? $headers["Object"] : NULL;
// Check CMS's permission for (presumably) anonymous users.
if ($apikey != Civi::settings()->get("security_key")) {
header('Content-Type:application/hal+json', TRUE, 500);
print "Missing or incorrent apikey.";
CRM_Utils_System::civiExit();
return;
}
if ($object == NULL) {
header('Content-Type:application/hal+json', TRUE, 500);
print "Missing allow webhook posts permission.";
CRM_Utils_System::civiExit();
// parent::run();
return;
}
$params = array();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$params["object"] = $object;
$optionals = array("apikey", "sitekey", "page", "limit", "id", "filter");
foreach ($optionals as $optional) {
if (isset($_GET[$optional])) {
$params[$optional] = $_GET[$optional];
}
}
$result = civicrm_api3('Exporter', 'export', $params);
header('Content-Type:application/hal+json', TRUE, 200);
print json_encode($result["values"]);
}
elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
$contact = json_decode(file_get_contents('php://input'), TRUE);
if ($contact == NULL) {
header('Content-Type:application/hal+json', TRUE, 500);
print "post was null";
CRM_Utils_System::civiExit();
// parent::run();
return;
}
//dummy $client just so i can use the ekino hal library
$client = new FileGetContentsHttpClient("https://www.google.com");
$contactarray = $contact["person"];
$person = Resource::create($client, $contactarray);
if (ActionNetworkContactImporter::validate_endpoint_data($person, NULL)) {
// Remember custom fields!
$result = civicrm_api3('Contact', 'get', array(
'email' => $contactarray["email_addresses"][0]["address"],
));
if (sizeof($result["values"]) == 0) {
$result = civicrm_api3('Contact', 'create', array(
'first_name' => $contactarray["given_name"],
'last_name' => $contactarray["family_name"],
'email' => $contactarray["email_addresses"][0]["address"],
'display_name' => $contactarray["family_name"],
'contact_type' => 'Individual',
'dupe_check' => 1,
'check_permission' => 1,
'sequential' => 1,
));
}
else {
// load all relevant parameters
$params = array(
'id' => $result["id"],
'first_name' => $contactarray["given_name"],
'last_name' => $contactarray["family_name"],
'email' => $contactarray["email_addresses"][0]["address"],
'preferred_language' => isset($contactarray["preferred_language"]) ? $contactarray["preferred_language"] : "",
'prefix_id' => isset($contactarray["honorific_prefix"]) ? $contactarray["honorific_prefix"] : "",
'suffix_id' => isset($contactarray["honorific_suffix"]) ? $contactarray["honorific_suffix"] : "",
'current_employer' => isset($contactarray["employer"]) ? $contactarray["employer"] : "",
'display_name' => $contactarray["family_name"],
'contact_type' => 'Individual',
'sequential' => 1,
);
if (isset($contactarray["postal_addresses"])) {
if (sizeof($contactarray["postal_addresses"]) != 0) {
$params["city"] = isset($contactarray["postal_addresses"][0]["locality"])
? $contactarray["postal_addresses"][0]["locality"] : "";
$params["state_province_name"] = isset($contactarray["postal_addresses"][0]["region"])
? $contactarray["postal_addresses"][0]["region"] : "";
$params["country"] = isset($contactarray["postal_addresses"][0]["country"])
? $contactarray["postal_addresses"][0]["country"] : "";
$params["postal_code"] = isset($contactarray["postal_addresses"][0]["postal_code"])
? $contactarray["postal_addresses"][0]["postal_code"] : "";
if (isset($contactarray["postal_addresses"][0]["address_lines"])) {
if (sizeof($contactarray["postal_addresses"][0]["address_lines"]) != 0) {
$params["street_address"] = $contactarray["postal_addresses"][0]["address_lines"][0];
}
}
}
}
if (isset($contactarray["phone_numbers"])) {
if (sizeof($contactarray["phone_numbers"]) != 0) {
$params["phone"] = isset($contactarray["phone_numbers"][0]["number"])
? $contactarray["phone_numbers"][0]["number"] : "";
$params["do_not_phone"] = isset($contactarray["phone_numbers"][0]["do_not_call"])
? $contactarray["phone_numbers"][0]["do_not_call"] : "";
}
}
if (isset($contactarray["birthdate"])) {
$yearitems = array();
$yearitems[] = isset($contactarray["birthdate"]["year"])
? $contactarray["birthdate"]["year"] : "";
$yearitems[] = isset($contactarray["birthdate"]["day"])
? $contactarray["birthdate"]["day"] : "";
$yearitems[] = isset($contactarray["birthdate"]["month"])
? $contactarray["birthdate"]["month"] : "";
$params["birth_date"] = join("-", $yearitems);
$items = explode("-", $params["birth_date"]);
foreach ($items as $item) {
if ($item == "") {
unset($params["birth_date"]);
}
}
}
// load all custom fields
if (isset($contactarray["custom_fields"])) {
foreach ($contactarray["custom_fields"] as $custom_key => $custom_value) {
// check if the key exists
$keyexistsresult = civicrm_api3('CustomField', 'get', array(
'sequential' => 1,
'label' => $custom_key
));
// if yes, set the value
if (sizeof($keyexistsresult["values"]) != 0) {
$custom_id = $keyexistsresult["values"][0]["id"];
$params["custom_" . $custom_id] = $custom_value;
}
}
}
$params["dupe_check"] = 1;
try {
$result = civicrm_api3('Contact', 'create', $params);
} catch (Exception $e) {
var_dump("dupe");
}
}
print json_encode(convertContactOSDI($result["values"][0], array()), JSON_PRETTY_PRINT);
}
}
CRM_Utils_System::civiExit();
// parent::run();
}
}
<?php
/**
*
*/
class CRM_Osdi_Permission extends CRM_Core_Permission {
/**
* Returns an array of permissions defined by this extension. Modeled off of
* CRM_Core_Permission::getCorePermissions().
*
* @return array Keyed by machine names with human-readable labels for values
*/
public static function getOsdiPermissions() {
// Name of extension or module.
$prefix = ts('OSDI sample application') . ': ';
return array(
'allow webhook posts' => $prefix . ts('allow webhook posts'),
);
}
/**
* Given a permission string or array, check for access requirements.
* if this is a permissions-challenged Joomla instance, don't enforce
* CiviMailchimp-defined permissions.
*
* @param mixed $permissions
* The permission(s) to check as an array or string.
* See parent class for examples.
*
* @return bool
*/