diff --git a/bootstrap.php b/bootstrap.php new file mode 100644 index 0000000..2dfc301 --- /dev/null +++ b/bootstrap.php @@ -0,0 +1,84 @@ +setMailchimpApi($mailchimpApi); + + /** + * Runs directly after creation of main plugin instance + */ + do_action('nf_mailchimp_init', $instance); +} + + +/** + * Initialize required functionality for NinjaFormsMailchimp instance + * + * - Add NF Bridge to provide NF functionality + * - Initialize WP REST API endpoints + * - Add subscribe action + * - register opt-in field + * @since 3.2.1 + */ +add_action('nf_mailchimp_init', function (\NFMailchimp\NinjaForms\Mailchimp\NinjaFormsMailchimp $instance) { + + // Provide NF core functionality + setNfBridge($instance); + + // Initialize WordPress REST API endpoints + add_action('rest_api_init', [$instance, 'initApi']); + + // Register the Subscribe to Mailchimp action + $instance->addSubscribeAction(); + + // Adds modal box to autogenerate form + add_filter('ninja_forms_new_form_templates', array($instance, 'registerAutogenerateModal')); + + add_filter( 'ninja_forms_register_fields', array( $instance, 'registerOptIn' ) ); + + add_action( 'ninja_forms_loaded', array( $instance, 'setupAdmin' ) ); + + add_filter('nf_react_table_extra_value_keys', array($instance, 'addMetabox')); + + (new DiagnosticScreen())->registerHooks(); +}, 2); + +/** + * Bind an NF Bridge to the NinjaFormsMailchimp instance + * @param \NFMailchimp\NinjaForms\Mailchimp\NinjaFormsMailchimp $instance + */ +function setNfBridge(\NFMailchimp\NinjaForms\Mailchimp\NinjaFormsMailchimp $instance) { + + $nfBridge = (new NFMailchimp\EmailCRM\NfBridge\NfBridge()) + ->registerServices(); + $instance->setNfBridge($nfBridge); +} + + diff --git a/lib/Mailchimp/ApiRequests/GetAudienceDefinitionData.php b/lib/Mailchimp/ApiRequests/GetAudienceDefinitionData.php new file mode 100644 index 0000000..8809d7d --- /dev/null +++ b/lib/Mailchimp/ApiRequests/GetAudienceDefinitionData.php @@ -0,0 +1,114 @@ +mailchimpApi = $mailchimpApi; + } + + + /** + * Construct AudienceDefinition from retrieved data + * @return AudienceDefinition + */ + public function handle(SingleList $singleList): AudienceDefinition + { + + $this->audienceDefinition = new AudienceDefinition(); + + $this->audienceDefinition->addList($singleList); + $this->getMergeFields($singleList->getListId()); + $this->getInterestCategories($singleList->getListId()); + $this->addAllInterestCategories($singleList->getListId()); + $this->getSegmentsViaRemoteApi($singleList->getListId()); + return $this->audienceDefinition; + } + + /** + * Adds merge fields retrieved through API to Audience Def + */ + protected function getMergeFields(string $listId):void + { + $mergeFieldsAction = new GetMergeFields($this->mailchimpApi); + $mergeFields = $mergeFieldsAction->requestMergeFields($listId); + $this->audienceDefinition->addMergeFields($mergeFields); + } + + /** + * Adds interest categories retrieved through API to Audience Def + */ + protected function getInterestCategories(string $listId):void + { + $interestCategoriesAction = new GetInterestCategories($this->mailchimpApi); + $interestCategories = $interestCategoriesAction->requestInterestCategories($listId); + $this->audienceDefinition->addInterestCategories($interestCategories); + } + + /** + * Iterate through interest categories and append interests from each category + */ + protected function addAllInterestCategories(string $listId) + { + foreach ($this->audienceDefinition->interestCategories->getInterestCategories() as $interestCategory) { + $interestCategoryId = $interestCategory->getId(); + $this->appendInterests($listId, $interestCategoryId); + } + } + + /** + * Add interests retrieved throcugh API to Audience Definition + * + * @param string $listId + * @param string $interestCategoryId + * @return void + */ + protected function appendInterests(string $listId, string $interestCategoryId) + { + $interestsAction = new GetInterests($this->mailchimpApi); + $interests = $interestsAction->requestInterests($listId, $interestCategoryId); + $this->audienceDefinition->appendInterests($interests); + } + + /** + * Adds Tags retrieved through API to Audience Definition + */ + protected function getSegmentsViaRemoteApi(string $listId) + { + $getSegmentsAction = new GetSegments($this->mailchimpApi); + $segments = $getSegmentsAction->requestSegments($listId); + $this->audienceDefinition->addTags($segments); + } +} diff --git a/lib/Mailchimp/ApiRequests/GetInterestCategories.php b/lib/Mailchimp/ApiRequests/GetInterestCategories.php new file mode 100644 index 0000000..98024cb --- /dev/null +++ b/lib/Mailchimp/ApiRequests/GetInterestCategories.php @@ -0,0 +1,42 @@ +mailchimpApi = $mailchimpApi; + } + + /** @inheritDoc */ + public function requestInterestCategories(string $listId): InterestCategories + { + try { + $r = $this->mailchimpApi->getInterestCategories($listId, ['count' => 500]); + $interestCategories = InterestCategories::fromArray((array) $r->categories); + + $interestCategories->setListId($listId); + + return $interestCategories; + } catch (\Exception $e) { + error_log(self::class . '::' . __FUNCTION__).' - ' . $e->getMessage(); + return new InterestCategories(); + } + } +} diff --git a/lib/Mailchimp/ApiRequests/GetInterests.php b/lib/Mailchimp/ApiRequests/GetInterests.php new file mode 100644 index 0000000..9a1878c --- /dev/null +++ b/lib/Mailchimp/ApiRequests/GetInterests.php @@ -0,0 +1,67 @@ +mailchimpApi = $mailchimpApi; + } + + /** @inheritdoc */ + public function requestInterests(string $listId, string $interestCategoryId): Interests + { + try { + $r = $this->mailchimpApi->getInterests($listId, $interestCategoryId, ['count' => 500]); + $interests = Interests::fromArray((array) $r->interests); + $interests->setListId($listId); + return $interests; + } catch (\Exception $e) { + + $this->logException($e, __FUNCTION__); + + return new Interests(); + } + } + + /** + * Log the exception with traceability + * + * @param \Exception $e + * @param string $functionName + * @return void + */ + protected function logException(\Exception $e, string $functionName): void + { + error_log($this->constructLogMessage($e, $functionName)); + } + + protected function constructLogMessage(\Exception $e, string $functionName): string + { + $return = self::class . '::' . $functionName . ' - ' . $e->getMessage(); + + return $return; + } +} diff --git a/lib/Mailchimp/ApiRequests/GetLists.php b/lib/Mailchimp/ApiRequests/GetLists.php new file mode 100644 index 0000000..0d99651 --- /dev/null +++ b/lib/Mailchimp/ApiRequests/GetLists.php @@ -0,0 +1,47 @@ +mailchimpApi = $mailchimpApi; + } + + /** + * Request collection of lists from remote API + * + * If exception is returned, return empty Lists + * + * @return Lists + */ + public function requestLists(): Lists + { + try { + + $response = $this->mailchimpApi->getLists(['count' => 500]); + return Lists::fromArray((array) $response->lists); + } catch (\Exception $e) { + + error_log(self::class . '::' . __FUNCTION__).' - ' . $e->getMessage(); + return new Lists(); + } + } +} diff --git a/lib/Mailchimp/ApiRequests/GetMergeFields.php b/lib/Mailchimp/ApiRequests/GetMergeFields.php new file mode 100644 index 0000000..881098d --- /dev/null +++ b/lib/Mailchimp/ApiRequests/GetMergeFields.php @@ -0,0 +1,49 @@ +mailchimpApi = $mailchimpApi; + } + + /** + * Request merge vars from remote API + * + * @param string $listId + * @return MergeVars + */ + public function requestMergeFields(string $listId): MergeVars + { + try { + $response = $this->mailchimpApi->getMergeFields($listId, ['count' => 500]); + $mergeVars = MergeVars::fromArray((array)$response->merge_fields); + + return $mergeVars; + } catch (\Exception $e) { + error_log(self::class . '::' . __FUNCTION__).' - ' . $e->getMessage(); + return new MergeVars(); + } + } +} diff --git a/lib/Mailchimp/ApiRequests/GetSegments.php b/lib/Mailchimp/ApiRequests/GetSegments.php new file mode 100644 index 0000000..70618cb --- /dev/null +++ b/lib/Mailchimp/ApiRequests/GetSegments.php @@ -0,0 +1,43 @@ +mailchimpApi = $mailchimpApi; + } + + /** + * @param string $listId + * @return Segments + * @throws \Exception + */ + public function requestSegments(string $listId): Segments + { + try { + $response = $this->mailchimpApi->getSegments($listId, ['count' => 500]); + $segments = Segments::fromArray((array)$response->segments); + $segments->setListId($listId); + return $segments; + } catch (\Exception $e) { + error_log(self::class . '::' . __FUNCTION__).' - ' . $e->getMessage(); + return new Segments(); + } + } +} diff --git a/lib/Mailchimp/ApiRequests/MailchimpApiException.php b/lib/Mailchimp/ApiRequests/MailchimpApiException.php new file mode 100644 index 0000000..17f86ba --- /dev/null +++ b/lib/Mailchimp/ApiRequests/MailchimpApiException.php @@ -0,0 +1,32 @@ +status . ': ' . $message_obj->title; + if (!empty($message_obj->detail)) { + $message .= ' - ' . $message_obj->detail; + } + if (!empty($message_obj->errors) && is_array($message_obj->errors)) { + foreach($message_obj->errors as $errorObject){ + $message .= ' ' . serialize($errorObject); + } + } + } + parent::__construct($message, $code, $previous); + } + +} \ No newline at end of file diff --git a/lib/Mailchimp/Contracts/ConvertSubmissionDataToSubscriberContract.php b/lib/Mailchimp/Contracts/ConvertSubmissionDataToSubscriberContract.php new file mode 100644 index 0000000..b11c3c4 --- /dev/null +++ b/lib/Mailchimp/Contracts/ConvertSubmissionDataToSubscriberContract.php @@ -0,0 +1,30 @@ +name; + } + + public function getNameOrId():string + { + return ! empty($this->name) ? $this->getName() : $this->getMailChimpAccountId(); + } + /** + * @param string $name + * + * @return Account + */ + public function setName(string $name): Account + { + $this->name = $name; + return $this; + } + + /** + * @return int + */ + public function getId(): int + { + return ! empty($this->id) ? $this->id : 0; + } + + /** + * @param int $id + * + * @return Account + */ + public function setId(int $id): Account + { + $this->id = $id; + return $this; + } + + /** + * @return string + */ + public function getApiKey(): string + { + if (!$this->apiKey) { + return ''; + } + return $this->apiKey; + } + + /** + * @param string $apiKey + * + * @return Account + */ + public function setApiKey(string $apiKey): Account + { + $this->apiKey = $apiKey; + return $this; + } + + /** + * @return string + */ + public function getMailChimpAccountId(): string + { + return $this->mailChimpAccountId; + } + + /** + * @param string $mailChimpAccountId + * + * @return Account + */ + public function setMailChimpAccountId(string $mailChimpAccountId): Account + { + $this->mailChimpAccountId = $mailChimpAccountId; + return $this; + } + + /** + * @return string + */ + public function getListId(): string + { + return ''; + } + + public static function fromArray(array $items): SimpleEntity + { + if (isset($items[ 'api_key'])) { + $items['apiKey' ] = $items[ 'api_key']; + } + if (isset($items[ 'mailchimp_account_id'])) { + $items['mailChimpAccountId' ] = $items[ 'mailchimp_account_id']; + } + return parent::fromArray($items); + } +} diff --git a/lib/Mailchimp/Entities/AudienceDefinition.php b/lib/Mailchimp/Entities/AudienceDefinition.php new file mode 100644 index 0000000..fbbfa59 --- /dev/null +++ b/lib/Mailchimp/Entities/AudienceDefinition.php @@ -0,0 +1,247 @@ +listId = ''; + $this->name = ''; + $this->mergeFields = new MergeVars(); + $this->interestCategories = new InterestCategories(); + $this->interests = new Interests(); + $this->tags = new Segments(); + } + + /** + * Construct the audience definition beginning with a single list + * @param SingleList $list + * + * @return AudienceDefinition + */ + public function addList(SingleList $list): AudienceDefinition + { + $this->listId = $list->getListId(); + $this->name = $list->getName(); + + // Interests are appended, not automatically added with entity + $this->interests->setListId($this->listId); + return $this; + } + + /** + * Add Merge Fields to the audience definition + * @param MergeVars $mergeVars + * + * @return AudienceDefinition + */ + public function addMergeFields(MergeVars $mergeVars): AudienceDefinition + { + $this->mergeFields = $mergeVars; + return $this; + } + + /** + * Add Interest Categories to the audience definition + * + * Each audience def has a single list of interest categories; each of these + * categories has its own collection of interests associated with it + * + * @param InterestCategories $interestCategories + * + * @return AudienceDefinition; + */ + public function addInterestCategories(InterestCategories $interestCategories): AudienceDefinition + { + $this->interestCategories = $interestCategories; + return $this; + } + + /** + * Adds a collection of interests to the audience definition + * + * Interests are retrieved by each interest category grouping, thus a separate + * request is made to retrieve the interests for each category and then + * appended here. Requests made to add members to the API do not + * involve the interest category as the interest Id is unique across all + * categories and can be combined into a single interests collection. + * + * @param Interests $interests + * @return AudienceDefinition + */ + public function appendInterests(Interests $interests): AudienceDefinition + { + $this->interests->appendInterests($interests); + return $this; + } + + /** + * Add tags to the audience definition. Only tag segments are added + * @param Segments $segments + * + * @return AudienceDefinition + */ + public function addTags(Segments $segments): AudienceDefinition + { + $this->tags = $segments->getTags(); + return $this; + } + + /** + * Checks if supplied MergeVar exists in Audience Definition, returns boolean + * @param string $mergeVar + * @return bool + */ + public function hasMergeVar(string $mergeVar): bool + { + return $this->mergeFields->hasMergeVar($mergeVar); + } + + /** + * Returns size limit for merge var; 0 indicates no size limit specified + * @param string $mergeVar + * @return int + */ + public function mergeVarSizeLimit(string $mergeVar): int + { + $return = $this->mergeFields->getMergeVar($mergeVar)->getSize(); + + return $return; + } + + /** + * Returns boolean true if given interest Id is in Audience Def + * @param string $interestId + * @return bool + */ + public function hasInterest(string $interestId): bool + { + return $this->interests->hasInterest($interestId); + } + + /** + * @param string $categoryId + * @return Interest[]; + */ + public function getCategoryInterests(string $categoryId): array + { + $categoryInterests = []; + $interests = is_array($this->interests) ? $this->interests : $this->interests->getInterests(); + foreach ($interests as $interest) { + if ($categoryId === $interest->getCategoryId()) { + $categoryInterests[] = $interest; + } + } + + return $categoryInterests; + } + + /** + * Get an interest from collection + * + * @param string $interestId + * @return Interest + * @throws Exception + */ + public function getInterest(string $interestId): Interest + { + if (!$this->hasInterest($interestId)) { + throw new Exception('Interest Not found'); + } + return $this->interests->getInterest($interestId); + } + + /** + * Returns boolean true if given tag is in Audience Def + * @param string $tag + * @return bool + */ + public function hasTag(string $tag): bool + { + return $this->tags->hasSegment($tag); + } + + /** + * @return AudienceDefinition + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + + foreach ($items as $property => $value) { + switch ($property) { + case 'mergeFields': + $mergeFields = MergeVars::fromArray($value); + $obj->mergeFields = $mergeFields; + break; + case 'interestCategories': + $interestCategories = InterestCategories::fromArray($value); + $obj->interestCategories = $interestCategories; + break; + case 'interests': + $interests = Interests::fromArray($value); + $obj->interests = $interests; + break; + case 'tags': + if (! is_array($value)) { + $tags = new Segments(); + } else { + $tags = Segments::fromArray($value); + } + $obj->tags = $tags; + break; + case 'listId': + case 'list_id': + $obj->setListId($value); + break; + default: + if (null !== $value) { + $obj = $obj->__set($property, $value); + } + } + } + + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/Categories.php b/lib/Mailchimp/Entities/Categories.php new file mode 100644 index 0000000..8d65e0f --- /dev/null +++ b/lib/Mailchimp/Entities/Categories.php @@ -0,0 +1,54 @@ +categories = []; + } + + /** + * @param array $items + * + * @return SimpleEntity + */ + public static function fromArray(array $items): SimpleEntity + { + + $obj = new static(); + foreach ($items as $category) { + if (! is_array($category)) { + $category = (array)$category; + } + $obj->setListId($category['list_id']); + $obj->categories[$category['id']]= [ + 'name' => $category[ 'name'], + 'id' => $category[ 'id' ] + ]; + } + return $obj; + } + + + /** + * @return array + */ + public function getCategories(): array + { + return $this->categories; + } +} diff --git a/lib/Mailchimp/Entities/Exception.php b/lib/Mailchimp/Entities/Exception.php new file mode 100644 index 0000000..895c7a1 --- /dev/null +++ b/lib/Mailchimp/Entities/Exception.php @@ -0,0 +1,12 @@ +exceptionStringMatch = $string; + return $this; + } + + /** + * Set Context + * @param string $string + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\ExceptionDiagnostic + */ + public function setContext(string $string): ExceptionDiagnostic + { + $this->context = $string; + return $this; + } + + /** + * Add diagnostic string instruction + * @param string $string + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\ExceptionDiagnostic + */ + public function addDiagnostic(string $string): ExceptionDiagnostic + { + $this->diagnostic[] = $string; + return $this; + } + + /** + * Return ExceptionStringMatch + * @return string + */ + public function getExceptionStringMatch(): string + { + return isset($this->exceptionStringMatch) ? $this->exceptionStringMatch : ''; + } + + /** + * Return Context + * @return string + */ + public function getContext(): string + { + return isset($this->context) ? $this->context : ''; + } + + /** + * Return diagnostic collection + * @return array + */ + public function getDiagnosticCollection(): array + { + return $this->diagnostic; + } + + /** + * @inheritdoc + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + if ('diagnostic' === $property && is_array($value)) { + $obj = $obj->__set($property, $value); + } elseif (!is_null($value)) { + $obj = $obj->__set($property, $value); + } + } + + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/ExceptionDiagnostics.php b/lib/Mailchimp/Entities/ExceptionDiagnostics.php new file mode 100644 index 0000000..0948a17 --- /dev/null +++ b/lib/Mailchimp/Entities/ExceptionDiagnostics.php @@ -0,0 +1,63 @@ +addExceptionDiagnostic($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addExceptionDiagnostic(ExceptionDiagnostic::fromArray($list)); + } + return $obj; + } + + /** + * Add an Exception Diagnostic to collection + * + * @param ExceptionDiagnostic $diagnostic + * + * @return ExceptionDiagnostics + */ + public function addExceptionDiagnostic(ExceptionDiagnostic $diagnostic): ExceptionDiagnostics + { + $this->exceptionDiagnostics[] = $diagnostic; + return $this; + } + + + /** + * Get all ExceptionDiagnostics in collection + * + * @return ExceptionDiagnostic[] + */ + public function getExceptionDiagnostics(): array + { + return $this->exceptionDiagnostics; + } +} diff --git a/lib/Mailchimp/Entities/Group.php b/lib/Mailchimp/Entities/Group.php new file mode 100644 index 0000000..d2e3b3d --- /dev/null +++ b/lib/Mailchimp/Entities/Group.php @@ -0,0 +1,142 @@ +setGroupId((string) $items['id']); + } + if (isset($items['groupId'])) { + $obj->setGroupId((string) $items['groupId']); + } + return $obj; + } + + + /** + * @return string + */ + public function getGroupId(): string + { + return is_string($this->groupId) ? $this->groupId : ''; + } + + /** + * @param string $groupId + * + * @return Group + */ + public function setGroupId(string $groupId): Group + { + $this->groupId = $groupId; + return $this; + } + + /** + * @return string + */ + public function getTitle(): string + { + return is_string($this->title) ? $this->title : ''; + } + + /** + * @param string $title + * + * @return Group + */ + public function setTitle(string $title): Group + { + $this->title = $title; + return $this; + } + + /** + * @return string + */ + public function getType(): string + { + return is_string($this->type) ? $this->type : ''; + } + + /** + * @param string $type + * + * @return Group + */ + public function setType(string $type): Group + { + $this->type = $type; + return $this; + } + + /** + * @return bool + */ + public function getShouldJoin(): bool + { + //if not set, default is false + return (bool)$this->shouldJoin; + } + + /** + * @param bool $shouldJoin + * + * @return Group + */ + public function setShouldJoin(bool $shouldJoin): Group + { + $this->shouldJoin = $shouldJoin; + return $this; + } + + /** + * @return string + */ + public function getId() + { + return $this->getGroupId(); + } + + /** + * @param string $id + * @return Group + */ + public function setId(string $id): Group + { + return $this->setGroupId($id); + } +} diff --git a/lib/Mailchimp/Entities/Groups.php b/lib/Mailchimp/Entities/Groups.php new file mode 100644 index 0000000..0e7528d --- /dev/null +++ b/lib/Mailchimp/Entities/Groups.php @@ -0,0 +1,161 @@ +groups = []; + $this->categories = []; + } + + /** @inheritdoc */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + $handleGroup = function ($obj, $group) { + if (!is_array($group)) { + if (is_a($group, Group::class)) { + $obj->addGroup($group); + return $obj; + } else { + $group = (array)$group; + } + } + $obj->addGroup(Group::fromArray($group)); + return $obj; + }; + + if (isset($items['groups'])) { + foreach ($items['groups'] as $group) { + $obj = $handleGroup($obj, $group); + } + } else { + foreach ($items as $group) { + $obj = $handleGroup($obj, $group); + } + } + + if (isset($items['categories'])) { + foreach ($items['categories'] as $groupId => $category) { + $obj->addCategoriesForGroup($groupId, $category); + } + } + return $obj; + } + + /** + * Add a group to collection + * + * @param Group $group + * + * @return $this + */ + public function addGroup(Group $group) + { + if (!is_array($this->groups)) { + $this->groups = $this->getGroups(); + } + $this->groups[$group->getId()] = $group; + return $this; + } + + /** + * @param string $id + * @return bool + */ + public function removeGroup(string $id): bool + { + $groups = $this->getGroups(); + if (isset($groups[$id])) { + unset($groups[$id]); + $this->groups = $groups; + return true; + } + return false; + } + + /** + * Get a group from collection + * + * @param string $id + * + * @return Group + * @throws Exception + */ + public function getGroup(string $id): Group + { + if (!$this->hasGroup($id)) { + throw new Exception(); + } + return $this->getGroups()[$id]; + } + + /** + * @param string $id + * @return bool + */ + public function hasGroup(string $id): bool + { + return isset($this->getGroups()[$id]); + } + + public function getGroups(): array + { + return is_array($this->groups) ? $this->groups : []; + } + + /** + * @param string $categoryId + * + * @return mixed|Categories + * @throws Exception + */ + public function getCategoriesForGroup(string $categoryId) + { + if (!$this->hasCategoriesForGroup($categoryId)) { + throw new Exception(); + } + return $this->categories[$categoryId]; + } + + /** + * @param string $categoryId + * + * @return bool + */ + public function hasCategoriesForGroup(string $categoryId): bool + { + return isset($this->categories[$categoryId]); + } + + /** + * @param string $categoryId + * @param Categories $categories + * + * @return Groups + */ + public function addCategoriesForGroup(string $categoryId, Categories $categories): Groups + { + $this->categories[$categoryId] = $categories; + return $this; + } +} diff --git a/lib/Mailchimp/Entities/Instruction.php b/lib/Mailchimp/Entities/Instruction.php new file mode 100644 index 0000000..020aa18 --- /dev/null +++ b/lib/Mailchimp/Entities/Instruction.php @@ -0,0 +1,101 @@ +instruction; + } + + /** + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * @return string + */ + public function getKey() + { + return $this->key; + } + + + /** + * @param string $instruction + * + * @return Instruction + */ + public function setInstruction(string $instruction): Instruction + { + $this->instruction = $instruction; + return $this; + } + + /** + * @param string $value + * + * @return Instruction + */ + public function setValue(string $value): Instruction + { + $this->value = $value; + return $this; + } + /** + * @param string $key + * + * @return Instruction + */ + public function setKey(string $key): Instruction + { + $this->key = $key; + return $this; + } + /** + * @inheritdoc + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + if (null !== $value) { + $obj = $obj->__set($property, $value); + } + } + + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/Instructions.php b/lib/Mailchimp/Entities/Instructions.php new file mode 100644 index 0000000..669e246 --- /dev/null +++ b/lib/Mailchimp/Entities/Instructions.php @@ -0,0 +1,69 @@ +instructions = []; + } + + /** + * @inheritDoc + */ + + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $list) { + if (!is_array($list)) { + if (is_a($list, Instruction::class)) { + $obj->addInstruction($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addInstruction(Instruction::fromArray($list)); + } + return $obj; + } + + /** + * Add an Instruction to collection + * + * @param Instruction $instruction + * + * @return Instructions + */ + public function addInstruction(Instruction $instruction): Instructions + { + $this->instructions[] = $instruction; + return $this; + } + + + /** + * Get all Instructions in collection + * + * @return Instruction[] + */ + public function getInstructions(): array + { + return $this->instructions; + } +} diff --git a/lib/Mailchimp/Entities/Interest.php b/lib/Mailchimp/Entities/Interest.php new file mode 100644 index 0000000..2d8e228 --- /dev/null +++ b/lib/Mailchimp/Entities/Interest.php @@ -0,0 +1,91 @@ +id; + } + + /** + * Get name of interest + * @return string + */ + public function getName(): string + { + return isset($this->name) ? (string) $this->name : ''; + } + + /** + * @param string $id + * + * @return InterestCategory + */ + public function setId(string $id): Interest + { + $this->id = $id; + return $this; + } + + /** + * Get interest category id + * @return string + */ + public function getCategoryId():string + { + return isset($this->category_id)?$this->category_id:''; + } + + /** + * @inheritdoc + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + if (null !== $value) { + $obj = $obj->__set($property, $value); + } + } + if (isset($items['list_id'])) { + $obj->setListId($items['list_id']); + } + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/InterestCategories.php b/lib/Mailchimp/Entities/InterestCategories.php new file mode 100644 index 0000000..2af7132 --- /dev/null +++ b/lib/Mailchimp/Entities/InterestCategories.php @@ -0,0 +1,95 @@ +interestCategories = []; + } + + /** @inheritDoc */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + + // Entity structure else response structure + if (isset($items['interestCategories'])) { + $array = $items['interestCategories']; + } else { + $array = $items; + } + + foreach ($array as $list) { + if (!is_array($list)) { + if (is_a($list, InterestCategory::class)) { + $obj->addInterestCategory($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addInterestCategory(InterestCategory::fromArray($list)); + } + + // Entity structure contains listId + if (isset($items['listId'])) { + $obj->setListId($items['listId']) ; + } + + return$obj; + } + + /** + * Add an Interest Category to collection + * + * @param InterestCategory $interestCategory + * + * @return InterestCategories + */ + public function addInterestCategory(InterestCategory $interestCategory): InterestCategories + { + $this->interestCategories[$interestCategory->getId()] = $interestCategory; + return $this; + } + + /** + * Get an Interest Category from collection + * + * @param string $interestCategoryId + * + * @return InterestCategory + * @throws Exception + */ + public function getInterestCategory(string $interestCategoryId): InterestCategory + { + if (!isset($this->interestCategories[$interestCategoryId])) { + throw new Exception(); + } + return $this->interestCategories[$interestCategoryId]; + } + + /** + * Get all Interest Categories in collection + * + * @return InterestCategory[] + */ + public function getInterestCategories(): array + { + return $this->interestCategories; + } +} diff --git a/lib/Mailchimp/Entities/InterestCategory.php b/lib/Mailchimp/Entities/InterestCategory.php new file mode 100644 index 0000000..b149257 --- /dev/null +++ b/lib/Mailchimp/Entities/InterestCategory.php @@ -0,0 +1,73 @@ +id; + } + + /** + * Get title of interest category + * @return string + */ + public function getTitle(): string + { + return isset($this->title) ? (string) $this->title : ''; + } + + /** + * @param string $id + * + * @return InterestCategory + */ + public function setId(string $id): InterestCategory + { + $this->id = $id; + return $this; + } + + /** + * @inheritdoc + */ + public static function fromArray(array $items): SimpleEntity + { + + $obj = new static(); + foreach ($items as $property => $value) { + if (null !== $value) { + $obj = $obj->__set($property, $value); + } + } + + if (isset($items['list_id'])) { + $obj->setListId($items['list_id']); + } + + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/Interests.php b/lib/Mailchimp/Entities/Interests.php new file mode 100644 index 0000000..122e08f --- /dev/null +++ b/lib/Mailchimp/Entities/Interests.php @@ -0,0 +1,120 @@ +interests = []; + } + + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + // Entity structure else response structure + if (isset($items['interests'])) { + $array = $items['interests']; + } else { + $array = $items; + } + foreach ($array as $list) { + if (!is_array($list)) { + if (is_a($list, Interest::class)) { + $obj->addInterest($list); + continue; + } else { + $list = (array) $list; + } + } + + $interestEntity = Interest::fromArray($list); + + $obj->addInterest($interestEntity); + } + + // Entity structure contains listId + if (isset($items['listId'])) { + $obj->setListId($items['listId']); + } + + return$obj; + } + + /** + * Add an Interest to collection + * + * @param Interest $interest + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\Interests + */ + public function addInterest(Interest $interest): Interests + { + $this->interests[$interest->getId()] = $interest; + return $this; + } + + /** + * Append collection of interests to existing collection + * @param \NFMailchimp\EmailCRM\Mailchimp\Entities\Interests $interests + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\Interests + */ + public function appendInterests(Interests $interests): Interests + { + + $newInterests = $interests->getInterests(); + + foreach ($newInterests as $interest) { + $this->addInterest($interest); + } + + return $this; + } + + /** + * Get an Interest from collection + * + * @param string $interestId + * + * @return Interest + * @throws Exception + */ + public function getInterest(string $interestId): Interest + { + if (!isset($this->interests[$interestId])) { + throw new Exception(); + } + return $this->interests[$interestId]; + } + + /** + * Get all Interests in collection + * + * @return Interest[] + */ + public function getInterests(): array + { + return $this->interests; + } + + /** + * Returns boolean if segment exists + * @param string $id + * @return bool + */ + public function hasInterest($id): bool + { + return isset($this->getInterests()[$id]); + } +} diff --git a/lib/Mailchimp/Entities/Lists.php b/lib/Mailchimp/Entities/Lists.php new file mode 100644 index 0000000..1d9bbf4 --- /dev/null +++ b/lib/Mailchimp/Entities/Lists.php @@ -0,0 +1,106 @@ +lists = []; + } + + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $list) { + if (! is_array($list)) { + if (is_a($list, SingleList::class)) { + $obj->addList($list); + continue; + } else { + $list = (array)$list; + } + } + + $obj->addList(SingleList::fromArray($list)); + } + return$obj; + } + + public function toUiFieldConfig(): array + { + $fieldConfig = [ + 'fieldType' => 'select', + 'required' => true, + 'fieldId' => 'mc-select-field', + 'options' => [], + 'label' => 'Choose List' + ]; + $fieldConfig['options'][] = [ + 'value' => null, + 'label' => ' --- ' + ]; + + if (is_array($lists = $this->getLists())) { + /** @var SingleList $list */ + foreach ($lists as $list) { + $fieldConfig[ 'options' ][] = [ + 'value' => $list->getListId(), + 'label' => $list->getName(), + ]; + } + } + return [$fieldConfig]; + } + + /** + * Add a list to collection + * + * @param SingleList $list + * + * @return Lists + */ + public function addList(SingleList $list): Lists + { + $this->lists[$list->getListId()] = $list; + return $this; + } + + /** + * Get a list from collection + * + * @param string $listId + * + * @return SingleList + * @throws Exception + */ + public function getList(string $listId): SingleList + { + if (! isset($this->lists[$listId])) { + throw new Exception(); + } + return $this->lists[$listId]; + } + + /** + * Get all lists in collection + * + * @return SingleList[] + */ + public function getLists(): array + { + return $this->lists; + } +} diff --git a/lib/Mailchimp/Entities/MailChimpEntity.php b/lib/Mailchimp/Entities/MailChimpEntity.php new file mode 100644 index 0000000..e359204 --- /dev/null +++ b/lib/Mailchimp/Entities/MailChimpEntity.php @@ -0,0 +1,80 @@ +listId; + } + + /** + * @param string $listId + * + * @return MailChimpEntity + */ + public function setListId(string $listId): MailChimpEntity + { + $this->listId = $listId; + return $this; + } + + /** + * @inheritdoc + */ + public static function fromArray(array $items) : SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + if (null !== $value) { + $obj = $obj->__set($property, $value); + } + } + if (isset($items[ 'list_id' ])) { + $obj->setListId($items[ 'list_id' ]); + } + return $obj; + } + + /** @inheritDoc */ + public function toArray(): array + { + $items = parent::toArray(); + $items = $this->recursiveArrayCast($items); + return $items; + } + + /** + * @param array $items + * @return array + */ + protected function recursiveArrayCast(array $items): array + { + foreach ($items as $key => $item) { + if (is_object($item) && method_exists($item, 'toArray')) { + $items[$key] = $item->toArray(); + } elseif (is_array($item)) { + $items[$key] = $this->recursiveArrayCast($item); + } + } + return $items; + } +} diff --git a/lib/Mailchimp/Entities/MailchimpFormConfig.php b/lib/Mailchimp/Entities/MailchimpFormConfig.php new file mode 100644 index 0000000..8251bb4 --- /dev/null +++ b/lib/Mailchimp/Entities/MailchimpFormConfig.php @@ -0,0 +1,208 @@ +processor]; + } + + /** + * @return string + */ + public function getId(): string + { + return is_string($this->id) ? $this->id : ''; + } + + /** + * @param string $id + * @return MailchimpFormConfig + */ + public function setId(string $id): MailchimpFormConfig + { + $this->id = $id; + return $this; + } + + + /** + * @return string + */ + public function getName(): string + { + return is_string($this->name) ? $this->name : ''; + } + + /** + * @param string $name + * @return MailchimpFormConfig + */ + public function setName(string $name): MailchimpFormConfig + { + $this->name = $name; + return $this; + } + + /** + * @return array + */ + public function getFields(): array + { + return is_array($this->fields) ? $this->fields : []; + } + + /** + * @param array $fields + * @return MailchimpFormConfig + */ + public function setFields(array $fields): MailchimpFormConfig + { + $this->fields = $fields; + return $this; + } + + /** + * @return array + */ + public function getProcessor(): array + { + return $this->processor; + } + + /** + * @param array $processor + */ + public function setProcessor(array $processor): MailchimpFormConfig + { + $this->processor = $processor; + return $this; + } + + + /** + * @return string + */ + protected function getSubmitButtonId(): string + { + return 'mc-submit'; + } + + protected function getEmailFieldId(): string + { + return 'mc-email'; + } + + /** + * @inheritDoc + */ + public function toArray(): array + { + $array = parent::toArray(); + $procesor = $array['processor']; + $array['processors'] = [$procesor]; + unset($array['processor']); + $array['fields'][] = [ + 'fieldType' => 'submit', + 'fieldId' => $this->getSubmitButtonId(), + 'label' => 'Subscribe' + ]; + $array['fields'][] = [ + 'fieldType' => 'email', + 'fieldId' => $this->getEmailFieldId(), + 'label' => 'Email' + ]; + $array['rows'] = [ + [ + 'rowId' => 'r1', + 'columns' => [ + [ + 'columnId' => 'r1-c1', + 'width' => '1/2', + 'fields' => [$this->getEmailFieldId()] + ], + [ + 'columnId' => 'r1-c2', + 'width' => '1/2', + 'fields' => [$this->getProcessor()['mergeFields'][0]] + ] + ] + ] + ]; + + if (isset($this->getProcessor()['mergeFields'][1])) { + $columns = [ + [ + 'columnId' => 'r2-c1', + 'width' => '1/2', + 'fields' => [$this->getProcessor()['mergeFields'][1]] + ], + + + ]; + if (isset($this->getProcessor()['mergeFields'][2])) { + $columns[] = [ + 'columnId' => 'r2-c2', + 'width' => '1/2', + 'fields' => [$this->getProcessor()['mergeFields'][2]] + ]; + } + $array['rows'][] = [ + 'rowId' => 'r2', + 'columns' => $columns + ]; + }; + $groupFields = $this->getProcessor()['groupFields']; + if (!empty($groupFields)) { + foreach ($groupFields as $fieldId) { + $array['rows'][] = [ + 'rowId' => "r-$fieldId", + 'columns' => [ + [ + 'columnId' => $fieldId, + 'width' => '1/1', + 'fields' => [$fieldId] + ], + ] + ]; + } + } + $array['rows'][] = [ + 'rowId' => "r-0", + 'columns' => [ + [ + 'columnId' => 'r0-c1', + 'width' => '1/1', + 'fields' => [$this->getSubmitButtonId()] + ], + ] + ]; + + return $array; + } +} diff --git a/lib/Mailchimp/Entities/MergeVar.php b/lib/Mailchimp/Entities/MergeVar.php new file mode 100644 index 0000000..650fec7 --- /dev/null +++ b/lib/Mailchimp/Entities/MergeVar.php @@ -0,0 +1,229 @@ +defaultValue; + } + + /** + * @param mixed $defaultValue + * + * @return MergeVar + */ + public function setDefaultValue($defaultValue) + { + $this->defaultValue = $defaultValue; + return $this; + } + + /** + * @return string + */ + public function getName(): string + { + return $this->name; + } + + /** + * @param string $name + * + * @return MergeVar + */ + public function setName(string $name): MergeVar + { + $this->name = $name; + return $this; + } + + /** + * @return string + */ + public function getType(): string + { + return isset($this->type)?$this->type:''; + } + + /** + * @param string $type + * + * @return MergeVar + */ + public function setType(string $type): MergeVar + { + $this->type = $type; + return $this; + } + + /** + * @return array + */ + public function getOptions(): array + { + return isset($this->options)?$this->options:[]; + } + + /** + * Returns size option, default is 0 + * @return int + */ + public function getSize(): int + { + return isset($this->options['size'])? (int)$this->options['size']:0; + } + /** + * @param array $options + * + * @return MergeVar + */ + public function setOptions(array $options): MergeVar + { + $this->options = $options; + return $this; + } + + /** + * @return string + */ + public function getValue(): string + { + return isset($this->value)?$this->value:''; + } + + /** + * @param string $value + * + * @return MergeVar + */ + public function setValue(string $value): MergeVar + { + $this->value = $value; + return $this; + } + + /** + * @return string + */ + public function getMergeId(): string + { + return isset($this->mergeId)?$this->mergeId:''; + } + + /** + * @param string $mergeId + * + * @return MergeVar + */ + public function setMergeId(string $mergeId): MergeVar + { + $this->mergeId = $mergeId; + return $this; + } + + /** + * @return mixed + */ + public function getTag() + { + return isset($this->tag)?$this->tag:''; + } + + /** + * @param mixed $tag + * + * @return MergeVar + */ + public function setTag($tag) + { + $this->tag = $tag; + return $this; + } + + /** + * @return bool + */ + public function getRequired(): bool + { + return isset($this->required)?$this->required:false; + } + + /** + * @param bool $required + * + * @return MergeVar + */ + public function setRequired(bool $required): MergeVar + { + $this->required = $required; + return $this; + } + + /** @inheritDoc */ + public static function fromArray(array $items): SimpleEntity + { + if (isset($items['options'])) { + $items['options'] = (array)$items['options']; + } + $obj = parent::fromArray($items); + if (isset($items['merge_id'])) { + $obj->setMergeId($items['merge_id']); + } + if (isset($items['mergeId'])) { + $obj->setMergeId($items['mergeId']); + } + if (isset($items['default_value'])) { + $obj->setDefaultValue($items['default_value']); + } + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/MergeVars.php b/lib/Mailchimp/Entities/MergeVars.php new file mode 100644 index 0000000..0f76627 --- /dev/null +++ b/lib/Mailchimp/Entities/MergeVars.php @@ -0,0 +1,159 @@ + $mergeVar) { + if ('list_id' === $property) { + $obj->setListId($mergeVar); + continue; + } + if (!is_array($mergeVar)) { + if (is_a($mergeVar, MergeVar::class)) { + $obj->addMergeVar($mergeVar); + continue; + } else { + $mergeVar = (array) $mergeVar; + } + } + $obj->addMergeVar(MergeVar::fromArray($mergeVar)); + } + + // Entity structure contains listId + if (isset($items['listId'])) { + $obj->setListId($items['listId']); + } + + return $obj; + } + + /** + * @param MergeVar $mergeVar + * + * @return MergeVars + */ + public function addMergeVar(MergeVar $mergeVar): MergeVars + { + if (!is_array($this->mergeVars)) { + $this->mergeVars = $this->getMergeVars(); + } + $this->mergeVars[$mergeVar->getTag()] = $mergeVar; + return $this; + } + + /** + * @param string $id + * + * @return MergeVar + * @throws Exception + */ + public function getMergeVar(string $id): MergeVar + { + if (!$this->hasMergeVar($id)) { + throw new Exception(); + } + return $this->getMergeVars()[$id]; + } + + /** + * Find a merge var by its tag + * + * @param string $tag + * + * @return null|MergeVar + */ + public function findMergeVarByTag(string $tag): ?MergeVar + { + /** @var MergeVar $mergeVar */ + foreach ($this->mergeVars as $mergeVar) { + if ($tag === $mergeVar->getTag()) { + return $mergeVar; + } + } + return null; + } + + /** + * @return array + */ + public function getMergeVars(): array + { + return is_array($this->mergeVars) ? $this->mergeVars : []; + } + + /** + * Remove merge var from collection + * + * @param string $id + * @return bool + */ + public function removeMergeVar(string $id): bool + { + if (!$this->hasMergeVar($id)) { + return false; + } + $mergeVars = $this->getMergeVars(); + if (isset($mergeVars[$id])) { + unset($mergeVars[$id]); + } else { + if (!empty($this->getMergeVars())) { + /** @var MergeVar $mergeVar */ + foreach ($this->getMergeVars() as $mergeVar) { + if ($id === $mergeVar->getTag()) { + unset($mergeVars[$mergeVar->getMergeId()]); + break; + } + } + } + } + $this->mergeVars = $mergeVars; + return true; + } + + /** + * Check if merge var is in collection + * + * @param string $mergeIdOrMergeTag + * @return bool + */ + public function hasMergeVar(string $mergeIdOrMergeTag): bool + { + if (isset($this->getMergeVars()[$mergeIdOrMergeTag])) { + return true; + } + if (!empty($this->getMergeVars())) { + /** @var MergeVar $mergeVar */ + foreach ($this->getMergeVars() as $mergeVar) { + if ($mergeIdOrMergeTag === $mergeVar->getTag()) { + return true; + } + } + } + return false; + } +} diff --git a/lib/Mailchimp/Entities/Responses/SubscriptionSuccessful.php b/lib/Mailchimp/Entities/Responses/SubscriptionSuccessful.php new file mode 100644 index 0000000..f6d06e1 --- /dev/null +++ b/lib/Mailchimp/Entities/Responses/SubscriptionSuccessful.php @@ -0,0 +1,20 @@ +id; + } + + /** + * Get name of interest + * @return string + */ + public function getName(): string + { + return isset($this->name) ? (string) $this->name : ''; + } + + /** + * @param string $id + * + * @return InterestCategory + */ + public function setId(string $id): Segment + { + $this->id = $id; + return $this; + } + + /** + * Is this segment a tag + * @return bool + */ + public function isTag(): bool + { + if( 'static' === $this->type || 'saved'===$this->type){ + $return = true; + }else{ + $return = false; + } + return $return; + } + + /** + * @inheritdoc + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + if (null !== $value) { + $obj = $obj->__set($property, $value); + } + } + if (isset($items['list_id'])) { + $obj->setListId($items['list_id']); + } + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/Segments.php b/lib/Mailchimp/Entities/Segments.php new file mode 100644 index 0000000..9f796dd --- /dev/null +++ b/lib/Mailchimp/Entities/Segments.php @@ -0,0 +1,137 @@ +listId = ''; + $this->segments = []; + } + + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + // Entity structure else response structure + if (isset($items['segments'])) { + $array = $items['segments']; + } else { + $array = $items; + } + + foreach ($array as $list) { + if (!is_array($list)) { + if (is_a($list, Segment::class)) { + $obj->addSegment($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addSegment(Segment::fromArray($list)); + } + + // Entity structure contains listId + if (isset($items['listId'])) { + $obj->setListId($items['listId']); + } + + + return $obj; + } + + /** + * Add a Segment to collection + * + * @param Segment $segment + * + * @return Segments + */ + public function addSegment(Segment $segment): Segments + { + $this->segments[$segment->getName()] = $segment; + return $this; + } + + /** + * Add a Tag Segment to collection; keyed on NAME, not Id + * + * @param Segment $segment + * + * @return Segments + */ + public function addTag(Segment $segment): Segments + { + $this->segments[$segment->getName()] = $segment; + return $this; + } + + /** + * Get a Segment from collection + * + * @param string $name + * + * @return Segment + * @throws Exception + */ + public function getSegment(string $name): Segment + { + if (!isset($this->segments[$name])) { + throw new Exception(); + } + return $this->segments[$name]; + } + + /** + * Get all Segments in collection + * + * @return Segment[] + */ + public function getSegments(): array + { + return $this->segments; + } + + /** + * Returns boolean if segment exists + * @param string $name + * @return bool + */ + public function hasSegment($name): bool + { + return isset($this->getSegments()[$name]); + } + + /** + * Return all tags in the collection, omitting 'saved' segments with options + * @return Segments + */ + public function getTags(): Segments + { + $obj = new static(); + + foreach ($this->segments as $segment) { + if ($segment->isTag()) { + $obj->addTag($segment); + } + } + + $obj->setListId($this->listId); + + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/SingleList.php b/lib/Mailchimp/Entities/SingleList.php new file mode 100644 index 0000000..a6f8090 --- /dev/null +++ b/lib/Mailchimp/Entities/SingleList.php @@ -0,0 +1,242 @@ +mergeFieldIds = []; + $this->groupFieldIds = []; + } + + /** + * Get ids of all merge fields + * + * @return array + */ + public function getMergeFieldIds(): array + { + return $this->mergeFieldIds; + } + + /** + * Get ids of all group fields + * + * @return array + */ + public function getGroupFieldIds(): array + { + return $this->groupFieldIds; + } + + + + + public function hasMergeFields() : bool + { + return ! empty($this->getMergeFieldsArray()); + } + protected function getMergeFieldsArray() : array + { + if (! $this->mergeFields || empty($this->getMergeFields()->toArray()['mergeVars'])) { + return []; + } + return $this->getMergeFields()->toArray(); + } + + protected function getGroupFieldsArray() : array + { + if (! $this->groupFields) { + return []; + } + return $this->getGroupFields()->toArray(); + } + + /** + * + * @param array $items + * + * @return SimpleEntity + */ + public static function fromArray(array $items): SimpleEntity + { + if (isset($items[ 'groupFields' ]) && is_array($items[ 'groupFields' ])) { + $items[ 'groupFields' ] = Groups::fromArray($items[ 'groupFields' ]); + } + + if (isset($items[ 'groups' ]) && is_array($items[ 'groups' ])) { + $items[ 'groupFields' ] = Groups::fromArray($items[ 'groups' ]); + } + if (isset($items[ 'mergeFields' ]) && is_array($items[ 'mergeFields' ])) { + if (isset($items[ 'mergeFields' ]['mergeVars'])&& is_array($items[ 'mergeFields' ]['mergeVars'])) { + $items['mergeFields'] = MergeVars::fromArray($items['mergeFields'][ 'mergeVars' ]); + } else { + $items['mergeFields'] = MergeVars::fromArray($items['mergeFields']); + } + } + return parent::fromArray($items); + } + + + /** + * @return MergeVars + */ + public function getMergeFields(): MergeVars + { + return $this->mergeFields; + } + + /** + * @param MergeVars $mergeFields + * + * @return SingleList + */ + public function setMergeFields(MergeVars $mergeFields): SingleList + { + $this->mergeFields = $mergeFields; + return $this; + } + + /** + * @return Groups + */ + public function getGroupFields(): Groups + { + return $this->groupFields; + } + + /** + * @param Groups $groupFields + * + * @return SingleList + */ + public function setGroupFields(Groups $groupFields): SingleList + { + $this->groupFields = $groupFields; + return $this; + } + + /** + * @return string + */ + public function getName(): string + { + return is_string($this->name) ? $this->name : ''; + } + + /** + * @param string $name + * + * @return SingleList + */ + public function setName(string $name): SingleList + { + $this->name = $name; + return $this; + } + + /** + * @return array + */ + public function getSegments(): array + { + return is_array($this->segments) ? $this->segments : []; + } + + /** + * @param array $segments + * + * @return SingleList + */ + public function setSegments(array $segments): SingleList + { + $this->segments = $segments; + return $this; + } + + /** + * @return int + */ + public function getAccountId(): int + { + return $this->accountId; + } + + /** + * @param int $accountId + * + * @return SingleList + */ + public function setAccountId(int $accountId = null): SingleList + { + $this->accountId = $accountId; + return $this; + } + + /** + * @return string + */ + public function getId(): string + { + return $this->id; + } + + /** + * @param string $id + * + * @return SingleList + */ + public function setId(string $id): SingleList + { + $this->id = $id; + return $this; + } + + /** @inheritDoc */ + public function getListId(): string + { + return $this->getId(); + } +} diff --git a/lib/Mailchimp/Entities/StandardSubscriberField.php b/lib/Mailchimp/Entities/StandardSubscriberField.php new file mode 100644 index 0000000..e0adb8c --- /dev/null +++ b/lib/Mailchimp/Entities/StandardSubscriberField.php @@ -0,0 +1,88 @@ +name) ? (string) $this->name : ''; + } + + /** + * Get title + * @return string + */ + public function getTitle(): string + { + return isset($this->title) ? (string) $this->title : ''; + } + + /** + * Get type + * @return string + */ + public function getType(): string + { + return isset($this->type) ? (string) $this->type : ''; + } + + /** + * Get allowed values + * @return string + */ + public function getAllowedValues(): array + { + return isset($this->allowedValues) ? (array) $this->allowedValues : []; + } + + /** + * @inheritdoc + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + if (null !== $value) { + $obj = $obj->__set($property, $value); + } + } + + return $obj; + } +} diff --git a/lib/Mailchimp/Entities/StandardSubscriberFields.php b/lib/Mailchimp/Entities/StandardSubscriberFields.php new file mode 100644 index 0000000..a023a63 --- /dev/null +++ b/lib/Mailchimp/Entities/StandardSubscriberFields.php @@ -0,0 +1,89 @@ +standardSubscriberFields = []; + } + + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + // Entity structure else response structure + if (isset($items['standardSubscriberFields'])) { + $array = $items['standardSubscriberFields']; + } else { + $array = $items; + } + + foreach ($array as $list) { + if (!is_array($list)) { + if (is_a($list, StandardSubscriberField::class)) { + $obj->addStandardSubscriberField($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addStandardSubscriberField(StandardSubscriberField::fromArray($list)); + } + + return $obj; + } + + /** + * Add a StandardSubscriberField to collection + * + * @param StandardSubscriberField $field + * + * @return StandardSubscriberFields + */ + public function addStandardSubscriberField(StandardSubscriberField $field): StandardSubscriberFields + { + $this->standardSubscriberFields[$field->getName()] = $field; + return $this; + } + + /** + * Get a StandardSubscriberField from collection + * + * @param string $name + * + * @return StandardSubscriberField + * @throws Exception + */ + public function getStandardSubscriberField(string $name): StandardSubscriberField + { + if (!isset($this->standardSubscriberFields[$name])) { + throw new Exception(); + } + return $this->standardSubscriberFields[$name]; + } + + /** + * Get all StandardSubscriberFields in collection + * + * @return StandardSubscriberFields[] + */ + public function getStandardSubscriberFields(): array + { + return $this->standardSubscriberFields; + } +} diff --git a/lib/Mailchimp/Entities/SubscribeGroups.php b/lib/Mailchimp/Entities/SubscribeGroups.php new file mode 100644 index 0000000..2b1ed70 --- /dev/null +++ b/lib/Mailchimp/Entities/SubscribeGroups.php @@ -0,0 +1,133 @@ +data)) { + $this->resetData(); + } + + if (!empty($this->data)) { + foreach ($this->groups->getGroups() as $group) { + if (array_key_exists($this->data, $group->getGroupId())) { + unset($this->data[$group->getGroupId()]); + } + } + } + + return $this->data; + } + + /** + * Set interest groups that are allowed + * + * @param Groups $groups + * + * @return $this + */ + public function setGroups(Groups $groups) + { + $this->groups = $groups; + $this->resetData(); + return $this; + } + + /** + * Set the value for one interest group - join or not + * + * @param string $groupId ID of group to join/ leave + * @param bool $join Set true to join or false to leave + * + * @return SubscribeGroups + */ + public function setGroupJoin(string $groupId, bool $join): SubscribeGroups + { + if (is_array($this->data) && array_key_exists($groupId, $this->data)) { + $this->data[$groupId] = $join; + } + return $this; + } + + /** + * Set the values for all interest groups - join or not + * + * @param array $options + * + * @return SubscribeGroups + * + * @throws Exception + */ + public function setGroupsJoins(array $options): SubscribeGroups + { + foreach ($options as $groupId => $join) { + if ($this->groups->getGroup($groupId)) { + if (is_array($join)) { + foreach ($join as $interest) { + $this->setGroupJoin($interest, true); + } + } else { + if (!is_null($join)) { + $this->setGroupJoin($join, true); + } + } + } + } + + return $this; + } + + + /** + * Reset join group data + */ + protected function resetData() + { + $this->data = []; + if (isset($this->groups)) { + /** @var Group $group */ + foreach ($this->groups->getGroups() as $group) { + if (in_array($group->getType(), ['checkboxes', 'radio', 'dropdown'])) { + try { + $categories = $this->groups->getCategoriesForGroup($group->getId()); + } catch (Exception $e) { + $categories = false; + } + if ($categories) { + foreach ($categories->toArray() as $interests) { + if (is_array($interests)) { + foreach ($interests as $interest) { + $this->data[$interest['id']] = false; + } + } elseif (is_string($interests)) { + $this->data[$interests] = false; + } + } + } + } + } + } + } +} diff --git a/lib/Mailchimp/Entities/SubscribeMergeVars.php b/lib/Mailchimp/Entities/SubscribeMergeVars.php new file mode 100644 index 0000000..b4fbee5 --- /dev/null +++ b/lib/Mailchimp/Entities/SubscribeMergeVars.php @@ -0,0 +1,115 @@ +mergeVars; + } + + + /** + * Reduce object to the form needed for API request + * + * @return array + */ + public function toArray(): array + { + if (! is_array($this->data)) { + $this->resetData(); + } + return $this->data; + } + + + /** + * Set a value for one merge field + * + * @param string $mergeTag Merge field to set value of + * @param mixed $value Value to set + * + * @return SubscribeMergeVars + */ + public function setMergeValue(string $mergeTag, $value) : SubscribeMergeVars + { + if (! is_array($this->data)) { + $this->resetData(); + } + if (array_key_exists($mergeTag, $this->data)) { + $this->data[$mergeTag] = $value; + } + return $this; + } + + /** + * Set all values for all merge fields + * + * @param array $values Array of values, keyed by tag or merge Id + * + * @return SubscribeMergeVars + * @throws \something\Mailchimp\Exception + */ + public function setMergeValues(array $values) : SubscribeMergeVars + { + foreach ($values as $mergeTagOrId => $value) { + if (! $mergeVar = $this->getMergeVars()->findMergeVarByTag($mergeTagOrId)) { + try { + $mergeVar = $this->getMergeVars()->getMergeVar($mergeTagOrId); + } catch (\Exception $e) { + continue; + } + } + + + if ($mergeVar) { + $this->setMergeValue($mergeVar->getTag(), $value); + } + } + + return $this; + } + + + /** + * @param MergeVars $mergeVars + * + * @return SubscribeMergeVars + */ + public function setMergeVars(MergeVars $mergeVars): SubscribeMergeVars + { + $this->mergeVars = $mergeVars; + return $this; + } + + protected function resetData() + { + if (! empty($this->mergeVars->getMergeVars())) { + /** @var MergeVar $mergeVar */ + foreach ($this->mergeVars->getMergeVars() as $mergeVar) { + $this->data[$mergeVar->getTag()] = $mergeVar->getDefaultValue(); + } + } + } +} diff --git a/lib/Mailchimp/Entities/Subscriber.php b/lib/Mailchimp/Entities/Subscriber.php new file mode 100644 index 0000000..df6b01d --- /dev/null +++ b/lib/Mailchimp/Entities/Subscriber.php @@ -0,0 +1,184 @@ +email_address = $email; + + return $this; + } + + /** + * Set the email type + * + * Allowed values html, text + * @param string $emailType + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\Subscriber + */ + public function setEmailType(string $emailType): Subscriber + { + + $allowedValues = array('html', 'text'); + + if (in_array($emailType, $allowedValues)) { + $this->email_type = $emailType; + } + + return $this; + } + + /** + * Set the email type + * + * Allowed values subscribed, unsubscribed, cleaned, pending, transactional + * @param string $status + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\Subscriber + */ + public function setStatus(string $status): Subscriber + { + + $allowedValues = array('subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional'); + + if (in_array($status, $allowedValues)) { + $this->status = $status; + } + + return $this; + } + + /** + * Add a merge var to request using merge var tag + * + * Confirmed through testing that merge var tag must be used, not id + * @param string $mergeVarTag + * @param mixed $value + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\Subscriber + */ + public function setMergeField(string $mergeVarTag, $value): Subscriber + { + $this->merge_fields[$mergeVarTag] = $value; + + return $this; + } + + /** + * Add an interest to the Subscriber entity + * @param string $interestId + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\Subscriber + */ + public function addInterest(string $interestId): Subscriber + { + $this->interests[$interestId] = true; + + return $this; + } + + /** + * Add a tag to the Subscriber entity + * @param string $tag + * @return \NFMailchimp\EmailCRM\Mailchimp\Entities\Subscriber + */ + public function addTag(string $tag): Subscriber + { + + $this->tags[] = $tag; + + return $this; + } + + /** + * Return the Subscriber email address + * @return string + */ + public function getEmailAddress(): string + { + return $this->email_address; + } +} diff --git a/lib/Mailchimp/Handlers/CreateFormBuilder.php b/lib/Mailchimp/Handlers/CreateFormBuilder.php new file mode 100644 index 0000000..3dbf055 --- /dev/null +++ b/lib/Mailchimp/Handlers/CreateFormBuilder.php @@ -0,0 +1,246 @@ +audienceDefinition = $audienceDefinition; + $this->formBuilder = $formBuilder; + + $this->constructFormBuilder(); + } + + /** + * Call methods that construct FormBuilder entity + */ + protected function constructFormBuilder() + { + $this->setFormTitle(); + $this->addMergeVars(); + $this->addInterestCategories(); + } + + /** + * Set the form title as Audience Definition name + */ + protected function setFormTitle() + { + $formTitle = $this->audienceDefinition->name; + + $this->formBuilder->setTitle($formTitle); + } + + /** + * Add MergeVars from AudienceDefinition as FormFields + */ + protected function addMergeVars() + { + $collection = $this->audienceDefinition->mergeFields->getMergeVars(); + + foreach ($collection as $mergeVar) { + $formField = $this->constructMergeVarField($mergeVar); + $this->formBuilder->addFormField($formField); + } + } + + /** + * Add InterestCategories as FormFields + */ + protected function addInterestCategories() + { + $collection = $this->audienceDefinition->interestCategories->getInterestCategories(); + + foreach ($collection as $interestCategory) { + $formField = $this->constructInterestCategoryField($interestCategory); + $this->formBuilder->addFormField($formField); + } + } + + + /** + * Constructs a form field from a merge var + * @param MergeVar $mergeVar + * @return FormField + */ + protected function constructMergeVarField(MergeVar $mergeVar): FormField + { + + $formField = new FormField(); + + // Mailchimp `tag` is the programmatic name + $formField->setId($mergeVar->getTag()); + + // Set label from MC name + $formField->setLabel($mergeVar->getName()); + + // Use method to select shared field type from MC field type + $formField->setType($this->selectFieldType($mergeVar)); + + // Set default value only if MC has a value + if ('' !== $mergeVar->getDefaultValue()) { + $formField->setDefault($mergeVar->getDefaultValue()); + } + + // Set required + if ($mergeVar->getRequired()) { + $formField->setRequired(true); + } + + // Set character limit if specified in MC + $options = $mergeVar->getOptions(); + if (isset($options['size'])) { + $formField->setCharacterLimit(intval($options['size'])); + } + + // If choices is selected, field has list options to select + // Mailchimp 'choices' <==> Form list options + if(isset($options['choices'])){ + + $optionsEntity = $this->constructMergeFieldOptions($options['choices']); + + $formField->setOptions($optionsEntity); + } + return $formField; + } + + /** + * Construct Options collection from array of Mailchimp 'choices' + * + * @param array $choices + * @return Options + */ + protected function constructMergeFieldOptions(array $choices): Options + { + $options = new Options(); + + foreach ($choices as $choice) { + $option = Option::fromArray([ + 'label'=>$choice, + 'value'=>$choice + ]); + + $options->addOption($option); + } + + return $options; + } + + /** + * Construct FormField from an InterestCategory + * @param InterestCategory $interestCategory + * @return FormField + */ + protected function constructInterestCategoryField(InterestCategory $interestCategory):FormField + { + $formField = new FormField(); + // Mailchimp `tag` is the programmatic name + $formField->setId($interestCategory->getId()); + + // Set label from MC name + $formField->setLabel($interestCategory->getTitle()); + + // Use method to select shared field type from MC field type + $formField->setType('multiselect'); + + // Set options + $formField->setOptions($this->constructInterestCategoryOptions($interestCategory->getId())); + + return $formField; + } + + /** + * Construct Options entity for a given InterestCategoryId + * @param string $interestCategoryId + * @return Options + */ + protected function constructInterestCategoryOptions(string $interestCategoryId):Options + { + /** @var Interest $interest */ + $options = new Options(); + $collection = $this->audienceDefinition->interests->getInterests(); + foreach ($collection as $interest) { + if ($interestCategoryId != $interest->getCategoryId()) { + continue; + } + + $option = new Option(); + $option->setLabel($interest->getName()); + $option->setValue($interest->getId()); + + $options->addOption($option); + } + + return $options; + } + + /** + * Selects a standard field type from Mailchimp's field type + * + * @param MergeVar $mergeVar + * @return string + */ + protected function selectFieldType(MergeVar $mergeVar): string + { + + $mailchimpFieldType = $mergeVar->getType(); + + $fieldType = 'textbox'; + switch ($mailchimpFieldType) { + case 'multiselect': + $fieldType = 'multiselect'; + break; + // Mailchimp term + case 'radio': + // NF term + case 'listradio': + $fieldType = 'listradio'; + break; + // Mailchimp term + case 'dropdown': + // NF term + case 'listselect': + $fieldType = 'listselect'; + break; + } + + return $fieldType; + } + + /** + * Get the Form Builder + * @return FormBuilder + */ + public function getFormBuilder(): FormBuilder + { + return $this->formBuilder; + } +} diff --git a/lib/Mailchimp/Handlers/SubscriberBuilder.php b/lib/Mailchimp/Handlers/SubscriberBuilder.php new file mode 100644 index 0000000..d9d1021 --- /dev/null +++ b/lib/Mailchimp/Handlers/SubscriberBuilder.php @@ -0,0 +1,259 @@ +audienceDefinition = $audienceDefinition; + + $this->subscriber = new Subscriber(); + + $this->subscriber->setListId($this->audienceDefinition->getListId()); + } + + /** + * Sets email address + * @param string $emailAddress + * @return SubscriberBuilder + */ + public function setEmailAddress(string $emailAddress): SubscriberBuilder + { + $this->subscriber->setEmailAddress($emailAddress); + + return $this; + } + + /** + * Sets email type + * @param string $emailType + * @return SubscriberBuilder + */ + public function setEmailType(string $emailType): SubscriberBuilder + { + $this->subscriber->setEmailType($emailType); + + return $this; + } + + /** + * Sets email status + * + * @param string $status + * @return SubscriberBuilder + */ + public function setStatus(string $status): SubscriberBuilder + { + $this->subscriber->setStatus($status); + + return $this; + } + + /** + * Adds value for Merge Var after ensuring Merge Var is part of AudienceDef + * + * @param string $mergeVarTag + * @param mixed $value + * @return SubscriberBuilder + */ + public function setMergeField(string $mergeVarTag, $value): SubscriberBuilder + { + $hasMergeField = $this->audienceDefinition->hasMergeVar($mergeVarTag); + + if ($hasMergeField) { + $value = $this->validateMergeVarValue($mergeVarTag, $value); + + $this->subscriber->setMergeField($mergeVarTag, $value); + } + + return $this; + } + + /** + * Forces string length no longer than size specified + * + * If a size limit is specified for the marge var, ensures value is a string + * and no longer than the specified character length + * + * @param string $mergeVarTag + * @param mixed $value + * @return mixed + */ + protected function validateMergeVarValue(string $mergeVarTag, $value) + { + $sizeLimit = $this->audienceDefinition->mergeVarSizeLimit($mergeVarTag); + + if (0 < $sizeLimit) { + $value = substr((string) $value, 0, $sizeLimit); + } + + return $value; + } + + /** + * Add an interest to Subscriber entity + * @param string $interestId + * @return SubscriberBuilder + */ + public function addInterest(string $interestId): SubscriberBuilder + { + $hasInterest = $this->audienceDefinition->hasInterest($interestId); + + if ($hasInterest) { + $this->subscriber->addInterest($interestId); + } + + return $this; + } + + /** + * Add a tag to the Subscriber entity + * @param string $tag + * @return SubscriberBuilder + */ + public function addTag(string $tag): SubscriberBuilder + { + $this->subscriber->addTag($tag); + + return $this; + } + + /** + * Constructs the request body for the Subscriber request + */ + public function constructRequestBody() + { + $requestBodyArray = []; + + $classVars = get_class_vars(get_class($this->subscriber)); + + foreach (array_keys($classVars) as $property) { + if (is_null($this->subscriber->$property)) { + continue; + } + + $requestBodyArray[$property] = $this->subscriber->$property; + } + + // email address is not part of request body + unset($requestBodyArray['email_address']); + unset($requestBodyArray['listId']); + + $this->requestBody = $requestBodyArray; + + $this->validateRequestBody(); + } + + /** + * Call methods that ensure request body is valid + */ + protected function validateRequestBody() + { + + $this->removeEmptyMergeFields(); + $this->removeEmptyInterests(); + } + + + /** + * Checks for empty merge_fields and unsets in requestBody + * + * @return void + */ + protected function removeEmptyMergeFields(): void + { + if (empty($this->requestBody['merge_fields'])) { + unset($this->requestBody['merge_fields']); + } + } + + /** + * Checks for empty interests and unsets in requestBody + * @return void + */ + protected function removeEmptyInterests(): void + { + if (empty($this->requestBody['interests'])) { + unset($this->requestBody['interests']); + } + } + + /** + * Returns the Subscriber entity + * @return Subscriber + */ + public function getSubscriber(): Subscriber + { + return $this->subscriber; + } + + /** + * Returns JSON encoded request body for Subscriber entity + * @return array + */ + public function getRequestBody(): array + { + if (!isset($this->requestBody)) { + $this->constructRequestBody(); + } + $this->validateRequestBody(); + + return $this->requestBody; + } + + /** + * Returns the subscriber list id + * @return string + */ + public function getListId(): string + { + return $this->subscriber->getListId(); + } + + /** + * Returns the subscriber email address + * @return string + */ + public function getEmailAddress(): string + { + return $this->subscriber->getEmailAddress(); + } + + /** + * Return AudienceDefinition + * @return AudienceDefinition + */ + public function getAudienceDefinition(): AudienceDefinition + { + return $this->audienceDefinition; + } +} diff --git a/lib/Mailchimp/Interfaces/MailchimpApi.php b/lib/Mailchimp/Interfaces/MailchimpApi.php new file mode 100644 index 0000000..aac1426 --- /dev/null +++ b/lib/Mailchimp/Interfaces/MailchimpApi.php @@ -0,0 +1,125 @@ +api_key = $api_key; + $this->api_user = 'api_key'; + + $dc = $this->getDataCenter($this->api_key); + + $this->endpoint = str_replace(self::DEFAULT_DATA_CENTER, $dc, $this->endpoint); + + return $this; + } + + /** + * Return HTTP client + * + * @return NfMailchimpHttpClientInterface + */ + private function getClient(): NfMailchimpHttpClientInterface + { + if (is_null($this->client)) { + + $this->client = new MailchimpWpHttpClient(); + } + + return $this->client; + } + + + /** + * Gets the ID of the data center associated with an API key. + * + * @param string $api_key + * The Mailchimp API key. + * + * @return string + * The data center ID. + */ + private function getDataCenter($api_key) + { + $api_key_parts = explode('-', $api_key); + + return (isset($api_key_parts[1])) ? $api_key_parts[1] : self::DEFAULT_DATA_CENTER; + } + + /** + * Gets information about all lists owned by the authenticated account. + * + * @param array $parameters + * Associative array of optional request parameters. + * + * @return object + * + * @see http://developer.mailchimp.com/documentation/mailchimp/reference/lists/#read-get_lists + */ + public function getLists($parameters = []) + { + return $this->request('GET', '/lists', NULL, $parameters); + } + + /** + * Gets a Mailchimp list. + * + * @param string $list_id + * The ID of the list. + * @param array $parameters + * Associative array of optional request parameters. + * + * @return object + * + * @see http://developer.mailchimp.com/documentation/mailchimp/reference/lists/#read-get_lists_list_id + */ + public function getList($list_id, $parameters = []) + { + $tokens = [ + 'list_id' => $list_id, + ]; + + return $this->request('GET', '/lists/{list_id}', $tokens, $parameters); + } + + /** + * Gets information about all interest categories associated with a list. + * + * @param string $list_id + * The ID of the list. + * @param array $parameters + * Associative array of optional request parameters. + * + * @return object + * + * @see http://developer.mailchimp.com/documentation/mailchimp/reference/lists/interest-categories/#read-get_lists_list_id_interest_categories + */ + public function getInterestCategories($list_id, $parameters = []) + { + $tokens = [ + 'list_id' => $list_id, + ]; + + return $this->request('GET', '/lists/{list_id}/interest-categories', $tokens, $parameters); + } + + + /** + * Gets information about all interests associated with an interest category. + * + * @param string $list_id + * The ID of the list. + * @param string $interest_category_id + * The ID of the interest category. + * @param array $parameters + * Associative array of optional request parameters. + * + * @return object + * + * @see http://developer.mailchimp.com/documentation/mailchimp/reference/lists/interest-categories/interests/#read-get_lists_list_id_interest_categories_interest_category_id_interests + */ + public function getInterests($list_id, $interest_category_id, $parameters = []) + { + $tokens = [ + 'list_id' => $list_id, + 'interest_category_id' => $interest_category_id, + ]; + + return $this->request('GET', '/lists/{list_id}/interest-categories/{interest_category_id}/interests', $tokens, $parameters); + } + + + + /** + * Gets merge fields associated with a Mailchimp list. + * + * @param string $list_id + * The ID of the list. + * @param array $parameters + * Associative array of optional request parameters. + * + * @return object + * + * @see http://developer.mailchimp.com/documentation/mailchimp/reference/lists/merge-fields/#read-get_lists_list_id_merge_fields + */ + public function getMergeFields($list_id, $parameters = []) + { + $tokens = [ + 'list_id' => $list_id, + ]; + + return $this->request('GET', '/lists/{list_id}/merge-fields', $tokens, $parameters); + } + + + + /** + * Adds a new or update an existing member of a Mailchimp list. + * + * @param string $list_id + * The ID of the list. + * @param string $email + * The member's email address. + * @param array $parameters + * Associative array of optional request parameters. + * @param bool $batch + * TRUE to create a new pending batch operation. + * + * @return object + * + * @see http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#edit-put_lists_list_id_members_subscriber_hash + */ + public function addOrUpdateMember($list_id, $email, $parameters = []) + { + $tokens = [ + 'list_id' => $list_id, + 'subscriber_hash' => md5(strtolower($email)), + ]; + + $parameters += [ + 'email_address' => $email, + ]; + + return $this->request('PUT', '/lists/{list_id}/members/{subscriber_hash}', $tokens, $parameters); + } + + + + /** + * Gets information about segments associated with a Mailchimp list. + * + * @param string $list_id + * The ID of the list. + * @param array $parameters + * Associative array of optional request parameters. + * + * @return object + * + * @see http://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#read-get_lists_list_id_segments + */ + public function getSegments($list_id, $parameters = []) + { + $tokens = [ + 'list_id' => $list_id, + ]; + + return $this->request('GET', '/lists/{list_id}/segments', $tokens, $parameters); + } + + + /** + * Makes a request to the Mailchimp API. + * + * @param string $method + * The REST method to use when making the request. + * @param string $path + * The API path to request. + * @param array $tokens + * Associative array of tokens and values to replace in the path. + * @param array $parameters + * Associative array of parameters to send in the request body. + * @param bool $batch + * TRUE if this request should be added to pending batch operations. + * @param bool $returnAssoc + * TRUE to return Mailchimp API response as an associative array. + * + * @return mixed + * Object or Array if $returnAssoc is TRUE. + * + * @throws MailchimpAPIException + */ + public function request($method, $path, $tokens = NULL, $parameters = []) + { + if (!empty($tokens)) { + foreach ($tokens as $key => $value) { + $path = str_replace('{' . $key . '}', $value, $path); + } + } + + // Set default request options with auth header. + $options = [ + 'headers' => [ + 'Authorization' => $this->api_user . ' ' . $this->api_key, + ], + ]; + + // Add trigger error header if a debug error code has been set. + if (!empty($this->debug_error_code)) { + $options['headers']['X-Trigger-Error'] = $this->debug_error_code; + } + + return $this->getClient()->handleRequest($method, $this->endpoint . $path, $options, $parameters); + } + + /** + * Set the value of client + * + * @return MailchimpApi + */ + public function setClient($client): MailchimpApi + { + $this->client = $client; + + return $this; + } +} diff --git a/lib/NfBridge/Actions/AutogenerateForm.php b/lib/NfBridge/Actions/AutogenerateForm.php new file mode 100644 index 0000000..185eb59 --- /dev/null +++ b/lib/NfBridge/Actions/AutogenerateForm.php @@ -0,0 +1,326 @@ +actionEntity = $actionEntity; + $this->standardApiFormFields = $standardApiFormFields; + $this->customApiFormFields = $customApiFormFields; + + // Set a default value + // Probably fully redundant and handle() requires a title, + // but should something change, we ensure it always has one + $this->formTitle = $this->actionEntity->getNicename(); + } + + /** + * Construct a Ninja Form per set FormFields, Action Configuration, and title + * @param string $listId + * @param string $formTitle + */ + public function handle(string $formTitle) + { + + $this->formTitle = $formTitle; + + $this->constructApiFields(); + + $this->constructNinjaFormWithAction(); + } + + /** + * Combine standard- and custom- ApiFormFields into a single collection + */ + protected function constructApiFields() + { + + $combined = array_merge($this->standardApiFormFields->toArray(), $this->customApiFormFields->toArray()); + + $this->apiFormFields = FormFields::fromArray($combined); + } + + /** + * Construct a new NF form per FormField and ActionConfiguration + * + * @return void + */ + public function constructNinjaFormWithAction(): void + { + $this->initializeForm(); + + $this->setNfFormTitle(); + + $this->addFormFields(); + + $this->addSubmitButton(); + + $this->addCreateEntryAction(); + + $this->addSaveAction(); + + $this->addSuccessMessageAction(); + + $this->nfForm->save(); + } + + /** + * Initialize a new form + */ + protected function initializeForm() + { + $this->nfForm = Ninja_Forms()->form(); + $this->nfForm->save(); + $this->formId = $this->nfForm->get_id(); + } + + /** + * Set the NF form title + */ + protected function setNfFormTitle() + { + + $this->nfForm->get()->update_settings( + [ + 'title' => $this->formTitle + ] + ); + } + + /** + * Add form fields + */ + protected function addFormFields() + { + + foreach ($this->apiFormFields->getFields() as $key => $field) { + $nfField = $this->nfForm->field()->get(); + // increment order + $this->order++; + + $settings = array( + 'type' => $field->getType(), + 'label' => $field->getLabel(), + 'label_post' => 'inside', + 'required' => $field->getRequired(), + 'key' => $key, + 'order' => $this->order + ); + + if (!empty($field->getOptions()->toArray())) { + $settings['options'] = $field->getOptions()->toArray(); + } + + if (0 !== $field->getCharacterLimit()) { + $settings['input_limit'] = $field->getCharacterLimit(); + } + + $nfField->update_settings($settings)->save(); + + $this->addActionFieldMap($key); + } + } + + /** + * Add submit button to the form + * @return void + */ + protected function addSubmitButton(): void + { + $nfField = $this->nfForm->field()->get(); + + $settings = array( + 'type' => 'submit', + 'label' => 'Submit', + 'label_post' => 'inside', + 'key' => 'submit' + ); + $nfField->update_settings($settings)->save(); + } + + /** + * Add action field map for given field key + * @param string $key + * @return void + */ + protected function addActionFieldMap(string $key): void + { + + $actionMetaKey = $key; + $actionMetaValue = '{field:' . $key . '}'; + + $this->actionFieldMap[$actionMetaKey] = $actionMetaValue; + } + + /** + * Add the action to the form + */ + protected function addCreateEntryAction() + { + $action = $this->nfForm->action()->get(); + + $this->actionFieldMap['type'] = $this->actionEntity->getName(); + $this->actionFieldMap['label'] = $this->actionEntity->getNicename(); + $this->actionFieldMap['active'] = '1'; + + $action->update_settings($this->actionFieldMap); + + $action->save(); + } + + /** + * Add Store Submission (programmatic name: save) to the form + * + */ + protected function addSaveAction() + { + $action = $this->nfForm->action()->get(); + + $actionMeta = [ + 'type' => 'save', + 'label' => 'Store Submission', + 'active' => '1' + ]; + + + $action->update_settings($actionMeta); + + $action->save(); + } + + /** + * Add Store Submission (programmatic name: save) to the form + * + */ + protected function addSuccessMessageAction() + { + $action = $this->nfForm->action()->get(); + + $actionMeta = [ + 'type' => 'successmessage', + 'label' => 'Success Message', + 'success_msg' => '

Your form has been successfully submitted.


', + 'active' => '1' + ]; + + + $action->update_settings($actionMeta); + + $action->save(); + } + + /** + * Get the newly created form Id + * @return int + */ + public function getFormId(): int + { + return $this->formId; + } + + /** + * Get the constructed Ninja Form + * @return NF_Abstracts_ModelFactory + */ + public function getNinjaForm(): NF_Abstracts_ModelFactory + { + return $this->nfForm; + } +} diff --git a/lib/NfBridge/Actions/ConfigureApiSettings.php b/lib/NfBridge/Actions/ConfigureApiSettings.php new file mode 100644 index 0000000..148f213 --- /dev/null +++ b/lib/NfBridge/Actions/ConfigureApiSettings.php @@ -0,0 +1,92 @@ +apiSettings = $apiSettings; + $this->constructSettingsConfig(); + } + + /** + * Iterate ApiSettings to construct NF Settings + */ + protected function constructSettingsConfig() + { + $settingsConfig = array(); + /** @var ApiSetting $setting */ + foreach ((array) $this->apiSettings->getApiSettings() as $setting) { + $type = $this->selectSettingType($setting->getExpectedDataType()); + + if ('none' === $type) { + continue; + } + + $settingsConfig[$setting->getId()] = array( + 'id' => $setting->getId(), + 'type' => $type, + 'label' => $setting->getLabel() + ); + } + + $this->settingsConfig = $settingsConfig; + } + + /** + * Return the correct NF setting field type for the expected data type + * @param string $expectedDataType + * @return string + */ + protected function selectSettingType(string $expectedDataType) + { + $type = 'textbox'; + + switch ($expectedDataType) { + case 'externallySetString': + $type = 'html'; + break; + case 'passThrough': + $type = 'none'; + break; + case 'userProvidedString': + default: + } + + return $type; + } + + /** + * Return configured NF settings array + * @return array + */ + public function getSettingsConfig() + { + return $this->settingsConfig; + } +} diff --git a/lib/NfBridge/Actions/ConstructActionSetting.php b/lib/NfBridge/Actions/ConstructActionSetting.php new file mode 100644 index 0000000..7801ae2 --- /dev/null +++ b/lib/NfBridge/Actions/ConstructActionSetting.php @@ -0,0 +1,76 @@ + $name, + 'label' => $label, + 'group' => 'primary', + 'type' => 'textbox', + 'use_merge_tags' => 1, + 'width' => 'full' + ); + + if ('' !== $value) { + $settingArray['value'] = $value; + } + + $actionSetting = ActionSetting::fromArray($settingArray); + + return $actionSetting; + } + + /** + * Adds toggle setting to action settings + * @param string $name + * @param string $label + * @param int $value + */ + public function createToggleSetting(string $name, string $label, int $value = 0): ActionSetting + { + + + $settingArray = array( + 'name' => $name, + 'label' => $label, + 'group' => 'primary', + 'type' => 'textbox', + 'use_merge_tags' => 1, + 'width' => 'full' + ); + + if (0 !== $value) { + $settingArray['value'] = 1; + } else { + $settingArray['value'] = 0; + } + + $actionSetting = ActionSetting::fromArray($settingArray); + + return $actionSetting; + } +} diff --git a/lib/NfBridge/Actions/ConstructActionSettings.php b/lib/NfBridge/Actions/ConstructActionSettings.php new file mode 100644 index 0000000..cbb8108 --- /dev/null +++ b/lib/NfBridge/Actions/ConstructActionSettings.php @@ -0,0 +1,76 @@ +actionSettings = new ActionSettings(); + } + + /** + * Adds field mapping textbox to action settings + * @param string $name + * @param string $label + * @param string $value + */ + public function addTextboxFieldMap(string $name, string $label, string $value): ActionSettings + { + /** @var ConstructActionSetting $creator */ + /** @var ActionSetting $actionSetting */ + $creator = new ConstructActionSetting(); + + $actionSetting = $creator->createTextboxFieldMap($name, $label, $value); + + $this->actionSettings->addActionSetting($actionSetting); + + return $this->actionSettings; + } + + /** + * Adds toggle setting to action settings + * @param string $name + * @param string $label + * @param int $value + */ + public function addToggleSetting(string $name, string $label, int $value): ActionSettings + { + /** @var ConstructActionSetting $creator */ + /** @var ActionSetting $actionSetting */ + $creator = new ConstructActionSetting(); + + $actionSetting = $creator->createToggleSetting($name, $label, $value); + + $this->actionSettings->addActionSetting($actionSetting); + + return $this->actionSettings; + } + + /** + * + * @return ActionSettings + */ + public function getActionSettings(): ActionSettings + { + return $this->actionSettings; + } +} diff --git a/lib/NfBridge/Actions/CreateAddNewModal.php b/lib/NfBridge/Actions/CreateAddNewModal.php new file mode 100644 index 0000000..e8f6468 --- /dev/null +++ b/lib/NfBridge/Actions/CreateAddNewModal.php @@ -0,0 +1,132 @@ +modal = $modal; + + $this->restEndpoint = $restEndpoint; + + $this->nonceField = $nonceField; + + $this->constructModalContent(); + + $this->addFormTitleInput(); + + $this->closeModalContent(); + + return $this->modal; + } + + + /** + * Construct full markup from incoming modal content + * + * Incoming modal content does not include markup for button or title input + * This method adds opening and closing div along with input box for title + * and button with link to endpoint + */ + protected function constructModalContent() + { + + $array = $this->modal->toArray(); + + $incomingContent = $array['modalContent']; + + $this->modal->setModalContent(''); + } +} diff --git a/lib/NfBridge/Actions/GetApiSettingsValues.php b/lib/NfBridge/Actions/GetApiSettingsValues.php new file mode 100644 index 0000000..493645d --- /dev/null +++ b/lib/NfBridge/Actions/GetApiSettingsValues.php @@ -0,0 +1,72 @@ +apiSettings = $apiSettings; + } + + /** + * Get API settings stored in core plugin + * + * @return array + */ + public function getApiSettingsValues(): array + { + + /** @var ApiSetting $apiSetting */ + foreach ($this->apiSettings->getApiSettings() as $apiSetting) { + $key = $apiSetting->getId(); + + $expectedDataType = $apiSetting->getExpectedDataType(); + + switch ($expectedDataType) { + case 'userProvidedString': + case 'externallySetString': + $value = Ninja_Forms()->get_setting($key); + + $this->apiSettingsValues[$key] = $value; + break; + case 'passThrough': + $value = $apiSetting->getLabel(); + + $this->apiSettingsValues[$key] = $value; + break; + case 'bool': + default: + break; + } + } + + return $this->apiSettingsValues; + } +} diff --git a/lib/NfBridge/Actions/HandleProcessData.php b/lib/NfBridge/Actions/HandleProcessData.php new file mode 100644 index 0000000..61a37cc --- /dev/null +++ b/lib/NfBridge/Actions/HandleProcessData.php @@ -0,0 +1,70 @@ +data = $data; + $this->actionKey = $actionKey; + } + + /** + * Add a form error + * @param string $message + * @return \NFMailchimp\EmailCRM\NfBridge\Actions\HandleProcessData + */ + public function addFormError(string $message): HandleProcessData + { + $this->data['errors']['form'][$this->actionKey] = $message; + + return $this; + } + + + /** + * Append ResponseData array + * @param array $responseData + */ + public function appendResponseData($responseData): HandleProcessData + { + $this->data['extra'][$this->actionKey]['responseData'][]=$responseData; + + return $this; + } + + + /** + * Return process $data array + * @return array + */ + public function toArray():array + { + return $this->data; + } +} diff --git a/lib/NfBridge/Actions/NewsletterAction.php b/lib/NfBridge/Actions/NewsletterAction.php new file mode 100644 index 0000000..967b7fa --- /dev/null +++ b/lib/NfBridge/Actions/NewsletterAction.php @@ -0,0 +1,120 @@ +setActionProperties(); + parent::__construct(); + $this->setActionSettings(); + } + /** + * Set your own action properties here + * + * $this->_name = 'replace-me'; + * $this->_nicename = 'Replace me(translateable)'; + * $this->_tags = array(); + * $this->_timing = 'normal'; + * $this->_priority = '10'; + * @return void + */ + abstract protected function setActionProperties(): void; + + /** + * Set your own action properties here + * + * $this->_settings['key']=[actionSettingsArray] + * @return void + */ + abstract protected function setActionSettings(): void; + + /** + * Return array of lists + * + * Indexed array of associative arrays + * + * array keys: 'value'=>(string) 'label'=>(string) 'fields'=>(array) 'groups'=>(array) + * @return array + */ + abstract protected function get_lists(); + + /** @inheritDoc */ + public function process($actionSettings, $formId, $data): array + { + $this->instantiateActionProcessor(); + + $actionSettingsDataHandler = (new ActionSettingsDataHandler())->setActionSettings($actionSettings); + $submissionDataDataHandler = (new SubmissionDataDataHandler()) + ->setSubmissionData($data) + ->setActionKey($this->getActionKey()); + + $this->constructRuntimeData($actionSettings, $formId, $data); + + $processAction = $this->instantiateActionProcessor(); + + $submissionDataDataHandlerAfterProcessing = $processAction->process($actionSettingsDataHandler, $formId, $submissionDataDataHandler,$this->runtimeData); + + return $submissionDataDataHandlerAfterProcessing->getData(); + } + + /** + * Instantiate your own Action Processor + * + * @return InterfacesProcessAction + */ + abstract protected function instantiateActionProcessor(): InterfacesProcessAction; + + /** + * Use raw process data to adjust runtime data passed into ProcessAction + * + * @param array $actionSettings + * @param [type] $formId + * @param array $data + * @return void + */ + protected function constructRuntimeData(array $actionSettings, $formId, array $data):void{} + + /** + * Return the action key used to register action + * + * @return string + */ + public function getActionKey(): string + { + return $this->_name; + } +} diff --git a/lib/NfBridge/Actions/NfAction.php b/lib/NfBridge/Actions/NfAction.php new file mode 100644 index 0000000..d86011d --- /dev/null +++ b/lib/NfBridge/Actions/NfAction.php @@ -0,0 +1,433 @@ +actionEntity = $actionEntity; + + $this->processHandler = $processHandler; + + $this->formProcessorsFactory = $formProcessorsFactory; + + $this->wpHooks = $wpHooks; + + $this->extractParameters(); + + $this->initActionSettings(); + + $this->constructPluginSettings(); + + $this->constructPluginSettingsGroup(); + } + + /** + * Extract action entity to properties + */ + protected function extractParameters() + { + $this->name = $this->actionEntity->getName(); + + $this->nicename = $this->actionEntity->getNicename(); + + $this->tags = $this->actionEntity->getTags(); + + $this->timing = $this->actionEntity->getTiming(); + + $this->priority = $this->actionEntity->getPriority(); + + $this->actionSettings = $this->actionEntity->getActionSettings(); + + $this->apiSettings = $this->actionEntity->getApiSettings(); + } + + /** + * Initialize action settings + */ + public function initActionSettings() + { + + $this->settingsAll = $this->wpHooks->applyFilters('ninja_forms_actions_settings_all', $this->settingsAll); + + if (!empty($this->settingsOnly)) { + $this->settings = array_merge($this->settings, $this->settingsOnly); + } else { + $this->settings = array_merge($this->settingsAll, $this->settings); + $this->settings = array_diff($this->settings, $this->settingsExclude); + } + + $this->settings = $this->loadSettings($this->settings); + + $this->settings = array_merge($this->settings, $this->actionSettings->outputConfiguration()); + } + + /** + * Construct plugins settings for the NF Action + */ + protected function constructPluginSettings() + { + + $settingsConfigObj = $this->formProcessorsFactory->getConfigureApiSettings($this->apiSettings); + + $this->pluginSettings = $settingsConfigObj->getSettingsConfig(); + } + + /** + * Construct group for the plugin settings + */ + protected function constructPluginSettingsGroup() + { + + $id = $this->apiSettings->getId(); + + $label = $this->apiSettings->getLabel(); + + $this->pluginSettingsGroup = [ + 'id' => $id, + 'label' => $label + ]; + } + + /** + * Return NF Action plugin settings + * @return array + */ + public function getPluginSettings() + { + + $id = $this->apiSettings->getId(); + + $nfPluginSettings[$id] = $this->pluginSettings; + + return $nfPluginSettings; + } + + /** + * Return NF Action plugin settings group + * @return array + */ + public function getPluginSettingsGroup() + { + $id = $this->apiSettings->getId(); + + $nfPluginGroup[$id] = $this->pluginSettingsGroup; + + return $nfPluginGroup; + } + + /** + * Save + */ + public function save($action_settings) + { + //@todo: Add save object + } + + /** + * NF method called at form submission + * + * @param array $actionSettings NF Action settings at form submission + * @param int $formId + * @param array $data NF $data passed at form submission + * @return array + */ + public function process($actionSettings, $formId, $data) + { + + $extractedData =$this->processHandler->extractFormFieldProcessingData($data); + + if (!empty($extractedData)) { + $actionSettings= array_merge($actionSettings, $extractedData); + } + + $submissionData = $this->formProcessorsFactory->getSubmissionData( + $actionSettings, + $this->actionSettings, + $this->apiSettings + ); + + $form = $this->formProcessorsFactory + ->getForm(Ninja_Forms()->form($formId)); + + $this->processHandler->handle($submissionData, $form); + + // after developing process data, append to $data + return $data; + } + + /** + * Get Timing + * + * Returns the timing for an action. + * + * @return mixed + */ + public function get_timing() + { + $timing = array('early' => -1, 'normal' => 0, 'late' => 1); + + return intval($timing[$this->timing]); + } + + /** + * Get Priority + * + * Returns the priority for an action. + * + * @return int + */ + public function get_priority() + { + return intval($this->priority); + } + + /** + * Get Name + * + * Returns the name of an action. + * + * @return string + */ + public function get_name() + { + return $this->name; + } + + /** + * Get Nicename + * + * Returns the nicename of an action. + * + * @return string + */ + public function get_nicename() + { + return $this->nicename; + } + + /** + * Get Section + * + * Returns the drawer section for an action. + * + * @return string + */ + public function get_section() + { + return $this->section; + } + + /** + * Get Image + * + * Returns the url of a branded action's image. + * + * @return string + */ + public function get_image() + { + return $this->image; + } + + /** + * Get Settings + * + * Returns the settings for an action. + * + * @return array|mixed + */ + public function get_settings() + { + return $this->settings; + } + + /** + * Sort Actions + * + * A static method for sorting two actions by timing, then priority. + * + * @param $a + * @param $b + * @return int + */ + public static function sort_actions($a, $b) + { + if (!isset(Ninja_Forms()->actions[$a->get_setting('type')])) { + return 1; + } + if (!isset(Ninja_Forms()->actions[$b->get_setting('type')])) { + return 1; + } + + $a->timing = Ninja_Forms()->actions[$a->get_setting('type')]->get_timing(); + $a->priority = Ninja_Forms()->actions[$a->get_setting('type')]->get_priority(); + + $b->timing = Ninja_Forms()->actions[$b->get_setting('type')]->get_timing(); + $b->priority = Ninja_Forms()->actions[$b->get_setting('type')]->get_priority(); + + // Compare Priority if Timing is the same + if ($a->timing == $b->timing) { + return $a->priority > $b->priority ? 1 : -1; + } + + // Compare Timing + return $a->timing < $b->timing ? 1 : -1; + } + + /** + * Loads settings array from FieldSettings config file + * @param array $onlySettings + * @return array + */ + protected function loadSettings($onlySettings = array()) + { + $settings = array(); + + // Loads a settings array from the FieldSettings configuration file. + $allSettings = \Ninja_Forms::config('ActionSettings'); + + foreach ($onlySettings as $setting) { + if (isset($allSettings[$setting])) { + $settings[$setting] = $allSettings[$setting]; + } + } + + return $settings; + } +} diff --git a/lib/NfBridge/Actions/NfNewsletterAction.php b/lib/NfBridge/Actions/NfNewsletterAction.php new file mode 100644 index 0000000..a8aafa5 --- /dev/null +++ b/lib/NfBridge/Actions/NfNewsletterAction.php @@ -0,0 +1,587 @@ +actionEntity = $actionEntity; + + $this->processHandler = $processHandler; + + $this->formProcessorsFactory = $formProcessorsFactory; + + $this->wpHooks = $wpHooks; + + $this->extractParameters(); + + $this->initActionSettings(); + + $this->constructPluginSettings(); + + $this->constructPluginSettingsGroup(); + + $this->newsletterExtension = $newsletterExtension; + + if (!$this->transient) { + $this->transient = $this->get_name() . '_newsletter_lists'; // Must match NF Newsletter Abstract + } + + $this->wpHooks->addAction('wp_ajax_nf_' . $this->name . '_get_lists', array($this, 'getLists')); + + $this->getListSettings(); + } + + + + /** + * Extract action entity to properties + */ + protected function extractParameters() + { + $this->name = $this->actionEntity->getName(); + + $this->nicename = $this->actionEntity->getNicename(); + + $this->tags = $this->actionEntity->getTags(); + + $this->timing = $this->actionEntity->getTiming(); + + $this->priority = $this->actionEntity->getPriority(); + + $this->actionSettings = $this->actionEntity->getActionSettings(); + + $this->apiSettings = $this->actionEntity->getApiSettings(); + } + + + /** + * Initialize action settings + */ + public function initActionSettings() + { + + $this->settingsAll = $this->wpHooks->applyFilters('ninja_forms_actions_settings_all', $this->settingsAll); + + if (!empty($this->settingsOnly)) { + $this->settings = array_merge($this->settings, $this->settingsOnly); + } else { + $this->settings = array_merge($this->settingsAll, $this->settings); + $this->settings = array_diff($this->settings, $this->settingsExclude); + } + + $this->settings = $this->loadSettings($this->settings); + + $this->settings = array_merge($this->settings, $this->actionSettings->outputConfiguration()); + } + + + /** + * Construct plugins settings for the NF Action + */ + protected function constructPluginSettings() + { + + $settingsConfigObj = $this->formProcessorsFactory->getConfigureApiSettings($this->apiSettings); + + $this->pluginSettings = $settingsConfigObj->getSettingsConfig(); + } + + + /** + * Construct group for the plugin settings + */ + protected function constructPluginSettingsGroup() + { + + $id = $this->apiSettings->getId(); + + $label = $this->apiSettings->getLabel(); + + $this->pluginSettingsGroup = [ + 'id' => $id, + 'label' => $label + ]; + } + + /** + * Return NF Action plugin settings + * @return array + */ + public function getPluginSettings() + { + + $id = $this->apiSettings->getId(); + + $nfPluginSettings[$id] = $this->pluginSettings; + + return $nfPluginSettings; + } + + /** + * Return NF Action plugin settings group + * @return array + */ + public function getPluginSettingsGroup() + { + $id = $this->apiSettings->getId(); + + $nfPluginGroup[$id] = $this->pluginSettingsGroup; + + return $nfPluginGroup; + } + + /** + * Save + */ + public function save($action_settings) + { + //@todo: Add save object + } + + /** + * NF method called at form submission + * + * @param array $actionSettings NF Action settings at form submission + * @param int $formId + * @param array $data NF $data passed at form submission + * @return array + */ + public function process($actionSettings, $formId, $data) + { + // provide standardized handling of submission data + $dataHandler = new HandleProcessData($data, $this->name); + + $extractedData =$this->processHandler->extractFormFieldProcessingData($data); + + if (!empty($extractedData)) { + $actionSettings= array_merge($actionSettings, $extractedData); + } + + $submissionData = $this->formProcessorsFactory->getSubmissionData( + $actionSettings, + $this->actionSettings, + $this->apiSettings + ); + + $form = $this->formProcessorsFactory + ->getForm(Ninja_Forms()->form($formId)); + + $responseDataArray = $this->processHandler->handle($submissionData, $form); + + // append a single response data entry to the process data + $dataHandler->appendResponseData($responseDataArray); + + return $dataHandler->toArray(); + } + + /** + * Get Timing + * + * Returns the timing for an action. + * + * @return mixed + */ + public function get_timing() + { + $timing = array('early' => -1, 'normal' => 0, 'late' => 1); + + return intval($timing[$this->timing]); + } + + /** + * Get Priority + * + * Returns the priority for an action. + * + * @return int + */ + public function get_priority() + { + return intval($this->priority); + } + + /** + * Get Name + * + * Returns the name of an action. + * + * @return string + */ + public function get_name() + { + return $this->name; + } + + /** + * Get Nicename + * + * Returns the nicename of an action. + * + * @return string + */ + public function get_nicename() + { + return $this->nicename; + } + + /** + * Get Section + * + * Returns the drawer section for an action. + * + * @return string + */ + public function get_section() + { + return $this->section; + } + + /** + * Get Image + * + * Returns the url of a branded action's image. + * + * @return string + */ + public function get_image() + { + return $this->image; + } + + /** + * Get Settings + * + * Returns the settings for an action. + * + * @return array|mixed + */ + public function get_settings() + { + return $this->settings; + } + + /** + * Sort Actions + * + * A static method for sorting two actions by timing, then priority. + * + * @param $a + * @param $b + * @return int + */ + public static function sort_actions($a, $b) + { + if (!isset(Ninja_Forms()->actions[$a->get_setting('type')])) { + return 1; + } + if (!isset(Ninja_Forms()->actions[$b->get_setting('type')])) { + return 1; + } + + $a->timing = Ninja_Forms()->actions[$a->get_setting('type')]->get_timing(); + $a->priority = Ninja_Forms()->actions[$a->get_setting('type')]->get_priority(); + + $b->timing = Ninja_Forms()->actions[$b->get_setting('type')]->get_timing(); + $b->priority = Ninja_Forms()->actions[$b->get_setting('type')]->get_priority(); + + // Compare Priority if Timing is the same + if ($a->timing == $b->timing) { + return $a->priority > $b->priority ? 1 : -1; + } + + // Compare Timing + return $a->timing < $b->timing ? 1 : -1; + } + + /** + * Loads settings array from FieldSettings config file + * @param array $onlySettings + * @return array + */ + protected function loadSettings($onlySettings = array()) + { + $settings = array(); + + // Loads a settings array from the FieldSettings configuration file. + $allSettings = \Ninja_Forms::config('ActionSettings'); + + foreach ($onlySettings as $setting) { + if (isset($allSettings[$setting])) { + $settings[$setting] = $allSettings[$setting]; + } + } + + return $settings; + } + + + /** + * Retrieve, cache, return via JSON echo list + */ + public function getLists() + { + check_ajax_referer('ninja_forms_builder_nonce', 'security'); + + $lists = $this->newsletterExtension->getLists(); + + array_unshift($lists, array('value' => 0, 'label' => '-', 'fields' => array(), 'groups' => array())); + + $this->cacheLists($lists); + + echo wp_json_encode(array('lists' => $lists)); + + wp_die(); // this is required to terminate immediately and return a proper response + } + + /** + * Construct list settings for NF Action + */ + private function getListSettings() + { + + $labelDefaults = array( + 'list' => 'List', + 'fields' => 'List Field Mapping', + 'preseleted_interests' => 'Interest Groups', + ); + + $labels = $labelDefaults; + + $prefix = $this->get_name(); + + // Set default to null to differentiate from empty + // otherwise can get caught in an infinite loop + $lists = get_transient($this->transient, null); + + if (is_null($lists)) { + $lists = $this->newsletterExtension->getLists(); + $this->cacheLists($lists); + } + + // Set an empty list to enable refresh link in action + if (empty($lists)) { + $lists = [ + [ + 'value' => '', + 'label' => 'No lists available, please check api key?' + ] + ]; + } + + $this->settings[$prefix . 'newsletter_list'] = array( + 'name' => 'newsletter_list', + 'type' => 'select', + 'label' => $labels['list'] . ' ', + 'width' => 'full', + 'group' => 'primary', + 'value' => '0', + 'options' => array(), + ); + + $fields = array(); + foreach ($lists as $list) { + $this->settings[$prefix . 'newsletter_list']['options'][] = $list; + + //Check to see if list has fields array set. + if (isset($list['fields'])) { + foreach ($list['fields'] as $field) { + $name = $list['value'] . '_' . $field['value']; + $fields[] = array( + 'name' => $name, + 'type' => 'textbox', + 'label' => $field['label'], + 'width' => 'full', + 'use_merge_tags' => array( + 'exclude' => array( + 'user', 'post', 'system', 'querystrings' + ) + ) + ); + } + } + } + + $this->settings[$prefix . 'newsletter_list_fields'] = array( + 'name' => 'newsletter_list_fields', + 'label' => __('List Field Mapping', 'ninja-forms'), + 'type' => 'fieldset', + 'group' => 'primary', + 'settings' => array() + ); + + + $this->settings[$prefix . 'newsletter_list_groups'] = array( + 'name' => 'newsletter_list_groups', + 'label' => __('Preselected Interest Groups', 'ninja-forms'), + 'type' => 'fieldset', + 'group' => 'primary', + 'settings' => array() + ); + } + + /** + * Cache lists + * @param array $lists + */ + private function cacheLists($lists) + { + if (!$lists) { + $lists = []; + } + set_transient($this->transient, $lists, $this->transientExpiration); + } +} diff --git a/lib/NfBridge/Actions/NfSettingsGlobalSettingsStorage.php b/lib/NfBridge/Actions/NfSettingsGlobalSettingsStorage.php new file mode 100644 index 0000000..5e8bc12 --- /dev/null +++ b/lib/NfBridge/Actions/NfSettingsGlobalSettingsStorage.php @@ -0,0 +1,93 @@ + + * + */ +class NfSettingsGlobalSettingsStorage implements GlobalSettingsStorageContract +{ + + /** + * + * @var GlobalSettings + */ + protected $globalSettings; + + public function __construct(GlobalSettings $globalSettings) + { + $this->setGlobalSettings($globalSettings); + } + + /** @inheritDoc */ + public function setGlobalSettings(GlobalSettings $globalSettings): GlobalSettingsStorageContract + { + $this->globalSettings = $globalSettings; + return $this; + } + + /** @inheritDoc */ + public function getGlobalSettings(): GlobalSettings + { + return $this->globalSettings; + } + + /** @inheritDoc */ + public function storeGlobalSettings(): GlobalSettingsStorageContract + { + /** @var GlobalSetting $globalSetting */ + foreach ($this->globalSettings->getGlobalSettings() as $key => $globalSetting) { + $value = $globalSetting->getValue(); + + Ninja_Forms()->update_setting($key, $value); + } + + return $this; + } + + /** @inheritDoc */ + public function retrieveGlobalSettings(): GlobalSettingsStorageContract + { + /** @var GlobalSetting $globalSetting */ + $globalSettings = $this->globalSettings->getGlobalSettings(); + + foreach ($globalSettings as $key => $globalSetting) { + $value = Ninja_Forms()->get_setting($key); + $globalSetting->setValue($value); + $this->globalSettings->addGlobalSetting($globalSetting); + } + + return $this; + } + + /** @inheritDoc */ + public function storeGlobalSetting(string $id): GlobalSettingsStorageContract + { + /** @var GlobalSetting $globalSetting */ + $globalSetting = $this->globalSettings->getGlobalSetting($id); + + $value = $globalSetting->getValue(); + + Ninja_Forms()->update_setting($id, $value); + + + return $this; + } + + /** @inheritDoc */ + public function retrieveGlobalSetting(string $id): GlobalSettingsStorageContract + { + + $globalSetting = $this->globalSettings->getGlobalSetting($id); + $value = Ninja_Forms()->get_setting($id); + $globalSetting->setValue($value); + $this->globalSettings->addGlobalSetting($globalSetting); + + return $this; + } +} diff --git a/lib/NfBridge/Actions/RegisterAction.php b/lib/NfBridge/Actions/RegisterAction.php new file mode 100644 index 0000000..2b08637 --- /dev/null +++ b/lib/NfBridge/Actions/RegisterAction.php @@ -0,0 +1,102 @@ +wpHooks = $wpHooks; + + $this->wpHooks->addFilter('ninja_forms_register_actions', [$this, 'registerActions']); + $this->wpHooks->addFilter('ninja_forms_plugin_settings', [$this, 'registerPluginSettings'], 10, 1); + $this->wpHooks->addFilter('ninja_forms_plugin_settings_groups', [$this, 'registerPluginSettingsGroups'], 10, 1); + } + + /** + * Add a NF action for registration + * @param NfActionContract $nfAction + */ + public function addNfAction(NfActionContract $nfAction) + { + $this->nfActions[$nfAction->get_name()] = $nfAction; + $this->pluginSettings = array_merge($this->pluginSettings, $nfAction->getPluginSettings()); + $this->pluginSettingsGroups = array_merge($this->pluginSettingsGroups, $nfAction->getPluginSettingsGroup()); + } + + /** + * Register actions in the Ninja Forms action registry + * @param array $actions + * @return array + */ + public function registerActions($actions) + { + $actions = array_merge($actions, $this->nfActions); + + return $actions; + } + + /** + * Merge new API settings into settings collection + * @param array $settings + * @return array + */ + public function registerPluginSettings($settings) + { + + $settings = array_merge($settings, $this->pluginSettings); + + return $settings; + } + + /** + * Merge new action's settings groups into settings groups collection + * @param array $groups + * @return array + */ + public function registerPluginSettingsGroups($groups) + { + + $mergedGroups = array_merge($groups, $this->pluginSettingsGroups); + + return $mergedGroups; + } +} diff --git a/lib/NfBridge/Actions/SingleDirectionAction.php b/lib/NfBridge/Actions/SingleDirectionAction.php new file mode 100644 index 0000000..65c74f2 --- /dev/null +++ b/lib/NfBridge/Actions/SingleDirectionAction.php @@ -0,0 +1,86 @@ +setActionProperties(); + } + + /** + * Set your own action properties here + * + * $this->_name = 'replace-me'; + * $this->_nicename = 'Replace me(translateable)'; + * $this->_tags = array(); + * $this->_timing = 'normal'; + * $this->_priority = '10'; + * @return void + */ + abstract protected function setActionProperties(): void; + + /** @inheritDoc */ + public function process($actionSettings, $formId, $data): array + { + $this->instantiateActionProcessor(); + + $actionSettingsDataHandler = (new ActionSettings())->setActionSettings($actionSettings); + $submissionDataDataHandler = (new SubmissionDataDataHandler()) + ->setSubmissionData($data) + ->setActionKey($this->getActionKey()); + + $processAction = $this->instantiateActionProcessor(); + + $processAction->process($actionSettingsDataHandler, $formId, $submissionDataDataHandler); + + $processedData = $submissionDataDataHandler->getData(); + + return $processedData; + } + + /** + * Instantiate your own Action Processor + * + * @return InterfacesProcessAction + */ + abstract protected function instantiateActionProcessor(): InterfacesProcessAction; + + /** + * Return the action key used to register action + * + * @return string + */ + public function getActionKey(): string + { + return $this->_name; + } +} diff --git a/lib/NfBridge/Contracts/ActionSettingsDataHandler.php b/lib/NfBridge/Contracts/ActionSettingsDataHandler.php new file mode 100644 index 0000000..a8781a1 --- /dev/null +++ b/lib/NfBridge/Contracts/ActionSettingsDataHandler.php @@ -0,0 +1,33 @@ +process() + * + * @var array + */ + protected $actionSettings; + + /** @inheritDoc */ + public function setActionSettings(array $actionSettings): ActionSettingsDataHandler{ + $this->actionSettings = $actionSettings; + return $this; + } + + + /** @inheritDoc */ + public function getValue(string $key, $default = ''){ + $return = $default; + if(isset($this->actionSettings[$key])){ + $return = $this->actionSettings[$key]; + } + + return $return; + } + + /** @inheritDoc */ + public function toArray(): array{ + + return $this->actionSettings; + } + + +} diff --git a/lib/NfBridge/DataHandlers/SubmissionDataDataHandler.php b/lib/NfBridge/DataHandlers/SubmissionDataDataHandler.php new file mode 100644 index 0000000..6584d45 --- /dev/null +++ b/lib/NfBridge/DataHandlers/SubmissionDataDataHandler.php @@ -0,0 +1,87 @@ +process() + * + * @var array + */ + private $data; + + /** + * Action key used for storing data + * + * @var string + */ + private $actionKey; + + /** @inheritDoc */ + public function getValue(string $key, $default = '') + { + $return = $default; + + if (isset($this->data[$key])) { + $return = $this->data[$key]; + } + + return $return; + } + + /** @inheritDoc */ + public function getFieldValueByFieldKey(string $fieldKey, $default = '') + { + $return = $default; + + if (isset($this->data['fields_by_key'][$fieldKey]['value'])) { + + $return = $this->data['fields_by_key'][$fieldKey]['value']; + } + + return $return; + } + + /** @inheritDoc */ + public function pushError(string $errorMessage): SubmissionDataDataHandler{ + + $this->data['errors'][$this->actionKey]=$errorMessage; + + return $this; + } + /** @inheritDoc */ + public function pushExtra($extra): SubmissionDataDataHandler + { + $this->data['extra'][$this->actionKey]['responseData'][]=$extra; + + return $this; + } + + /** @inheritDoc */ + public function setSubmissionData(array $data): InterfaceSubmissionDataDataHandler + { + $this->data = $data; + + return $this; + } + + /** @inheritDoc */ + public function setActionKey(string $actionKey): InterfaceSubmissionDataDataHandler + { + $this->actionKey = $actionKey; + + return $this; + } + + /** @inheritDoc */ + public function getData(): array + { + return $this->data; + } +} + diff --git a/lib/NfBridge/Entities/ActionEntity.php b/lib/NfBridge/Entities/ActionEntity.php new file mode 100644 index 0000000..d3a0fe5 --- /dev/null +++ b/lib/NfBridge/Entities/ActionEntity.php @@ -0,0 +1,241 @@ + $value) { + if ('actionSettings' === $property) { + if (is_array($value)) { + $actionSettingsEntity = ActionSettings::fromArray($value); + $obj->setActionSettings($actionSettingsEntity); + } else { + if (is_a($value, ActionSettings::class)) { + $obj->setActionSettings($value); + } + } + + continue; + } + if ('apiSettings' === $property) { + if (is_array($value)) { + $apiSettingsEntity = ApiSettings::fromArray($value); + $obj->setApiSettings($apiSettingsEntity); + } else { + if (is_a($value, ApiSettings::class)) { + $obj->setApiSettings($value); + } + } + + continue; + } + + $obj = $obj->__set($property, $value); + } + + return $obj; + } + + /** + * Return action name + * @return string + */ + public function getName(): string + { + return isset($this->name) ? (string) $this->name : ''; + } + + /** + * Return action nicename + * @return string + */ + public function getNicename(): string + { + return isset($this->nicename) ? (string) $this->nicename : ''; + } + + /** + * Return action tags + * @return string + */ + public function getTags(): array + { + return isset($this->tags) ? (array) $this->tags : array(); + } + + /** + * Return action timing + * @return string + */ + public function getTiming(): string + { + return isset($this->timing) ? (string) $this->timing : ''; + } + + /** + * Return action priority + * @return int + */ + public function getPriority(): int + { + return isset($this->priority) ? (int) $this->priority : 10; + } + + /** + * Return action settings + * @return ActionSettings + */ + public function getActionSettings(): ActionSettings + { + return isset($this->actionSettings) ? $this->actionSettings : new ActionSettings(); + } + + /** + * Return API settings + * @return ApiSettings + */ + public function getApiSettings(): ApiSettings + { + return isset($this->apiSettings) ? $this->apiSettings : new ApiSettings(); + } + + /** + * Set action name + * @param string $stringValue + * @return ActionEntity + */ + public function setName(string $stringValue): ActionEntity + { + $this->name = $stringValue; + + return $this; + } + + /** + * Set action nice name + * @param string $stringValue + * @return ActionEntity + */ + public function setNicename(string $stringValue): ActionEntity + { + $this->nicename = $stringValue; + + return $this; + } + + /** + * Set action type + * @param array $arrayValue + * @return ActionEntity + */ + public function setTags(array $arrayValue): ActionEntity + { + $this->tags = $arrayValue; + + return $this; + } + + /** + * Set action timing + * @param string $stringValue + * @return ActionEntity + */ + public function setTiming(string $stringValue): ActionEntity + { + $this->timing = $stringValue; + + return $this; + } + + /** + * Set action priority + * @param int $intValue + * @return ActionEntity + */ + public function setPriority(int $intValue): ActionEntity + { + $this->priority = $intValue; + + return $this; + } + + /** + * Set action settings + * @param array $keyedSettingsArray + * @return ActionEntity + */ + public function setActionSettings(ActionSettings $keyedSettingsArray): ActionEntity + { + $this->actionSettings = $keyedSettingsArray; + + return $this; + } + + /** + * Set API settings settings + * @param array $keyedSettingsArray + * @return ActionEntity + */ + public function setApiSettings(ApiSettings $keyedSettingsArray): ActionEntity + { + $this->apiSettings = $keyedSettingsArray; + + return $this; + } +} diff --git a/lib/NfBridge/Entities/ActionSetting.php b/lib/NfBridge/Entities/ActionSetting.php new file mode 100644 index 0000000..45d0489 --- /dev/null +++ b/lib/NfBridge/Entities/ActionSetting.php @@ -0,0 +1,426 @@ + $value) { + $obj = $obj->__set($property, $value); + } + return $obj; + } + + /** + * Return action settings name + * @return string + */ + public function getName(): string + { + return isset($this->name) ? (string) $this->name : ''; + } + + /** + * Return action settings type + * @return string + */ + public function getType(): string + { + return isset($this->type) ? (string) $this->type : ''; + } + + /** + * Return action settings label + * @return string + */ + public function getLabel(): string + { + return isset($this->label) ? (string) $this->label : ''; + } + + /** + * Return action settings width + * @return string + */ + public function getWidth(): string + { + return isset($this->width) ? (string) $this->width : ''; + } + + /** + * Return action settings group + * @return string + */ + public function getGroup(): string + { + return isset($this->group) ? (string) $this->group : ''; + } + + /** + * Return action settings value + * @return string + */ + public function getValue(): string + { + return isset($this->value) ? (string) $this->value : ''; + } + + /** + * Return action settings help + * @return string + */ + public function getHelp(): string + { + return isset($this->help) ? (string) $this->help : ''; + } + + /** + * Return action settings options + * @return Options + */ + public function getOptions(): Options + { + return isset($this->options) ? $this->options : new Options(); + } + + /** + * Return action settings mask + * @return string + */ + public function getMask(): string + { + return isset($this->mask) ? (string) $this->mask : ''; + } + + /** + * Return action settings dependencies + * @return array + */ + public function getDeps(): array + { + return isset($this->deps) ? (array) $this->deps : array(); + } + + /** + * Return action settings useMergeTags + * @return string|array + */ + public function getUseMergeTags() + { + return isset($this->useMergeTags) ? $this->useMergeTags : ''; + } + + /** + * Return action settings settings + * @return array + */ + public function getSettings(): array + { + return isset($this->settings) ? (array) $this->settings : array(); + } + + /** + * Return action settings columns + * @return array + */ + public function getColumns(): array + { + return isset($this->columns) ? (array) $this->columns : array(); + } + + /** + * Return action settings template row + * @return string + */ + public function getTmplRow(): string + { + return isset($this->templateRow) ? (string) $this->templateRow : array(); + } + + /** + * Set action settings name + * @param string $stringValue + * @return ActionSetting + */ + public function setName(string $stringValue): ActionSetting + { + $this->name = $stringValue; + + return $this; + } + + /** + * Set action settings type + * @param string $stringValue + * @return ActionSetting + */ + public function setType(string $stringValue): ActionSetting + { + $this->type = $stringValue; + + return $this; + } + + /** + * Set action settings label + * @param string $stringValue + * @return ActionSetting + */ + public function setLabel(string $stringValue): ActionSetting + { + $this->label = $stringValue; + + return $this; + } + + /** + * Set action settings width + * @param string $stringValue + * @return ActionSetting + */ + public function setWidth(string $stringValue): ActionSetting + { + $this->width = $stringValue; + + return $this; + } + + /** + * Set action settings group + * @param string $stringValue + * @return ActionSetting + */ + public function setGroup(string $stringValue): ActionSetting + { + $this->group = $stringValue; + + return $this; + } + + /** + * Set action settings value + * @param string $stringValue + * @return ActionSetting + */ + public function setValue(string $stringValue): ActionSetting + { + $this->value = $stringValue; + + return $this; + } + + /** + * Set action settings help + * @param string $stringValue + * @return ActionSetting + */ + public function setHelp(string $stringValue): ActionSetting + { + $this->help = $stringValue; + + return $this; + } + + /** + * Set action settings options + * @param Options $options + * @return ActionSetting + */ + public function setOptions(Options $options): ActionSetting + { + $this->options = $options; + + return $this; + } + + /** + * Set action settings mask + * @param string $stringValue + * @return ActionSetting + */ + public function setMask(string $stringValue): ActionSetting + { + $this->mask = $stringValue; + + return $this; + } + + /** + * Set action settings dependencies + * @param array $arrayValue + * @return ActionSetting + */ + public function setDeps(array $arrayValue): ActionSetting + { + $this->deps = $arrayValue; + + return $this; + } + + /** + * Set action settings dependencies + * @param string|array $Value + * @return ActionSetting + */ + public function setUseMergeTags(array $Value): ActionSetting + { + $this->useMergeTags = $Value; + + return $this; + } + + /** + * Set action settings settings + * @param array $arrayValue + * @return ActionSetting + */ + public function setSettings(array $arrayValue): ActionSetting + { + $this->settings = $arrayValue; + + return $this; + } + + /** + * Set action settings columns + * @param array $arrayValue + * @return ActionSetting + */ + public function setColumns(array $arrayValue): ActionSetting + { + $this->columns = $arrayValue; + + return $this; + } + + /** + * Return action setting configured for NF Action + * + * Removes unset/null values to enable default NF settings + * @return array + */ + public function outputConfiguration(): array + { + $array = []; + + $props = get_object_vars($this); + + foreach ($props as $prop => $value) { + if (is_null($value)) { + continue; + } + + if ('options'===$prop) { + $value = $value->toArray(); + } + + $array[$prop] = $value; + } + + return $array; + } +} diff --git a/lib/NfBridge/Entities/ActionSettings.php b/lib/NfBridge/Entities/ActionSettings.php new file mode 100644 index 0000000..afb54ba --- /dev/null +++ b/lib/NfBridge/Entities/ActionSettings.php @@ -0,0 +1,112 @@ +actionSettings = []; + } + + /** @inheritDoc */ + public static function fromArray(array $items): SimpleEntity + { + + $obj = new static(); + + // Entity structure else response structure + if (isset($items['actionSettings'])) { + $array = $items['actionSettings']; + } else { + $array = $items; + } + + foreach ($array as $list) { + if (!is_array($list)) { + if (is_a($list, ActionSetting::class)) { + $obj->addActionSetting($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addActionSetting(ActionSetting::fromArray($list)); + } + + return$obj; + } + + /** + * Add an Action Setting to collection + * + * @param ActionSetting $actionSetting + * + * @return ActionSettings + */ + public function addActionSetting(ActionSetting $actionSetting): ActionSettings + { + + $this->actionSettings[$actionSetting->getName()] = $actionSetting; + return $this; + } + + /** + * Get an Action Setting from collection + * + * @param string $name + * + * @return ActionSetting + * @throws Exception + */ + public function getActionSetting(string $name): ActionSetting + { + if (!isset($this->actionSettings[$name])) { + throw new Exception(); + } + return $this->actionSettings[$name]; + } + + /** + * Get all Action Settings in collection + * + * @return ActionSetting[] + */ + public function getActionSettings(): array + { + return $this->actionSettings; + } + + /** + * Return action settings configured for NF Action + * + * Removes unset/null values to enable default NF settings + * @return array + */ + public function outputConfiguration(): array + { + + $array = []; + + foreach ($this->actionSettings as $actionSetting) { + $array[$actionSetting->getName()] = $actionSetting->outputConfiguration(); + } + + return $array; + } +} diff --git a/lib/NfBridge/Entities/ApiSetting.php b/lib/NfBridge/Entities/ApiSetting.php new file mode 100644 index 0000000..ad46014 --- /dev/null +++ b/lib/NfBridge/Entities/ApiSetting.php @@ -0,0 +1,111 @@ + $value) { + $obj = $obj->__set($property, $value); + } + return $obj; + } + + /** + * Return API setting Id + * @return string + */ + public function getId(): string + { + return isset($this->id) ? (string) $this->id : ''; + } + + /** + * Return API setting label + * @return string + */ + public function getLabel(): string + { + return isset($this->label) ? (string) $this->label : ''; + } + + /** + * Return API setting data type + * @return string + */ + public function getExpectedDataType(): string + { + return isset($this->expectedDataType) ? (string) $this->expectedDataType : ''; + } + + /** + * Set API setting Id + * @param string $stringValue + * @return ApiSetting + */ + public function setId(string $stringValue): ApiSetting + { + $this->id = $stringValue; + + return $this; + } + + /** + * Set API setting label + * @param string $stringValue + * @return ApiSetting + */ + public function setLabel(string $stringValue): ApiSetting + { + $this->label = $stringValue; + + return $this; + } + + /** + * Set API setting expected data type + * @param string $stringValue + * @return ApiSetting + */ + public function setExpectedDataType(string $stringValue): ApiSetting + { + $this->expectedDataType = $stringValue; + + return $this; + } +} diff --git a/lib/NfBridge/Entities/ApiSettings.php b/lib/NfBridge/Entities/ApiSettings.php new file mode 100644 index 0000000..b4d1243 --- /dev/null +++ b/lib/NfBridge/Entities/ApiSettings.php @@ -0,0 +1,187 @@ +apiSettings = []; + } + + /** + * Return API setting Id + * @return string + */ + public function getId(): string + { + return isset($this->id) ? (string) $this->id : ''; + } + + /** + * Return API setting label + * @return string + */ + public function getLabel(): string + { + return isset($this->label) ? (string) $this->label : ''; + } + + /** + * Set API setting Id + * @param string $stringValue + * @return ApiSettings + */ + public function setId(string $stringValue): ApiSettings + { + $this->id = $stringValue; + + return $this; + } + + /** + * Set API setting label + * @param string $stringValue + * @return ApiSettings + */ + public function setLabel(string $stringValue): ApiSettings + { + $this->label = $stringValue; + + return $this; + } + + /** @inheritDoc */ + public static function fromArray(array $items): SimpleEntity + { + + $obj = new static(); + + + foreach ($items as $property => $value) { + // if string, set property value + if ('apiSettings' !== $property) { + $obj = $obj->__set($property, $value); + continue; + } + // Add entities stored in array + + foreach ((array) $value as $list) { + if (!is_array($list)) { + if (is_a($list, ApiSetting::class)) { + $obj->addApiSetting($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addApiSetting(ApiSetting::fromArray($list)); + } + } + + return $obj; + } +/** + * Convert ApiSettings object into associative array + * + * @return array + */ + public function toArray(): array + { + + $vars = get_object_vars($this); + + $array = []; + + foreach ($vars as $property => $value) { + if ('apiSettings'===$property) { + $apiSettings=[]; + + if (!is_array($value)) { + $array['apiSettings']=[]; + continue; + } + + foreach ($value as $key => $apiSetting) { + if (is_a($apiSetting, ApiSetting::class)) { + $apiSettings[$key]=$apiSetting->toArray(); + } + } + + $value = $apiSettings; + } elseif (is_object($value) && is_callable([$value, 'toArray'])) { + $value = $value->toArray(); + } + + $array[$property] = $value; + } + + return $array; + } + + /** + * Add an API Setting to collection + * + * @param ApiSetting $apiSetting + * + * @return ApiSettings + */ + public function addApiSetting(ApiSetting $apiSetting): ApiSettings + { + + $this->apiSettings[$apiSetting->getId()] = $apiSetting; + return $this; + } + + /** + * Get an API Setting from collection + * + * @param string $key + * + * @return ApiSetting + * @throws Exception + */ + public function getApiSetting(string $key): ApiSetting + { + if (!isset($this->apiSettings[$key])) { + throw new Exception(); + } + return $this->apiSettings[$key]; + } + + /** + * Get all API Settings in collection + * + * @return ApiSetting[] + */ + public function getApiSettings(): array + { + return $this->apiSettings; + } +} diff --git a/lib/NfBridge/Entities/Form.php b/lib/NfBridge/Entities/Form.php new file mode 100644 index 0000000..c47904d --- /dev/null +++ b/lib/NfBridge/Entities/Form.php @@ -0,0 +1,41 @@ +offsetGet('name')) ? $this->offsetGet('name') : ''; + } + + + public function setId(string $id) + { + $this->offsetSet('id', $id); + } + + /** + * Get the id of the form + * + * @return string + */ + public function getId() : string + { + $id = $this->offsetGet('id'); + return is_string($id) || is_numeric($id) ? (string) $id : ''; + } +} diff --git a/lib/NfBridge/Entities/Forms.php b/lib/NfBridge/Entities/Forms.php new file mode 100644 index 0000000..3b856f3 --- /dev/null +++ b/lib/NfBridge/Entities/Forms.php @@ -0,0 +1,74 @@ +forms[$form->getId()] = $form; + return $this; + } + + /** + * Get a form from this collection + * + * @param string $formId + * @return Form + * @throws Exception + */ + public function getForm(string $formId): FormContract + { + if (!$this->hasForm($formId)) { + throw new Exception("No form with ID $formId found"); + } + return $this->forms[$formId]; + } + + /** + * Does collection have a form of this ID? + * + * @param string $formId + * @return bool + */ + public function hasForm(string $formId): bool + { + return array_key_exists($formId, $this->forms); + } + + /** + * Remove a form from the collection + * + * @param string $formId + * @return FormCollection + * @throws Exception + */ + public function removeForm(string $formId): FormCollection + { + if (!$this->hasForm($formId)) { + throw new Exception("No form with ID $formId found"); + } + unset($this->forms[$formId]); + return $this; + } +} diff --git a/lib/NfBridge/Entities/Modal.php b/lib/NfBridge/Entities/Modal.php new file mode 100644 index 0000000..0dad990 --- /dev/null +++ b/lib/NfBridge/Entities/Modal.php @@ -0,0 +1,101 @@ +modalContent = $content; + + return $this; + } + + /** + * Append modal content + * @param string $content + * @return \NFMailchimp\NinjaForms\Mailchimp\Entities\Modal + */ + public function appendModalContent(string $content): Modal + { + $this->modalContent .= $content; + + return $this; + } + + /** @inheritdoc */ + public function toArray(): array + { + $vars = get_object_vars($this); + $array = []; + foreach ($vars as $property => $value) { + if (is_object($value) && is_callable([$value, 'toArray'])) { + $value = $value->toArray(); + } + $array[$property] = $value; + } + $array['template-desc']=$array['templateDesc']; + $array['modal-title']=$array['modalTitle']; + $array['modal-content']=$array['modalContent']; + + return $array; + } + + /** + * Get modal Id + * @return string + */ + public function getId(): string + { + + return $this->id; + } +} diff --git a/lib/NfBridge/Entities/NFBridgeEntity.php b/lib/NfBridge/Entities/NFBridgeEntity.php new file mode 100644 index 0000000..1893ada --- /dev/null +++ b/lib/NfBridge/Entities/NFBridgeEntity.php @@ -0,0 +1,13 @@ +label) ? (string) $this->label : ''; + } + + /** + * Return option value + * @return string + */ + public function getValue(): string + { + return isset($this->value) ? (string) $this->value : ''; + } + + /** + * Set option label + * @param string $stringValue + * @return Option + */ + public function setLabel(string $stringValue): Option + { + $this->label = $stringValue; + + return $this; + } + + /** + * Set option label + * @param string $stringValue + * @return Option + */ + public function setValue(string $stringValue): Option + { + $this->value = $stringValue; + + return $this; + } +} diff --git a/lib/NfBridge/Entities/Options.php b/lib/NfBridge/Entities/Options.php new file mode 100644 index 0000000..cbcb4d0 --- /dev/null +++ b/lib/NfBridge/Entities/Options.php @@ -0,0 +1,66 @@ +options[] = $option; + + return $this; + } + + /** + * Return option collection as array + * @return array + */ + public function toArray(): array + { + + $toArray = []; + + foreach ($this->options as $option) { + $toArray[] = $option->toArray(); + } + + return $toArray; + } + + /** + * Convert array into Options + * @param array $items + * @return SimpleEntity + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $option) { + if (is_a($option, Option::class)) { + $obj->addOption($option); + } elseif (is_array($option)) { + $obj->addOption(Option::fromArray($option)); + } + } + return $obj; + } +} diff --git a/lib/NfBridge/Entities/SubmissionData.php b/lib/NfBridge/Entities/SubmissionData.php new file mode 100644 index 0000000..a66db6d --- /dev/null +++ b/lib/NfBridge/Entities/SubmissionData.php @@ -0,0 +1,50 @@ +fields; + + $keys = array_keys($settings->getActionSettings()); + + return $keys; + } + + /** + * Return submission values matching field collection keys + * @return array + */ + public function getKeyedSubmissionData(): array + { + + $keyedSubmissionData = []; + + $arrayKeys = $this->getSubmissionKeys(); + + foreach ($arrayKeys as $key) { + if ($this->hasValue($key)) { + $keyedSubmissionData[$key] = $this->getValue($key); + } + } + + return $keyedSubmissionData; + } + + // phpcs:enable +} diff --git a/lib/NfBridge/Exception.php b/lib/NfBridge/Exception.php new file mode 100644 index 0000000..336138f --- /dev/null +++ b/lib/NfBridge/Exception.php @@ -0,0 +1,9 @@ + (string) $form->get_id(), + 'name'=> $form->get_model($form->get_id(), 'form')->get_setting('title')]); + } +} diff --git a/lib/NfBridge/Factories/FormProcessorsFactory.php b/lib/NfBridge/Factories/FormProcessorsFactory.php new file mode 100644 index 0000000..436054c --- /dev/null +++ b/lib/NfBridge/Factories/FormProcessorsFactory.php @@ -0,0 +1,91 @@ +wpHooks = $wpHooks; + } + + /** + * @inheritdoc + */ + public function getWpHooks(): WpHooksContract + { + return $this->wpHooks; + } + + /** @inheritDoc */ + public function getSubmissionData( + array $formActionSubmissionArray, + FormActionFieldCollection $actionSettings, + ApiSettings $apiSettings + ): SubmissionDataContract { + + $getApiSettingsValues = $this->getGetApiSettingsValues($apiSettings); + $keyValuePairs = $getApiSettingsValues->getApiSettingsValues(); + $combinedKeyValuePairs = array_merge($formActionSubmissionArray, $keyValuePairs); + $submissionData = new SubmissionData($combinedKeyValuePairs, $actionSettings); + + return $submissionData; + } + + /** @inheritDoc */ + public function getConfigureApiSettings(ApiSettings $apiSettings): ConfigureApiSettings + { + + return new ConfigureApiSettings($apiSettings); + } + + /** @inheritdoc */ + public function getForm(NF_Abstracts_ModelFactory $nfFormModelFactory): FormContract + { + $settings = $nfFormModelFactory->get_settings(); + + $array=[ + 'name'=>$settings['title'], + 'id'=>$nfFormModelFactory->get_id() + ]; + + return new Form($array); + } + + + /** @inheritdoc */ + public function getGetApiSettingsValues(ApiSettings $apiSettings): GetApiSettingsValues + { + + return new GetApiSettingsValues($apiSettings); + } +} diff --git a/lib/NfBridge/Factories/NfActionFactory.php b/lib/NfBridge/Factories/NfActionFactory.php new file mode 100644 index 0000000..1a956e0 --- /dev/null +++ b/lib/NfBridge/Factories/NfActionFactory.php @@ -0,0 +1,47 @@ +wpHooks = $wpHooks; + } + + /** + * @inheritDoc + */ + public function getIdentifier(): string + { + return self::IDENTIFIER; + } + + /** @inheritDoc */ + public function getContainer(): ServiceContainerContract + { + return $this; + } + + /** + * Register the module's services + * + * @return Module + */ + public function registerServices(): Module + { + // Bind FormFactory service to container + $this->bind(FormFactoryContract::class, function () { + return new FormFactory(); + }); + + // Bind NFActionFactory to the container + $this->bind(NfActionFactoryContract::class, function () { + return new NfActionFactory(); + }); + + // Bind SubmissionDataFactory to the container + $this->bind(SubmissionDataFactoryContract::class, function () { + + return new SubmissionDataFactory(); + }); + + // Bind FormProcessorsFactory to the container + $this->bind(FormProcessorsFactoryContract::class, function () { + if (is_null($this->wpHooks)) { + $this->wpHooks= new WpHooksApi(); + } + return new FormProcessorsFactory($this->wpHooks); + }); + + // Bind RegisterAction to the container + $this->bind(RegisterAction::class, function () { + if (is_null($this->wpHooks)) { + $this->wpHooks= new WpHooksApi(); + } + return new RegisterAction($this->wpHooks); + }); + + // Bind CreateAddNewModal to the container + $this->bind('CreateAddNewModal', function () { + + return new CreateAddNewModal(); + }); + return $this; + } +} diff --git a/lib/RestApi/Contracts/AuthorizeRequestContract.php b/lib/RestApi/Contracts/AuthorizeRequestContract.php new file mode 100644 index 0000000..e3cd169 --- /dev/null +++ b/lib/RestApi/Contracts/AuthorizeRequestContract.php @@ -0,0 +1,24 @@ +uri; + } + + /** + * @inheritDoc + */ + public function setUri(string $uri): EndpointContract + { + $this->uri = $uri; + return $this; + } + + /** + * @inheritDoc + */ + public function getArgs(): array + { + return $this->args; + } + + /** + * @inheritDoc + */ + public function setArgs(array $args): EndpointContract + { + $this->args = $args; + return $this; + } + + + /** + * @inheritDoc + */ + public function getToken(RequestContract $request): string + { + $header = $request->getHeader('Authorization'); + if ($header && 0 === strpos($header, 'Bearer')) { + return trim(substr($header, 7)); + } + return $header ? $header : ''; + } +} diff --git a/lib/RestApi/Request.php b/lib/RestApi/Request.php new file mode 100644 index 0000000..25cb043 --- /dev/null +++ b/lib/RestApi/Request.php @@ -0,0 +1,41 @@ + [], 'params' => [] ]) + { + $obj = new static(); + if (! empty($items['headers'])) { + foreach ($items['headers'] as $header => $value) { + $obj->setHeader($header, $value); + } + } + + if (! empty($items['params'])) { + $obj->setParams($items['params']); + } + return $obj; + } +} diff --git a/lib/RestApi/Response.php b/lib/RestApi/Response.php new file mode 100644 index 0000000..f43d79e --- /dev/null +++ b/lib/RestApi/Response.php @@ -0,0 +1,89 @@ +setStatus($items['status']); + } + + if (isset($items['method'])) { + $obj->setHttpMethod($items['method']); + } + + if (isset($items['headers'])) { + if (is_array($items['headers'])) { + $obj->setHeaders($items['headers']); + } + } + + if (isset($items['data'])) { + if (is_array($items['data'])) { + $obj->setData($items['data']); + } + } + + return $obj; + } + + /** + * @inheritDoc + */ + public function getData(): array + { + return $this->data; + } + + /** + * @inheritDoc + */ + public function setData(array $data): HttpResponseContract + { + $this->data = $data; + return $this; + } + + + /** + * @inheritDoc + */ + public function getStatus(): int + { + return $this->status; + } + + /** + * @inheritDoc + */ + public function setStatus(int $code): HttpResponseContract + { + $this->status = $code; + return $this; + } +} diff --git a/lib/RestApi/Traits/ProvidesHttpHeaders.php b/lib/RestApi/Traits/ProvidesHttpHeaders.php new file mode 100644 index 0000000..f486763 --- /dev/null +++ b/lib/RestApi/Traits/ProvidesHttpHeaders.php @@ -0,0 +1,75 @@ +hasHeader($headerName) ? $this->headers[ $headerName ] : null; + } + + /** + * @param string $headerName + * + * @return bool + */ + public function hasHeader(string $headerName): bool + { + + if (array_key_exists($headerName, $this->getHeaders())) { + return true; + } + return false; + } + + + /** + * Set header in request + * + * @param string $headerName + * @param mixed $headerValue + * + * @return HttpContract + */ + public function setHeader(string $headerName, $headerValue): HttpContract + { + $this->headers[ $headerName ] = $headerValue; + return $this; + } + + /** @inheritdoc */ + public function getHeaders(): array + { + return is_array($this->headers) ? $this->headers : []; + } + + /** + * Bulk assign headers + * + * @param array $headers + * @return HttpContract + */ + public function setHeaders(array $headers): HttpContract + { + foreach ($headers as $header => $headerValue) { + $this->setHeader($header, $headerValue); + } + return $this; + } +} diff --git a/lib/RestApi/Traits/ProvidesHttpMethod.php b/lib/RestApi/Traits/ProvidesHttpMethod.php new file mode 100644 index 0000000..cb52184 --- /dev/null +++ b/lib/RestApi/Traits/ProvidesHttpMethod.php @@ -0,0 +1,37 @@ +httpMethod) ? $this->httpMethod : 'GET'; + } + + /** + * Set the HTTP method for the request or response + * + * @param string $method + * + * @return HttpContract + */ + public function setHttpMethod(string $method) : HttpContract + { + $this->httpMethod = $method; + return $this; + } +} diff --git a/lib/RestApi/Traits/ProvidesRestParams.php b/lib/RestApi/Traits/ProvidesRestParams.php new file mode 100644 index 0000000..28e9da3 --- /dev/null +++ b/lib/RestApi/Traits/ProvidesRestParams.php @@ -0,0 +1,74 @@ +hasParam($paramName) ? $this->params[ $paramName ] : null; + } + + /** + * Set parameter in request + * + * @param string $paramName + * @param mixed $paramValue + * + * @return $this + */ + public function setParam(string $paramName, $paramValue): HttpRequestContract + { + $this->params[ $paramName ] = $paramValue; + return $this; + } + + /** + * Does request have param? + * + * @param string $paramName + * + * @return bool + */ + public function hasParam(string $paramName): bool + { + return array_key_exists($paramName, $this->getParams()); + } + + /** + * Get all params of request + * + * @return array + */ + public function getParams(): array + { + return is_array($this->params) ? $this->params : []; + } + + /** + * Set parameters of request + * + * @param array $params + * + * @return HttpRequestContract + */ + public function setParams(array $params): HttpRequestContract + { + $this->params = $params; + return $this; + } +} diff --git a/lib/Shared/Actions/OpenAuthImplementation.php b/lib/Shared/Actions/OpenAuthImplementation.php new file mode 100644 index 0000000..27a4097 --- /dev/null +++ b/lib/Shared/Actions/OpenAuthImplementation.php @@ -0,0 +1,235 @@ +remoteRequest = $remoteRequest; + } + + /** + * Set OpenAuth credentials with which to generate authorization + * + * @param OpenAuthCredentials $openAuthCredentials + * @return \NFMailchimp\EmailCRM\AmoCrm\Abstracts\OpenAuthenticatorContract + */ + public function setCredentials(OpenAuthCredentials $openAuthCredentials): OpenAuthImplementationContract + { + $this->openAuthCredentials = $openAuthCredentials; + return $this; + } + + /** + * Return OpenAuthCredentials + * + * The authentication process generates new refresh_ and access_ tokens. + * + * These values are updated in the originally supplied credentials. The + * requesting class can retrieve the updated credentials, store the + * refresh token, and use the access token for immediate authorization. + * + * @return OpenAuthCredentials + */ + public function getCredentials(): OpenAuthCredentials + { + return $this->openAuthCredentials; + } + + /** + * Set URL for making grant_type = authorization_code request + * + * @param string $grantTypeAuthCodeUrl + * @return OpenAuthenticatorContract + */ + public function setGrantTypeAuthCodeUrl(string $grantTypeAuthCodeUrl): OpenAuthImplementationContract + { + $this->grantTypeAuthCodeUrl = $grantTypeAuthCodeUrl; + return $this; + } + + /** + * Set URL for making grant_type = refresh_token request + * + * @param string $grantTypeRefreshTokenUrl + * @return OpenAuthenticatorContract + */ + public function setGrantTypeRefreshTokenUrl(string $grantTypeRefreshTokenUrl): OpenAuthImplementationContract + { + $this->grantTypeRefreshTokenUrl = $grantTypeRefreshTokenUrl; + return $this; + } + + /** + * Makes a grant_type = Authorization request per OAuth standards + * @return HandledResponse + */ + public function authorizeFromAuthorizationCode(): HandledResponse + { + $this->setRequestSettings(); + $this->remoteRequest->setUrl($this->grantTypeAuthCodeUrl); + $body = $this->constructGrantTypeAuthCodeBody(); + + $this->remoteRequest->setBody(json_encode($body)); + + $incomingResponseData = $this->remoteRequest->handle(); + + $handledResponse = $this->evaluateResponseData($incomingResponseData); + + return $handledResponse; + } + + /** + * Makes a grant_type = refresh_token request per OAuth standards + * @return HandledResponse + */ + public function authorizeFromRefreshToken(): HandledResponse + { + $this->setRequestSettings(); + + $this->remoteRequest->setUrl($this->grantTypeRefreshTokenUrl); + + $body = $this->constructGrantTypeRefreshTokenBody(); + + + $this->remoteRequest->setBody(json_encode($body)); + + $incomingResponseData = $this->remoteRequest->handle(); + + + $handledResponse = $this->evaluateResponseData($incomingResponseData); + + return $handledResponse; + } + + /** + * Evaluates the response from endpoint to put data in known locations + * + * **Note** that the credentials are, per OAuth specification, modified + * in the making of a authorization request. + * * An authorization token can only be used once + * * A refresh token is only used once but, when making an authorization + * request, a new token is returned along with the access_token that is + * intended for immediate authorization. + * + * @param HandledResponse $handledResponse + * @return HandledResponse + */ + protected function evaluateResponseData(HandledResponse $handledResponse): HandledResponse + { + + if ($handledResponse->isSuccessful()) { + $body = json_decode($handledResponse->getResponseBody(), true); + + if (isset($body['access_token']) && isset($body['refresh_token'])) { + $this->openAuthCredentials->setAccessToken($body['access_token']); + $this->openAuthCredentials->setRefreshToken($body['refresh_token']); + + $handledResponse->setResponseBody(json_encode([ + "accessToken" => $this->openAuthCredentials->getAccessToken(), + "refreshToken" => $this->openAuthCredentials->getRefreshToken() + ])); + } + } + return $handledResponse; + } + + /** + * Construct request body per OAuth specifications + * @return array + */ + protected function constructGrantTypeAuthCodeBody(): array + { + + $body = [ + 'client_id' => $this->openAuthCredentials->getClientId(), + 'client_secret' => $this->openAuthCredentials->getClientSecret(), + 'grant_type' => 'authorization_code', + 'code' => $this->openAuthCredentials->getAuthorizationCode(), + 'redirect_uri' => $this->openAuthCredentials->getRedirectUri() + ]; + + return $body; + } + + /** + * Construct request body per OAuth specifications + * @return array + */ + protected function constructGrantTypeRefreshTokenBody(): array + { + $body = [ + 'client_id' => $this->openAuthCredentials->getClientId(), + 'client_secret' => $this->openAuthCredentials->getClientSecret(), + 'grant_type' => 'refresh_token', + 'refresh_token' => $this->openAuthCredentials->getRefreshToken(), + 'redirect_uri' => $this->openAuthCredentials->getRedirectUri() + ]; + + return $body; + } + + /** + * Set HTTP settings required for making HTTP request + */ + protected function setRequestSettings() + { + + $this->remoteRequest->setHeaderParameter('Content-Type', 'application/json'); + $this->remoteRequest->setHttpArg('method', 'POST'); + } +} diff --git a/lib/Shared/ArrayLike.php b/lib/Shared/ArrayLike.php new file mode 100644 index 0000000..f8f9da8 --- /dev/null +++ b/lib/Shared/ArrayLike.php @@ -0,0 +1,70 @@ +items = $items; + } + + /** @inheritDoc */ + public function toArray(): array + { + return $this->items; + } + + + /** @inheritDoc */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->items[] = $value; + } else { + $this->items[$offset] = $value; + } + } + /** @inheritDoc */ + public function offsetExists($offset) + { + return isset($this->items[$offset]); + } + /** @inheritDoc */ + public function offsetUnset($offset) + { + unset($this->items[$offset]); + } + + /** @inheritDoc */ + public function offsetGet($offset) + { + return isset($this->items[$offset]) ? $this->items[$offset] : null; + } + + /** @inheritDoc */ + public function jsonSerialize() + { + return $this->toArray(); + } +} diff --git a/lib/Shared/CommData.php b/lib/Shared/CommData.php new file mode 100644 index 0000000..8086d9d --- /dev/null +++ b/lib/Shared/CommData.php @@ -0,0 +1,87 @@ +arrayStore = $arrayStore; + } + + /** + * Retrieves existing CommData from db + * + * If incoming value is not an array, sets CommData as empty array + */ + public function initializeCommData() + { + + $db_comm_data = $this->arrayStore->getData(); + + if (!is_array($db_comm_data)) { + $this->comm_data = array(); + } else { + $this->comm_data = $db_comm_data; + } + } + + + /** + * Removes existing data in key and initializes empty array + * @param string $key + */ + public function resetKey($key) + { + + unset($this->comm_data[$key]); + } + + /** + * Appends an entry to the indexed array in a given key + * @param string $key Comm Data key storing the data + * @param mixed $entry Value to be appended as array element + */ + public function append($key, $entry) + { + + $this->comm_data[$key][]=$entry; + } + + /** + * Replaces existing value with a new value + * @param string $key + * @param mixed $entry New value to be stored in key + */ + public function set($key, $entry) + { + + $this->comm_data[$key]=$entry; + } + + + + /** + * Stores CommData array in WP options table under given key + */ + public function storeCommData() + { + + $this->arrayStore->saveData($this->comm_data); + } +} diff --git a/lib/Shared/Containers/ServiceContainer.php b/lib/Shared/Containers/ServiceContainer.php new file mode 100644 index 0000000..6b62125 --- /dev/null +++ b/lib/Shared/Containers/ServiceContainer.php @@ -0,0 +1,127 @@ +services)) { + $this->services = []; + } + + return ! empty($this->services) && array_key_exists($serviceName, $this->services); + } + + /** @inheritdoc */ + public function bind($alias, $concrete) + { + $this->services[$alias] = $concrete; + } + + /** @inheritdoc */ + public function make($alias) + { + if ($this->isUnBoundSingleton($alias)) { + $binding = $this->unBoundSingletons[$alias]; + $this->singleton($alias, $binding()); + } + + if (! isset($this->services[$alias])) { + return $this->resolve($alias); + } + + if (is_callable($this->services[$alias])) { + return call_user_func_array($this->services[$alias], array($this)); + } + + if (is_object($this->services[$alias])) { + return $this->services[$alias]; + } + + if (class_exists($this->services[$alias])) { + return $this->resolve($this->services[$alias]); + } + + return $this->resolve($alias); + } + + private function isUnBoundSingleton($alias) + { + + return ! empty($this->unBoundSingletons) && array_key_exists($alias, $this->unBoundSingletons); + } + + /** @inheritdoc */ + public function singleton($alias, $binding) + { + if (is_callable($binding)) { + $this->unBoundSingletons[ $alias ] = $binding; + } else { + if ($this->isUnBoundSingleton($alias)) { + unset($this->unBoundSingletons[$alias]); + } + $this->services[$alias] = $binding; + } + } + + + /** + * Resolve dependencies. + * + * @todo use Doctrine Insanitator? + * + * @param $class + * @return object + */ + private function resolve($class) + { + $reflection = new \ReflectionClass($class); + + $constructor = $reflection->getConstructor(); + + // Constructor is null + if (! $constructor) { + return new $class; + } + + // Constructor with no parameters + $params = $constructor->getParameters(); + + if (count($params) === 0) { + return new $class; + } + + $newInstanceParams = array(); + + foreach ($params as $param) { + if (is_null($param->getClass())) { + $newInstanceParams[] = null; + continue; + } + + $newInstanceParams[] = $this->make( + $param->getClass()->getName() + ); + } + + return $reflection->newInstanceArgs( + $newInstanceParams + ); + } +} diff --git a/lib/Shared/Containers/ServiceFactoryContainer.php b/lib/Shared/Containers/ServiceFactoryContainer.php new file mode 100644 index 0000000..44e3800 --- /dev/null +++ b/lib/Shared/Containers/ServiceFactoryContainer.php @@ -0,0 +1,55 @@ +factories[$service] = $serviceFactory; + return $this; + } + + /** @inheritDoc */ + public function useFactory(string $service, $args = []) + { + if (! $this->hasFactory($service)) { + throw new \Exception("Service {$service} not found", 500); + } + + return call_user_func( + [ + $this->factories[$service], + 'handle' + ], + $args, + $this + ); + } + + /** @inheritDoc */ + public function hasFactory(string $service): bool + { + return is_array($this->factories) && array_key_exists($service, $this->factories); + } +} diff --git a/lib/Shared/Contracts/ApiModuleContract.php b/lib/Shared/Contracts/ApiModuleContract.php new file mode 100644 index 0000000..77fa5cb --- /dev/null +++ b/lib/Shared/Contracts/ApiModuleContract.php @@ -0,0 +1,34 @@ +formFields = new FormFields(); + } + + /** + * Set form title + * @param string $title + * @return FormBuilder + */ + public function setTitle(string $title): FormBuilderContract + { + $this->title = $title; + return $this; + } + + /** + * Add form field to the form builder + * @param FormField $formField + * @return FormBuilder + */ + public function addFormField(FormField $formField): FormBuilderContract + { + $this->formFields->addFormField($formField); + return $this; + } + + /** + * Get form builder title + * @return string + */ + public function getTitle(): string + { + + return isset($this->title) ? $this->title : ''; + } + + /** + * Get form fields + * @return FormFields + */ + public function getFormFields(): FormFields + { + return $this->formFields; + } + + /** + * Return FormBuilder entity as associative array + * @return array + */ + public function toArray(): array + { + /** @var FormField $field */ + $array = []; + + $array['title'] = $this->getTitle(); + + $collection = $this->getFormFields()->getFields(); + + foreach ($collection as $field) { + $array['formFields'][$field->getId()] = $field->toArray(); + } + + return $array; + } +} diff --git a/lib/Shared/Entities/FormField.php b/lib/Shared/Entities/FormField.php new file mode 100644 index 0000000..3c1b503 --- /dev/null +++ b/lib/Shared/Entities/FormField.php @@ -0,0 +1,265 @@ + element + * + * Required argument -- can be empty string for hidden fields. + * + * @var string + */ + protected $label; + + /** + * What type of field. + * + * Optional argument. + * Default is simple which is an + * CF Options: simple|checkbox|advanced|dropdown + * + * @var string + */ + protected $type; + + /** + * Default value for the field + * + * Optional argument + * Default value is null + * + * @var mixed + */ + protected $default; + + /** + * Makes field required or not. + * + * Optional argument + * Default is not required. + * + * @var bool + */ + protected $required; + + /** + * The description of the field. + * + * If used the field HTML __should__ have an `aria-describedby` attribute referring to the element displaying this description. + * + * Optional argument + * + * @var string + */ + protected $description; + + /** + * + * @var Options + */ + protected $options; + + /** + * Character limit + * @var int + */ + protected $characterLimit; + + /** + * Set the field Id + * @param string $id Field Id + * @return SimpleEntity + */ + public function setId(string $id): SimpleEntity + { + $this->id = $id; + return $this; + } + + /** + * Set the field label + * @param string $label Field label + * @return SimpleEntity + */ + public function setLabel(string $label): SimpleEntity + { + + $this->label = $label; + return $this; + } + + /** + * Set the field type + * @param string $type Field type + * @return SimpleEntity + */ + public function setType(string $type): SimpleEntity + { + $this->type = $type; + return $this; + } + + /** + * Set the default value + * @param type $default Default value + * @return SimpleEntity + */ + public function setDefault($default): SimpleEntity + { + $this->default = $default; + return $this; + } + + /** + * Set Required parameter + * @param bool $required Boolean of `is required?` + * @return SimpleEntity + */ + public function setRequired(?bool $required): SimpleEntity + { + $this->required = $required; + return $this; + } + + /** + * Set the field description + * @param string $description Field description + * @return SimpleEntity + */ + public function setDescription(?string $description): SimpleEntity + { + $this->description = $description; + return $this; + } + + /** + * Set the character limit for the field + * @param int $limit + * @return SimpleEntity + */ + public function setCharacterLimit(?int $limit): SimpleEntity + { + $this->characterLimit = $limit; + return $this; + } + + /** + * Set field options + * @param Options $options + * @return SimpleEntity + */ + public function setOptions(?Options $options): SimpleEntity + { + $this->options = $options; + return $this; + } + + /** + * Get field id + * @return string + */ + public function getId():string + { + return isset($this->id) ? $this->id : ''; + } + + /** + * Get field label + * @return string + */ + public function getLabel():string + { + return isset($this->label) ? $this->label : ''; + } + + /** + * Get field type + * @return string + */ + public function getType():string + { + return isset($this->type) ? $this->type : ''; + } + + /** + * Get field default value + * @return mixed + */ + public function getDefault():string + { + return isset($this->default) ? $this->default : ''; + } + + /** + * Get field required boolean + * @return bool + */ + public function getRequired():bool + { + return isset($this->required) ? $this->required : false; + } + + /** + * Get field description + * @return string + */ + public function getDescription():string + { + return isset($this->description) ? $this->description : ''; + } + + /** + * Get options + * @return Options + */ + public function getOptions(): Options + { + return isset($this->options) ? $this->options : new Options(); + } + + /** + * Get character limit for the field; 0 indicates no limit + * + * @return int + */ + public function getCharacterLimit():int + { + return isset($this->characterLimit)? $this->characterLimit:0; + } + /** @inheritdoc */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + if ('options'===$property && is_array($value)) { + $options = Options::fromArray($value); + + $obj->setOptions($options); + continue; + } + + $obj = $obj->__set($property, $value); + } + return $obj; + } +} diff --git a/lib/Shared/Entities/FormFields.php b/lib/Shared/Entities/FormFields.php new file mode 100644 index 0000000..9d7bb42 --- /dev/null +++ b/lib/Shared/Entities/FormFields.php @@ -0,0 +1,104 @@ +formFields[$field->getId()] = $field; + return $this; + } + + /** + * Get form field specified by Id + * @param string $id Id of field + * @return FormField + * @throws Exception + */ + public function getField(string $id): FormField + { + + if (!isset($this->formFields[$id])) { + throw new \Exception(); + } + + return $this->formFields[$id]; + } + + /** + * Return collection of all form fields + * @return array + */ + public function getFields(): array + { + return $this->formFields; + } + + /** + * Return array of all form fields + * @return array + */ + public function toArray(): array + { + + $array = []; + foreach ($this->formFields as $property => $field) { + $array[$property] = $field->toArray(); + } + return $array; + } + + /** + * Return simple entity constructed from array of FormFields + * @param array $items + * @return SimpleEntity + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + + // Entity structure else response structure + if (isset($items['formFields'])) { + $array = $items['formFields']; + } else { + $array = $items; + } + foreach ($array as $item) { + if (!is_array($item)) { + if (is_a($item, FormField::class)) { + $obj->addFormField($item); + continue; + } else { + $item = (array) $item; + } + } + + $entity = FormField::fromArray($item); + + $obj->addFormField($entity); + } + + return $obj; + } +} diff --git a/lib/Shared/Entities/GlobalSetting.php b/lib/Shared/Entities/GlobalSetting.php new file mode 100644 index 0000000..81f79a3 --- /dev/null +++ b/lib/Shared/Entities/GlobalSetting.php @@ -0,0 +1,151 @@ + $value) { + $obj = $obj->__set($property, $value); + } + return $obj; + } + + /** + * Return Global setting Id + * @return string + */ + public function getId(): string + { + return isset($this->id) ? (string) $this->id : ''; + } + + /** + * Return Global setting label + * @return string + */ + public function getLabel(): string + { + return isset($this->label) ? (string) $this->label : ''; + } + + /** + * Return Global setting data type + * @return string + */ + public function getExpectedDataType(): string + { + return isset($this->expectedDataType) ? (string) $this->expectedDataType : ''; + } + + /** + * Get the value for the GlobalSetting + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * Set Global setting Id + * @param string $stringValue + * @return GlobalSetting + */ + public function setId(string $stringValue): GlobalSetting + { + $this->id = $stringValue; + + return $this; + } + + /** + * Set Global setting label + * @param string $stringValue + * @return GlobalSetting + */ + public function setLabel(string $stringValue): GlobalSetting + { + $this->label = $stringValue; + + return $this; + } + + /** + * Set Global setting expected data type + * + * @param string $stringValue + * @return GlobalSetting + */ + public function setExpectedDataType(string $stringValue): GlobalSetting + { + $this->expectedDataType = $stringValue; + + return $this; + } + + /** + * Set the value for the GlobalSetting + * + * @param type $param + * @return \NFMailchimp\EmailCRM\Shared\Entities\GlobalSetting + */ + public function setValue($param):GlobalSetting + { + $this->value = $param; + + return $this; + } +} diff --git a/lib/Shared/Entities/GlobalSettings.php b/lib/Shared/Entities/GlobalSettings.php new file mode 100644 index 0000000..106858e --- /dev/null +++ b/lib/Shared/Entities/GlobalSettings.php @@ -0,0 +1,189 @@ +globalSettings = []; + } + + /** + * Return Global setting Id + * @return string + */ + public function getId(): string + { + return isset($this->id) ? (string) $this->id : ''; + } + + /** + * Return Global setting label + * @return string + */ + public function getLabel(): string + { + return isset($this->label) ? (string) $this->label : ''; + } + + /** + * Set Global setting Id + * @param string $stringValue + * @return GlobalSettings + */ + public function setId(string $stringValue): GlobalSettings + { + $this->id = $stringValue; + + return $this; + } + + /** + * Set Global setting label + * @param string $stringValue + * @return GlobalSettings + */ + public function setLabel(string $stringValue): GlobalSettings + { + $this->label = $stringValue; + + return $this; + } + + /** @inheritDoc */ + public static function fromArray(array $items): SimpleEntity + { + + $obj = new static(); + + + foreach ($items as $property => $value) { + // if string, set property value + if ('globalSettings' !== $property) { + $obj = $obj->__set($property, $value); + continue; + } + // Add entities stored in array + + foreach ((array) $value as $list) { + if (!is_array($list)) { + if (is_a($list, GlobalSetting::class)) { + $obj->addGlobalSetting($list); + continue; + } else { + $list = (array) $list; + } + } + + $obj->addGlobalSetting(GlobalSetting::fromArray($list)); + } + } + + return $obj; + } + + /** + * Convert GlobalSetting object into associative array + * + * @return array + */ + public function toArray(): array + { + + $vars = get_object_vars($this); + + $array = []; + + foreach ($vars as $property => $value) { + if ('globalSettings'===$property) { + $globalSettings=[]; + + if (!is_array($value)) { + $array['globalSettings']=[]; + continue; + } + + foreach ($value as $key => $globalSetting) { + if (is_a($globalSetting, GlobalSetting::class)) { + $globalSettings[$key]=$globalSetting->toArray(); + } + } + + $value = $globalSettings; + } elseif (is_object($value) && is_callable([$value, 'toArray'])) { + $value = $value->toArray(); + } + + $array[$property] = $value; + } + + return $array; + } + + /** + * Add an Global Setting to collection + * + * @param GlobalSetting $globalSetting + * + * @return GlobalSettings + */ + public function addGlobalSetting(GlobalSetting $globalSetting): GlobalSettings + { + + $this->globalSettings[$globalSetting->getId()] = $globalSetting; + return $this; + } + + /** + * Get a Global Setting from collection + * + * @param string $key + * + * @return GlobalSetting + * @throws Exception + */ + public function getGlobalSetting(string $key): GlobalSetting + { + if (!isset($this->globalSettings[$key])) { + throw new Exception(); + } + return $this->globalSettings[$key]; + } + + /** + * Get all Global Settings in collection + * + * @return GlobalSetting[] + */ + public function getGlobalSettings(): array + { + return $this->globalSettings; + } +} diff --git a/lib/Shared/Entities/HandledResponse.php b/lib/Shared/Entities/HandledResponse.php new file mode 100644 index 0000000..3886757 --- /dev/null +++ b/lib/Shared/Entities/HandledResponse.php @@ -0,0 +1,388 @@ +context = $string; + return $this; + } + + /** + * Get the context + * + * @return string + */ + public function getContext(): string + { + return (isset($this->context)&& !is_null($this->context))?$this->context:''; + } + + /** + * Set the record count + * @param int $int + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setRecordCount(?int $int): HandledResponse + { + $this->recordCount = $int; + return $this; + } + + /** + * Get the record count + * @return int + */ + public function getRecordCount(): int + { + return (isset($this->recordCount)&& !is_null($this->recordCount))?$this->recordCount:0; + } + + /** + * Set the records collection + * + * @param array $array + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setRecords(?array $array): HandledResponse + { + $this->records = $array; + return $this; + } + + /** + * Append a single record to the record collection + * + * @param string $string + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function appendRecord(?string $string): HandledResponse + { + $this->records[] = $string; + return $this; + } + + /** + * Append a array of records to the collection + * + * @param array $array + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function appendRecords(?array $array): HandledResponse + { + $this->records = array_merge($this->records, $array); + return $this; + } + + /** + * Get the record collection + * + * @return array + */ + public function getRecords(): array + { + return (isset($this->records)&& !is_null($this->records))?$this->records:[]; + } + + /** + * Set the timestamp + * + * @param int $int + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setTimestamp(?int $int): HandledResponse + { + $this->timestamp = $int; + return $this; + } + + /** + * Get the timestamp + * @return int + */ + public function getTimestamp(): int + { + return (isset($this->timestamp)&& !is_null($this->timestamp))?$this->timestamp:0; + } + + /** + * Set IsSuccessful + * + * @param bool $bool + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setIsSuccessful(?bool $bool): HandledResponse + { + $this->isSuccessful = $bool; + return $this; + } + + /** + * Get IsSuccessful + * + * @return bool + */ + public function isSuccessful(): bool + { + return (isset($this->isSuccessful)&& !is_null($this->isSuccessful))?$this->isSuccessful:true; + } + + /** + * Set IsWpError + * + * @param bool $bool + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setIsWpError(?bool $bool): HandledResponse + { + $this->isWpError = $bool; + return $this; + } + + /** + * Get IsWpError + * @return bool + */ + public function isWpError(): bool + { + return (isset($this->isWpError)&& !is_null($this->isWpError))?$this->isWpError:false; + } + + /** + * Set IsApiError + * + * @param bool $bool + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setIsApiError(?bool $bool): HandledResponse + { + $this->isApiError = $bool; + return $this; + } + + /** + * Get IsApiError + * + * @return bool + */ + public function isApiError(): bool + { + return (isset($this->isApiError)&& !is_null($this->isApiError))?$this->isApiError:false; + } + + /** + * Set IsException + * + * @param bool $bool + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setIsException(?bool $bool): HandledResponse + { + $this->isException = $bool; + return $this; + } + + /** + * Get IsException + * + * @return bool + */ + public function isException(): bool + { + return (isset($this->isException)&& !is_null($this->isException))?$this->isException:false; + } + + /** + * Set HasNoData + * + * @param bool $bool + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setHasNoData(?bool $bool): HandledResponse + { + $this->hasNoData = $bool; + return $this; + } + + /** + * Get HasNoData + * + * @return bool + */ + public function hasNoData(): bool + { + return (isset($this->hasNoData)&& !is_null($this->hasNoData))?$this->hasNoData:false; + } + + /** + * Set ErrorCode + * + * @param int $int + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setErrorCode(?int $int): HandledResponse + { + $this->errorCode = $int; + return $this; + } + + /** + * Get ErrorCode + * + * @return int + */ + public function getErrorCode(): int + { + return (isset($this->errorCode)&& !is_null($this->errorCode))?$this->errorCode:0; + } + + /** + * Get ErrorMessages + * + * @param array $array + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setErrorMessages(?array $array): HandledResponse + { + $this->errorMessages = $array; + return $this; + } + + /** + * Append a single error message to collection + * + * @param string $string + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function appendErrorMessage(?string $string): HandledResponse + { + $this->errorMessages[] = $string; + return $this; + } + + /** + * Get ErrorMessages + * + * @return array + */ + public function getErrorMessages(): array + { + return (isset($this->errorMessages)&& !is_null($this->errorMessages))?$this->errorMessages:[]; + } + + /** + * Set ResponseBody + * + * @param string $string + * @return \NFMailchimp\EmailCRM\Shared\Entities\HandledResponse + */ + public function setResponseBody(?string $string): HandledResponse + { + $this->responseBody = $string; + return $this; + } + + /** + * Get ResponseBody + * + * @return string + */ + public function getResponseBody(): string + { + return (isset($this->responseBody)&& !is_null($this->responseBody))?$this->responseBody:''; + } +} diff --git a/lib/Shared/Entities/OpenAuthCredentials.php b/lib/Shared/Entities/OpenAuthCredentials.php new file mode 100644 index 0000000..d5bdcf6 --- /dev/null +++ b/lib/Shared/Entities/OpenAuthCredentials.php @@ -0,0 +1,190 @@ +clientId = $clientId; + return $this; + } + + /** + * Get client id + * @return string + */ + public function getClientId(): string + { + return $this->clientId; + } + + /** + * Set client secret + * + * @param string $clientSecret + * @return SimpleEntity + */ + public function setClientSecret(string $clientSecret): SimpleEntity + { + $this->clientSecret = $clientSecret; + return $this; + } + + /** + * Get client secret + * + * @return string + */ + public function getClientSecret(): string + { + return $this->clientSecret; + } + + /** + * Set authorization code + * + * @param string|null $authorizationCode + * @return SimpleEntity + */ + public function setAuthorizationCode(?string $authorizationCode): SimpleEntity + { + $this->authorizationCode = $authorizationCode; + return $this; + } + + /** + * Get authorization code + * + * @return string + */ + public function getAuthorizationCode(): string + { + return (isset($this->authorizationCode)&& !is_null($this->authorizationCode))?$this->authorizationCode:''; + } + + /** + * Set redirect URI + * + * @param string|null $redirectUri + * @return SimpleEntity + */ + public function setRedirectUri(?string $redirectUri): SimpleEntity + { + $this->redirectUri = $redirectUri; + return $this; + } + + /** + * Get redirect URI + * + * @return string + */ + public function getRedirectUri(): string + { + return (isset($this->redirectUri)&& !is_null($this->redirectUri))?$this->redirectUri:''; + } + + /** + * Set refresh token + * + * @param string|null $refreshToken + * @return SimpleEntity + */ + public function setRefreshToken(?string $refreshToken): SimpleEntity + { + $this->refreshToken = $refreshToken; + return $this; + } + + /** + * Get refresh token + * + * @return string + */ + public function getRefreshToken(): string + { + return (isset($this->refreshToken)&& !is_null($this->refreshToken))?$this->refreshToken:''; + } + + /** + * Set access token + * + * @param string|null $accesstoken + * @return SimpleEntity + */ + public function setAccessToken(?string $accesstoken): SimpleEntity + { + $this->accessToken = $accesstoken; + return $this; + } + + /** + * Get access token + * + * @return string + */ + public function getAccessToken(): string + { + return (isset($this->accessToken)&& !is_null($this->accessToken))?$this->accessToken:''; + } +} diff --git a/lib/Shared/Entities/Option.php b/lib/Shared/Entities/Option.php new file mode 100644 index 0000000..58a4793 --- /dev/null +++ b/lib/Shared/Entities/Option.php @@ -0,0 +1,69 @@ +label) ? (string) $this->label : ''; + } + + /** + * Return option value + * @return string + */ + public function getValue(): string + { + return isset($this->value) ? (string) $this->value : ''; + } + + /** + * Set option label + * @param string $stringValue + * @return Option + */ + public function setLabel(string $stringValue): Option + { + $this->label = $stringValue; + + return $this; + } + + /** + * Set option label + * @param string $stringValue + * @return Option + */ + public function setValue(string $stringValue): Option + { + $this->value = $stringValue; + + return $this; + } +} diff --git a/lib/Shared/Entities/Options.php b/lib/Shared/Entities/Options.php new file mode 100644 index 0000000..c52158e --- /dev/null +++ b/lib/Shared/Entities/Options.php @@ -0,0 +1,66 @@ +options[] = $option; + + return $this; + } + + /** + * Return option collection as array + * @return array + */ + public function toArray(): array + { + + $toArray = []; + + foreach ($this->options as $option) { + $toArray[] = $option->toArray(); + } + + return $toArray; + } + + /** + * Convert array into Options + * @param array $items + * @return SimpleEntity + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $option) { + if (is_a($option, Option::class)) { + $obj->addOption($option); + } elseif (is_array($option)) { + $obj->addOption(Option::fromArray($option)); + } + } + return $obj; + } +} diff --git a/lib/Shared/Entities/ResponseData.php b/lib/Shared/Entities/ResponseData.php new file mode 100644 index 0000000..e523991 --- /dev/null +++ b/lib/Shared/Entities/ResponseData.php @@ -0,0 +1,203 @@ +get_message() + * @var string + */ + protected $message = ''; + + /** + * Programmatic word(s) describing what generated this response data + * @var string + */ + protected $context = ''; + + /** + * Human-readable instructions to help address any exception issues + * @var string + */ + protected $diagnostics = ''; + + /** + * Usually `success` or `failure` to categorize the response + * @var string + */ + protected $type = ''; + + /** + * + * @var string + */ + protected $note = ''; + + /** + * Return Response data as ResponseData entity + * @param array $items + * @return SimpleEntity + */ + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + + foreach ($items as $property => $value) { + if (property_exists($obj, $property)) { + if (is_object($value)) { + $value = json_encode($value); + } + + $obj->$property = $value; + } + } + return $obj; + } + + /** + * Return array of ResponseData + * @return array + */ + public function toArray(): array + { + $vars = get_object_vars($this); + $array = []; + foreach ($vars as $property => $value) { + $array[$property] = $value; + } + return $array; + } + + /** + * Return Response + * @return string + */ + public function getResponse(): string + { + return $this->response; + } + + /** + * Return Message + * @return string + */ + public function getMessage(): string + { + return $this->message; + } + + /** + * Return Context + * @return string + */ + public function getContext(): string + { + return $this->context; + } + + /** + * Return Diagnostics + * @return string + */ + public function getDiagnostics(): string + { + return $this->diagnostics; + } + + /** + * Return Type + * @return string + */ + public function getType(): string + { + return $this->type; + } + + /** + * Return Note + * @return string + */ + public function getNote(): string + { + return $this->note; + } + + /** + * Set Response + * @return SimpleEntity + */ + public function setResponse(string $value): SimpleEntity + { + $this->response = $value; + + return $this; + } + + /** + * Set Message + * @return SimpleEntity + */ + public function setMessage(string $value): SimpleEntity + { + $this->message = $value; + return $this; + } + + /** + * Set Context + * @return SimpleEntity + */ + public function setContext(string $value): SimpleEntity + { + $this->context = $value; + return $this; + } + + /** + * Set Diagnostics + * @return SimpleEntity + */ + public function setDiagnostics(string $value): SimpleEntity + { + $this->diagnostics = $value; + return $this; + } + + /** + * Set Type + * @return SimpleEntity + */ + public function setType(string $value): SimpleEntity + { + $this->type = $value; + return $this; + } + + /** + * Set Note + * @return SimpleEntity + */ + public function setNote(string $value): SimpleEntity + { + $this->note = $value; + return $this; + } +} diff --git a/lib/Shared/Entities/SubmissionData.php b/lib/Shared/Entities/SubmissionData.php new file mode 100644 index 0000000..868a83a --- /dev/null +++ b/lib/Shared/Entities/SubmissionData.php @@ -0,0 +1,50 @@ +setItems($items); + $this->fields = $fields; + } + + /** + * Get value or default + * + * @param string $key + * @param null $default + * @return mixed|null + */ + public function getValue(string $key, $default = null) + { + if ($this->hasValue($key)) { + return $this->$key; + } + return $default; + } +} diff --git a/lib/Shared/SimpleEntity.php b/lib/Shared/SimpleEntity.php new file mode 100644 index 0000000..4bf16b2 --- /dev/null +++ b/lib/Shared/SimpleEntity.php @@ -0,0 +1,63 @@ + $value) { + if (is_object($value) && is_callable([$value, 'toArray'])) { + $value = $value->toArray(); + } + $array[$property] = $value; + } + return $array; + } + + public static function fromArray(array $items): SimpleEntity + { + $obj = new static(); + foreach ($items as $property => $value) { + $obj = $obj->__set($property, $value); + } + return $obj; + } + + public function jsonSerialize() + { + return $this->toArray(); + } + + /** @inheritdoc */ + public function __get($name) + { + $getter = 'get' . ucfirst($name); + if (method_exists($this, $getter)) { + return call_user_func([$this, $getter]); + } + if (property_exists($this, $name)) { + return $this->$name; + } + } + + /** @inheritdoc */ + public function __set($name, $value) + { + $setter = 'set' . ucfirst($name); + if (method_exists($this, $setter)) { + return call_user_func([$this, $setter], $value); + } + if (property_exists($this, $name)) { + $this->$name = $value; + return $this; + } + return $this; + } +} diff --git a/lib/Shared/Storage/InMemoryArrayStore.php b/lib/Shared/Storage/InMemoryArrayStore.php new file mode 100644 index 0000000..9bde3fc --- /dev/null +++ b/lib/Shared/Storage/InMemoryArrayStore.php @@ -0,0 +1,46 @@ +key = $key; + $this->data = []; + } + + public function getData(): array + { + return $this->data; + } + + /** @inheritDoc */ + public function saveData(array $data) + { + //would save to database in a real adapter + $this->data = $data; + } + + /** @inheritDoc */ + public function getKey(): string + { + return $this->key; + } +} diff --git a/lib/Shared/Traits/ConvertsFromArrayWithSnakeCaseing.php b/lib/Shared/Traits/ConvertsFromArrayWithSnakeCaseing.php new file mode 100644 index 0000000..6763e8d --- /dev/null +++ b/lib/Shared/Traits/ConvertsFromArrayWithSnakeCaseing.php @@ -0,0 +1,35 @@ + $value) { + $obj->__set(static::unSnake($property), $value); + } + return $obj; + } + + + /** + * Convert snake case to camel case + * @param string $str + * @return string + */ + protected static function unSnake(string $str): string + { + if (false === strpos($str, '_')) { + return $str; + } + $str = ucWords($str, '_'); + return lcfirst(str_replace('_', '', $str)); + } +} diff --git a/lib/Shared/Traits/ConvertsToArrayWithSnakeCaseing.php b/lib/Shared/Traits/ConvertsToArrayWithSnakeCaseing.php new file mode 100644 index 0000000..30df106 --- /dev/null +++ b/lib/Shared/Traits/ConvertsToArrayWithSnakeCaseing.php @@ -0,0 +1,49 @@ + $value) { + if (is_object($value) && is_callable([$value, 'toArray'])) { + $value = $value->toArray(); + } elseif (is_callable([$this,$this->getterName($property)])) { + $value = call_user_func([$this,$this->getterName($property)]); + } + + $array[$this->snake($property)] = $value; + } + return $array; + } + + protected function getterName(string $property) + { + + return 'get'. ucfirst($property); + } + + + /** + * Convert camel-cased string to snake case + * + * @see https://stackoverflow.com/a/1993772 + * @param string $str + * @return string + */ + protected function snake(string $str): string + { + preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $str, $matches); + $ret = $matches[0]; + foreach ($ret as &$match) { + $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match); + } + return implode('_', $ret); + } +} diff --git a/lib/Shared/Traits/UsesArrayForEntity.php b/lib/Shared/Traits/UsesArrayForEntity.php new file mode 100644 index 0000000..84b22fa --- /dev/null +++ b/lib/Shared/Traits/UsesArrayForEntity.php @@ -0,0 +1,88 @@ +items)) { + return $this->items[$name]; + } + } + + /** + * Update a single config value + * + * @param string $name Value name + * @param mixed $value New value + * @return SimpleEntity + */ + public function __set($name, $value) + { + if (array_key_exists($name, $this->items)) { + $this->items[$name] = $value; + } + + return $this; + } + + /** @inheritDoc */ + public static function fromArray(array $items): SimpleEntity + { + return new static($items); + } + + /** @inheritDoc */ + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Can this object supply a value? + * + * @param string $name Name of the value + * @return bool + */ + public function hasValue($name): bool + { + return ! empty($this->items) && array_key_exists($name, $this->items); + } + + /** @inheritDoc */ + public function toArray(): array + { + return $this->items; + } + + protected function setItems(array $items) + { + $this->items = $items; + } + + /** + * At item to collection + * + * @param string $key + * @param $value + */ + public function addData(string $key, $value) + { + $this->items[$key] = $value; + } +} diff --git a/lib/WpBridge/Contracts/WpBridgeContract.php b/lib/WpBridge/Contracts/WpBridgeContract.php new file mode 100644 index 0000000..7152c9b --- /dev/null +++ b/lib/WpBridge/Contracts/WpBridgeContract.php @@ -0,0 +1,14 @@ +key = $key; + } + + /** @inheritDoc */ + public function getData(): array + { + return get_option($this->getKey(), []); + } + + /** @inheritDoc */ + public function getKey(): string + { + return $this->key; + } + + /** @inheritDoc */ + public function saveData(array $data) + { + update_option($this->getKey(), $data); + } +} diff --git a/lib/WpBridge/Database/TransientStore.php b/lib/WpBridge/Database/TransientStore.php new file mode 100644 index 0000000..a7e1eae --- /dev/null +++ b/lib/WpBridge/Database/TransientStore.php @@ -0,0 +1,48 @@ +key = $key; + } + + /** @inheritDoc */ + public function getData(): array + { + $savedData = get_transient($this->key); + if (is_array($savedData)) { + return $savedData; + } + return []; + } + + /** @inheritDoc */ + public function getKey(): string + { + return $this->key; + } + + /** @inheritDoc */ + public function saveData(array $data) + { + set_transient($this->key, $data); + } +} diff --git a/lib/WpBridge/Database/UseWpdb.php b/lib/WpBridge/Database/UseWpdb.php new file mode 100644 index 0000000..210aad2 --- /dev/null +++ b/lib/WpBridge/Database/UseWpdb.php @@ -0,0 +1,44 @@ +setWpdb($wpdb); + } + + /** + * @inheritDoc + */ + public function setWpdb(\wpdb $wpdb): WpdbInterface + { + $this->wpdb = $wpdb; + return $this; + } + + /** + * @inheritDoc + */ + public function getWpdb(): \wpdb + { + return $this->wpdb; + } + + /** + * @inheritDoc + */ + public function getResults(string $sql) + { + return $this->wpdb->get_results($sql); + } +} diff --git a/lib/WpBridge/Database/WPOptionsApi.php b/lib/WpBridge/Database/WPOptionsApi.php new file mode 100644 index 0000000..c65b3e6 --- /dev/null +++ b/lib/WpBridge/Database/WPOptionsApi.php @@ -0,0 +1,25 @@ +get_error_message(),(int) $response->get_error_code()); + } else { + + $status = (string)wp_remote_retrieve_response_code($response); + + $message =(string)wp_remote_retrieve_body($response); + + if ('DELETE' === $method) { + if ('204' === $status) { + return true; + } + return false; + } + if (2 == substr($status, 0, 1)) { + return json_decode(wp_remote_retrieve_body($response)); + } + throw new MailchimpAPIException($message, $status); + } + } +} diff --git a/lib/WpBridge/Http/RemoteRequest.php b/lib/WpBridge/Http/RemoteRequest.php new file mode 100644 index 0000000..8752961 --- /dev/null +++ b/lib/WpBridge/Http/RemoteRequest.php @@ -0,0 +1,193 @@ +setDefaultHttpArgs(); + } + + /** + * Set HTTP request URL + * + * @param string $url + * @return \NFMailchimp\EmailCRM\AmoCrm\Handlers\RemoteRequest + */ + public function setUrl(string $url): RemoteRequestContract + { + $this->url = $url; + return $this; + } + + /** + * Set an HTTP argument + * + * @param string $arg + * @param mixed $value + * @return \NFMailchimp\EmailCRM\AmoCrm\Handlers\RemoteRequest + */ + public function setHttpArg(string $arg, $value): RemoteRequestContract + { + + if (in_array($arg, $this->allowedArgs)) { + $this->httpArgs[$arg] = $value; + } + + return $this; + } + + /** + * Set an HTTP argument + * + * @param string $arg + * @param mixed $value + * @return \NFMailchimp\EmailCRM\AmoCrm\Handlers\RemoteRequest + */ + public function addQueryArg(string $arg, $value): RemoteRequestContract + { + + $this->queryArgs[$arg] = $value; + + return $this; + } + + /** + * Set HTTP request body + * @param mixed $body + * @return \NFMailchimp\EmailCRM\AmoCrm\Handlers\RemoteRequest + */ + public function setBody($body): RemoteRequestContract + { + $this->body = $body; + return $this; + } + + /** + * Set an HTTP header parameter + * @param string $arg + * @param mixed $value + * @return \NFMailchimp\EmailCRM\AmoCrm\Handlers\RemoteRequest + */ + public function setHeaderParameter($arg, $value): RemoteRequestContract + { + $this->headers[$arg] = $value; + return $this; + } + + protected function finalizeRequest() + { + if (!is_null($this->headers)) { + $this->httpArgs['headers'] = $this->headers; + } + if (!is_null($this->body)) { + $this->httpArgs['body'] = $this->body; + } + + if (!empty($this->queryArgs)) { + $this->url = add_query_arg($this->queryArgs, $this->url); + } + } + /** + * + * @return HandledResponse + */ + public function handle() + { + $this->finalizeRequest(); + + $this->handledResponse= new HandledResponse(); + + $rawResponse = wp_remote_request($this->url, $this->httpArgs); + + if (is_wp_error($rawResponse)) { + $this->handledResponse->setIsWpError(true); + $this->handledResponse->setIsSuccessful(false); + $this->handledResponse->setErrorMessages($rawResponse->get_error_messages()); + } else { + $this->handledResponse->setResponseBody($rawResponse['body']); + } + + $this->handledResponse->setTimestamp(time()); + + return $this->handledResponse; + } + + /** + * Set default arguments + */ + protected function setDefaultHttpArgs() + { + $this->httpArgs = [ + 'timeout' => 45, + 'redirection' => 0, + 'httpversion' => '1.0', + 'sslverify' => true, + 'method' => 'GET' + ]; + } +} diff --git a/lib/WpBridge/RestApi/AuthorizeRequestWithWordPressUser.php b/lib/WpBridge/RestApi/AuthorizeRequestWithWordPressUser.php new file mode 100644 index 0000000..d1d5fd5 --- /dev/null +++ b/lib/WpBridge/RestApi/AuthorizeRequestWithWordPressUser.php @@ -0,0 +1,38 @@ +capability = $capability; + } + + /** + * @param RequestContract $request + * @return bool + */ + public function authorizeRequest(RequestContract $request): bool + { + return current_user_can($this->capability); + } +} diff --git a/lib/WpBridge/RestApi/CreateWordPressEndpoints.php b/lib/WpBridge/RestApi/CreateWordPressEndpoints.php new file mode 100644 index 0000000..e4d256c --- /dev/null +++ b/lib/WpBridge/RestApi/CreateWordPressEndpoints.php @@ -0,0 +1,119 @@ +namespace = $namespace; + $this->registrationFunction = $registrationFunction; + } + + /** + * Register an endpoint with WordPress + * + * @param Endpoint $endpoint + */ + public function registerRouteWithWordPress(Endpoint $endpoint) + { + call_user_func($this->registrationFunction, $this->namespace, $endpoint->getUri(), $this->wpArgs($endpoint)); + } + + + /** + * Create arguments for register_rest_route() + * + * @param Endpoint $endpoint + * + * @return array + */ + public function wpArgs(Endpoint $endpoint) + { + $callback = $this->createCallBack([$endpoint,'handleRequest']); + $permissionsCallback = $this->createAuthCallBack([$endpoint,'authorizeRequest']); + return [ + 'args' => $endpoint->getArgs(), + 'methods' => $endpoint->getHttpMethod(), + 'callback' => $callback, + 'permission_callback' => $permissionsCallback + ]; + } + + /** + * Create the callable function for WordPress to use as the callback for this endpoint + * + * @param callable $handler + * @return callable + */ + protected function createCallBack(callable $handler) : callable + { + + return function (\WP_REST_Request $_request) use ($handler) { + $request = $this->requestFromWp($_request); + $response = $handler($request); + return new \WP_REST_Response( + $response->getData(), + $response->getStatus(), + $response->getHeaders() + ); + }; + } + + /** + * Create a callable function WordPress will call to authorize the request + * + * @param callable $handler + * @return callable + */ + protected function createAuthCallBack(callable $handler) : callable + { + return function ($_request) use ($handler) { + $request = $this->requestFromWp($_request); + return $handler($request); + }; + } + + /** + * Create instance of request class from a WordPress request + * + * @param \WP_REST_Request $_request + * + * @return Request + */ + protected function requestFromWp(\WP_REST_Request $_request): RequestContract + { + $request = new Request(); + $request->setParams(array_merge($_request->get_params(), $_request->get_url_params())); + foreach ($_request->get_headers() as $header => $headerValue) { + $request->setHeader($header, $headerValue); + } + return $request; + } +} diff --git a/lib/WpBridge/WpBridge.php b/lib/WpBridge/WpBridge.php new file mode 100644 index 0000000..5cfb08a --- /dev/null +++ b/lib/WpBridge/WpBridge.php @@ -0,0 +1,38 @@ +=')) { + if (class_exists('Ninja_Forms')) { + include_once __DIR__ . '/bootstrap.php'; + } else { + //Ninja Forms is not active + } + } else { + add_action('admin_notices', 'nf_mailchimp_php_nag'); + } +} + +/** + * Callback for admin notice shown when PHP version is not correct. + * + * @since 3.2.0 + */ +function nf_mailchimp_php_nag() { + ?> +
+

+ %s', + esc_html__('Learn More', 'nf-mailchimp') + ) + ?> +

+
+ mailchimpApi = $mailchimpApi; + parent::__construct(); + } + + /** @inheritDoc */ + protected function setActionProperties(): void + { + // This should be a slug format + $this->_name = 'mailchimp'; + + // Ensure your name is short, and translatable + $this->_nicename = 'Mailchimp'; + + // future documentation + $this->_tags = ['newsletter']; + + // These two are the coarse and fine settings for putting your action in the action queue + $this->_timing = 'normal'; // can be `early` `normal` `late` + $this->_priority = 10; // can be a string version of an integer + } + + /** @inheritDoc */ + protected function setActionSettings( ): void + { + $this->_settings['double_opt_in'] = [ + 'name' => 'double_opt_in', + 'type' => 'toggle', + 'label' => __('Require subscribers to confirm their subscription', 'ninja-forms-mail-chimp'), + 'group' => 'advanced', + 'width' => 'full', + 'value' => 0 + ]; + + $this->_settings['enable_new_tags'] = [ + 'name' => 'enable_new_tags', + 'type' => 'toggle', + 'label' => __('Allow creation of NEW tags from submitted values', 'ninja-forms-mail-chimp'), + 'group' => 'advanced', + 'width' => 'full', + 'value' => 0 + ]; + } + + /** @inheritDoc */ + protected function instantiateActionProcessor(): InterfacesProcessAction + { + return new AddOrUpdateMailchimp(); + } + + /** @inheritDoc */ + protected function constructRuntimeData(array $actionSettings, $formId, array $data):void{ + $this->runtimeData['mailchimpApi']=$this->mailchimpApi; + } + + /** @inheritDoc */ + public function get_lists() + { + $return = $this->getLists(); + + return $return; + } + + /** + * Make API calls to construct array of lists + * + * @return array + */ + protected function getLists(): array + { + $getNfStructuredLists = new GetNfStructuredLists($this->mailchimpApi); + $lists = $getNfStructuredLists->getLists(); + + // Make/update an option every time the list is updated. + // @todo: Verify if needed - doesn't appear to be used - SRS + update_option('ninja_forms_mailchimp_interests', $lists); + return $lists; + } + +} diff --git a/src/Admin/DiagnosticScreen.php b/src/Admin/DiagnosticScreen.php new file mode 100644 index 0000000..c5a312f --- /dev/null +++ b/src/Admin/DiagnosticScreen.php @@ -0,0 +1,32 @@ + __('Mailchimp Subscribe', 'ninja-forms-authorize-net'), + 'labelValueCollection' => $labelValueCollection + + ]; + + $return = MetaboxOutputEntity::fromArray($array); + } + + return $return; + } + + protected static function extractResponses($mailchimpSubmissionData): array + { + $return = []; + + if (isset($mailchimpSubmissionData['responseData']) && is_array($mailchimpSubmissionData['responseData'])) { + foreach ($mailchimpSubmissionData['responseData'] as $responseDataArray) { + $responses[] = ResponseData::fromArray($responseDataArray); + } + } else { + $return[] = [ + 'label' => 'No Data', + 'value' => 'Submission could not communicate with Mailchimp' + ]; + return $return; + } + + /** @var ResponseData $responseData */ + foreach ($responses as $responseData) { + + if ( + 'error' !== $responseData->getType() + ) { + $subscriber = Subscriber::fromArray(json_decode($responseData->getResponse(), true)); + $return[] = [ + 'label' => __('Subscriber Info', 'ninja-forms-mail-chimp'), + 'value' => __('Successfully subscribed', 'ninja-forms-mail-chimp') + ]; + $return[] = [ + 'label' => __('Email', 'ninja-forms-mail-chimp'), + 'value' => esc_html($subscriber->email_address) + ]; + $return[] = [ + 'label' => __('Status', 'ninja-forms-mail-chimp'), + 'value' => esc_html($subscriber->status) + ]; + $return[] = [ + 'label' => __('List Id', 'ninja-forms-mail-chimp'), + 'value' => esc_html($subscriber->listId) + ]; + } else { + $return[] = [ + 'label' => __('Notice', 'ninja-forms-mail-chimp'), + 'value' => __('Request rejected', 'ninja-forms-mail-chimp') + ]; + $return[] = [ + 'label' => __('Rejection', 'ninja-forms-mail-chimp'), + 'value' => $responseData->getNote() + ]; + } + } + + return $return; + } +} diff --git a/src/Contracts/NinjaFormsMailchimpContract.php b/src/Contracts/NinjaFormsMailchimpContract.php new file mode 100644 index 0000000..f6e1792 --- /dev/null +++ b/src/Contracts/NinjaFormsMailchimpContract.php @@ -0,0 +1,38 @@ +autogenerateForm = $autogenerateForm; + } + /** + * Add a DiagnoseException handler + * @param DiagnoseException $diagnoseException + * @return void + */ + public function addDiagnoseException(DiagnoseException $diagnoseException): void + { + $this->diagnoseException = $diagnoseException; + } + + public function addAuthorizer(AuthorizeRequestContract $authorizer) + { + $this->authorizer=$authorizer; + } + /** @inheritDoc */ + public function getHttpMethod(): string + { + return 'POST'; + } + + /** @inheritDoc */ + public function getArgs(): array + { + return [ + 'listId' => [ + 'type' => 'string', + 'required' => true, + ], + 'formTitle' => [ + 'type' => 'string', + 'required' => false, + ] + ]; + } + + /** @inheritDoc */ + public function getUri(): string + { + return 'nf-autogenerate/'; + } + + /** + * Authorize the request + * + * @param RequestContract $request + * @return bool + */ + public function authorizeRequest(RequestContract $request): bool + { + return $this->authorizer->authorizeRequest($request); + } + + /** @inheritDoc */ + public function handleRequest(RequestContract $request): ResponseContract + { + + $listId=$request->getParam('listId'); + + $formTitle = !is_null($request->getParam('formTitle'))?urldecode($request->getParam('formTitle')):'Mailchimp Autogenerated Form'; + try { + $this->autogenerateForm->handle($listId, $formTitle); + $formId=$this->autogenerateForm->getFormId(); + $response = NfMailchimpResponse::fromArray( + [ + 'data'=>['formId'=>$formId], + 'status'=>200 + ] + ); + wp_redirect(admin_url().'?page=ninja-forms&form_id='.$formId); + exit(); + + return $response; + } catch (\Exception $exception) { + $response = $this->constructExceptionResponse($exception, 'AutogenerateForm'); + return $response; + } + } + + /** + * Construct exception response from given exception + * @param \Exception $exception + * @param string $context + * @return Response + */ + protected function constructExceptionResponse($exception, string $context = ''): ResponseContract + { + $response = new NfMailchimpResponse(); + $exceptionString = $exception->getMessage(); + + if (isset($this->diagnoseException)) { + $diagnostics = $this->diagnoseException->handle($exceptionString, $context); + } else { + $diagnostics = []; + } + + $data = [ + 'message' => $exceptionString, + 'context' => $context, + 'diagnostics' => $diagnostics + ]; + + $response->setData($data); + + $response->setStatus($exception->getCode() ? (int)$exception->getCode() : 500); + return $response; + } +} diff --git a/src/Entities/NfMailchimpResponse.php b/src/Entities/NfMailchimpResponse.php new file mode 100644 index 0000000..5d215c4 --- /dev/null +++ b/src/Entities/NfMailchimpResponse.php @@ -0,0 +1,170 @@ +setData($items['data']); + } + + if (isset($items['headers']) && is_array($items['headers'])) { + $obj->setHeaders($items['headers']); + } + + if (isset($items['status']) && is_int($items['status'])) { + $obj->setStatus($items['status']); + } + + if (isset($items['httpMethod']) && is_string($items['httpMethod'])) { + $obj->setHttpMethod($items['httpMethod']); + } + + return $obj; + } + + /** + + * Get response data + * + * @return array + */ + public function getData(): array + { + return $this->data; + } + + /** + * Get response headers + * + * @return array + */ + public function getHeaders(): array + { + return $this->headers; + } + + /** + * Get the HTTP status code + * + * @return int + */ + public function getStatus(): int + { + return $this->status; + } + + /** + * Set the HTTP status code + * + * @param int $code + * + * @return HttpResponseContract + */ + public function setStatus(int $code): HttpResponseContract + { + $this->status = $code; + return $this; + } + + /** + * Set the request headers + * + * @param array $headers + * + * @return HttpContract + */ + public function setHeaders(array $headers): HttpContract + { + $this->headers = $headers; + + return $this; + } + + /** + * Set the response body data + * + * @param array $data + * + * @return HttpResponseContract + */ + public function setData(array $data): HttpResponseContract + { + + $this->data = $data; + + return $this; + } + + /** + * Get the HTTP method for the response + * + * @return string + */ + public function getHttpMethod(): string + { + + return $this->httpMethod; + } + + /** + * Set the HTTP method for the response + * + * @param string $method + * + * @return HttpResponseContract + */ + public function setHttpMethod(string $method) + { + + $this->httpMethod = $method; + + return $this; + } +} diff --git a/src/Filters/NinjaFormsPluginSettings.php b/src/Filters/NinjaFormsPluginSettings.php new file mode 100644 index 0000000..8de58b2 --- /dev/null +++ b/src/Filters/NinjaFormsPluginSettings.php @@ -0,0 +1,39 @@ + [ + 'id' => 'ninja_forms_mc_api', + 'label' => 'API Key', + 'type' => 'textbox' + ] + ]; + + // Register your additional actions by keying an instatiated object here + + // Ensure you RETURN the array + return $return; + } +} diff --git a/src/Filters/NinjaFormsPluginSettingsGroups.php b/src/Filters/NinjaFormsPluginSettingsGroups.php new file mode 100644 index 0000000..d55034b --- /dev/null +++ b/src/Filters/NinjaFormsPluginSettingsGroups.php @@ -0,0 +1,35 @@ + 'mail_chimp', + 'label' => 'Mailchimp' + ]; + + // Register your additional actions by keying an instatiated object here + + // Ensure you RETURN the array + return $return; + } +} diff --git a/src/Handlers/AddOrUpdateMailchimp.php b/src/Handlers/AddOrUpdateMailchimp.php new file mode 100644 index 0000000..b3b0d35 --- /dev/null +++ b/src/Handlers/AddOrUpdateMailchimp.php @@ -0,0 +1,164 @@ +getData(); + + $fieldsData = $data['fields']; + + $opt_in = $this->isOptIn($fieldsData); + + if(!$opt_in){ + return $submissionDataDataHandler; + } + + try { + $newsletterId = $this->getNewsletterId($actionSettingsDataHandler); + + $mailchimpApi = $this->getApi($runtimeData); + + $apiReadySubscriber = $this->getApiReadySubscriber($runtimeData, $newsletterId, $actionSettingsDataHandler); + + $responseObject = $mailchimpApi->addOrUpdateMember($newsletterId, $apiReadySubscriber->getEmailAddress(), $apiReadySubscriber->getRequestBody()); + + $responseArray = (ResponseData::fromArray([ + 'type' => 'success', + 'response' => $responseObject, + 'context' => 'SubscribeFormActionHandler_subscribeToList' + ]))->toArray(); + + $submissionDataDataHandler->pushExtra($responseArray); + + return $submissionDataDataHandler; + } catch (\UnexpectedValueException $unexpectedValue) { + + \error_log('Caught value exception'); + \error_log($unexpectedValue->getMessage()); + \error_log(self::class . '::' . __FUNCTION__); + } catch (MailchimpApiException $mailchimpException) { + $rejectionMessage = (ResponseData::fromArray( [ + 'type' => 'error', + 'context' => 'MailchimpSubscribeActionProcessHandler_Response', + 'note' => $mailchimpException->getMessage() + ]))->toArray(); + + $submissionDataDataHandler->pushExtra($rejectionMessage); + } catch (\Throwable $e) { + + \error_log($e->getMessage()); + \error_log(self::class . '::' . __FUNCTION__); + } finally { + return $submissionDataDataHandler; + } + } + + /** + * Return bool - if this sub has an opt-in field, is it checked? If no opt-in field, default to true + * @param array[] $fields + * @return bool + */ + protected function isOptIn(array $fields): bool + { + // Set true flag for later use. + $opt_in = true; + + // Loop over the fields from the form data and... + foreach ($fields as $field) { + // ...If the field type is equal to Mailchimp Opt continue. + if ('mailchimp-optin' != $field['type']) { + continue; + } + + // ...If the field value is the field value is false change the optin flag to false. + if (!$field['value']) { + $opt_in = false; + } + } + + return $opt_in; + } + + /** + * Construct object structured for Add/Update subscriber + * + * @param array $runtimeData + * @param string $newsletterId + * @param ActionSettingsDataHandler $actionSettingsDataHandler + * @return ConstructApiSubscriberFromActionSettings + */ + protected function getApiReadySubscriber(array $runtimeData, string $newsletterId, ActionSettingsDataHandler $actionSettingsDataHandler): ConstructApiSubscriberFromActionSettings + { + $mailchimpApi = $this->getApi($runtimeData); + + $singleList = SingleList::fromArray([ + 'id' => $newsletterId + ]); + + $audienceDefinition = (new GetAudienceDefinitionData($mailchimpApi))->handle($singleList); + + $subscriberBuilder = new SubscriberBuilder($audienceDefinition); + + $return = (new ConstructApiSubscriberFromActionSettings($actionSettingsDataHandler, $subscriberBuilder))->handle(); + + return $return; + } + + /** + * Get newsletter id from action settings + * + * @param ActionSettingsDataHandler $actionSettingsDataHandler + * + * @return string + * @throws \UnexpectedValueException + */ + private function getNewsletterId(ActionSettingsDataHandler $actionSettingsDataHandler): string + { + if ($actionSettingsDataHandler->getValue('newsletter_list', false)) { + + $return = $actionSettingsDataHandler->getValue('newsletter_list'); + } else { + throw new \UnexpectedValueException('Newsletter key does not exist in submission process data'); + } + return $return; + } + + /** + * Undocumented function + * + * @param array $runtimeData + * @return MailchimpApi + * @throws \\UnexpectedValueException + */ + private function getApi(array $runtimeData): MailchimpApi + { + if (isset($runtimeData['mailchimpApi'])) { + $return = $runtimeData['mailchimpApi']; + } else { + throw new \UnexpectedValueException('Mailchimp API not passed correctly in submission process data'); + } + + return $return; + } +} diff --git a/src/Handlers/AuthorizesTrue.php b/src/Handlers/AuthorizesTrue.php new file mode 100644 index 0000000..c5f8543 --- /dev/null +++ b/src/Handlers/AuthorizesTrue.php @@ -0,0 +1,27 @@ +mailchimpApi = $mailchimpApi; + } + + /** + * Autogenerate a Ninja Form given a listId and Form Title + * @param string $listId + * @param string $formTitle + */ + public function handle(string $listId, string $formTitle) + { + $this->setListId($listId); + $this->setFormTitle($formTitle); + $audienceDefinition = $this->getAudienceDefinition(); + $this->setAudienceDefinition($audienceDefinition); + + $formBuilder = $this->constructFormBuilder(); + $this->setFormBuilder($formBuilder); + + $this->constructNinjaFormWithAction(); + } + + /** + * Set the listId + * @param string $listId + * @return \NFMailchimp\NinjaForms\Mailchimp\Handlers\AutogenerateForm + */ + public function setListId(string $listId): AutogenerateForm + { + $this->listId = $listId; + return $this; + } + /** + * Set the form title within the class (different than NF form title) + * @param string $formTitle + * @return \NFMailchimp\NinjaForms\Mailchimp\Handlers\AutogenerateForm + */ + public function setFormTitle(string $formTitle): AutogenerateForm + { + $this->formTitle = $formTitle; + return $this; + } + /** + * Set Audience Definition + * + * @param AudienceDefinition $audienceDefinition + * @return \NFMailchimp\NinjaForms\Mailchimp\Handlers\AutogenerateForm + */ + public function setAudienceDefinition(AudienceDefinition $audienceDefinition): AutogenerateForm + { + $this->audienceDefinition = $audienceDefinition; + + // interest categories are part of audience definition; extract at same time + $this->interestCategories = array_keys($this->audienceDefinition->interestCategories->getInterestCategories()); + + return $this; + } + /** + * Set form builder + * @param FormBuilder $formBuilder + * @return \NFMailchimp\NinjaForms\Mailchimp\Handlers\AutogenerateForm + */ + public function setFormBuilder(FormBuilder $formBuilder):AutogenerateForm + { + $this->formBuilder = $formBuilder; + return $this; + } + + /** + * Construct a Ninja Form from the previously set FormBuilder entity + * @return void + */ + public function constructNinjaFormWithAction():void + { + $this->initializeForm(); + + $this->setNfFormTitle(); + $this->addEmailField(); + $this->addFormFields(); + $this->addSubmitButton(); + $this->addMailchimpAction(); + $this->addSaveAction(); + $this->addSuccessMessageAction(); + $this->nfForm->save(); + } + + /** + * Construct the form builder entity + */ + protected function constructFormBuilder() + { + $createFormBuilder = new CreateFormBuilder($this->audienceDefinition, new FormBuilder()); + $formBuilder = $createFormBuilder->getFormBuilder(); + $formBuilder->setTitle($this->formTitle); + return $formBuilder; + } + + /** + * Initialize a new form + */ + protected function initializeForm() + { + $this->nfForm = Ninja_Forms()->form(); + $this->nfForm->save(); + $this->formId=$this->nfForm->get_id(); + } + + /** + * Set the NF form title + */ + protected function setNfFormTitle() + { + + $this->nfForm->get()->update_settings( + [ + 'title' => $this->formBuilder->getTitle() + ] + ); + } + + /** + * Add email field + */ + protected function addEmailField() + { + + $nfField = $this->nfForm->field()->get(); + // increment order + $this->order++; + $type = $this->selectNFFieldType('email'); + $key = 'email_address'; + $settings = array( + 'type' => $type, + 'label' => 'Email Address', + 'label_post' => 'inside', + 'required' => true, + 'key' => $key, + 'order' => $this->order + ); + + + + $nfField->update_settings($settings)->save(); + + $this->addActionFieldMap($key); + } + + /** + * Add form fields + */ + protected function addFormFields() + { + + $collection = $this->formBuilder->getFormFields()->getFields(); + + foreach ($collection as $key => $field) { + $nfField = $this->nfForm->field()->get(); + // increment order + $this->order++; + $type = $this->selectNFFieldType($field->getType()); + + $settings = array( + 'type' => $type, + 'label' => $field->getLabel(), + 'label_post' => 'inside', + 'required' => $field->getRequired(), + 'key' => $key, + 'order' => $this->order + ); + + if (!empty($field->getOptions()->toArray())) { + $settings['options'] = $field->getOptions()->toArray(); + } + + if (0 !== $field->getCharacterLimit()) { + $settings['input_limit'] = $field->getCharacterLimit(); + } + + $nfField->update_settings($settings)->save(); + + $this->addActionFieldMap($key); + } + } + + /** + * Add submit button to the form + * @return void + */ + protected function addSubmitButton(): void + { + $nfField = $this->nfForm->field()->get(); + + $settings = array( + 'type' => 'submit', + 'label' => 'Submit', + 'label_post' => 'inside', + 'key' => 'submit' + ); + $nfField->update_settings($settings)->save(); + } + + /** + * Add action field map for given field key + * @param string $key + * @return void + */ + protected function addActionFieldMap(string $key): void + { + + $actionMetaKey = $this->listId . '_' . $key; + $actionMetaValue = '{field:' . $key . '}'; + + $mcEntity = $this->determineMailchimpEntity($key); + $interestsKey = $this->listId . '_interests'; + if ('interestCategory' === $mcEntity) { + if (isset($this->actionFieldMap[$interestsKey])) { + $temp = explode(',', $this->actionFieldMap[$interestsKey]); + } else { + $temp = []; + } + $temp[] = $actionMetaValue; + $this->actionFieldMap[$interestsKey] = implode(',', $temp); + } else { + $this->actionFieldMap[$actionMetaKey] = $actionMetaValue; + } + } + + /** + * Add the Mailchimp action to the form + * + * Currently hardcoded; perhaps switch to using delivered action entity + */ + protected function addMailchimpAction() + { + $action = $this->nfForm->action()->get(); + + $this->actionFieldMap['type'] = 'mailchimp'; + $this->actionFieldMap['label'] = 'MyMailchimp'; + $this->actionFieldMap['active'] = '1'; + $this->actionFieldMap['newsletter_list'] = $this->listId; + + $action->update_settings($this->actionFieldMap); + + $action->save(); + } + + /** + * Add Store Submission (programmatic name: save) to the form + * + */ + protected function addSaveAction() + { + $action = $this->nfForm->action()->get(); + + $actionMeta=[ + 'type'=>'save', + 'label'=>'Store Submission', + 'active'=>'1' + ]; + + + $action->update_settings($actionMeta); + + $action->save(); + } + + /** + * Add Store Submission (programmatic name: save) to the form + * + */ + protected function addSuccessMessageAction() + { + $action = $this->nfForm->action()->get(); + + $actionMeta=[ + 'type'=>'successmessage', + 'label'=>'Success Message', + 'success_msg'=>'

Your form has been successfully submitted.


', + 'active'=>'1' + ]; + + + $action->update_settings($actionMeta); + + $action->save(); + } + + /** + * Select the NF form field type from the Mailchimp field type + * @param string $incoming + * @return string + */ + protected function selectNFFieldType(string $incoming): string + { + + $outgoing = 'textbox'; + switch ($incoming) { + // Mailchimp email address uses NF email field type + case 'email': + $outgoing = 'email'; + break; + // MC multiselect uses NF listcheckbox + case 'multiselect': + // NF term + case 'listcheckbox': + $outgoing = 'listcheckbox'; + break; + // Mailchimp term + case 'radio': + // NF term + case 'listradio': + $outgoing = 'listradio'; + break; + // Mailchimp term + case 'dropdown': + // NF term + case 'listselect': + $outgoing = 'listselect'; + break; + } + return $outgoing; + } + + /** + * Determines if form field is for MergeVar, InterestCategory + * + * values = mergeVar | interestCategory + * @param string $key + * @return string + */ + protected function determineMailchimpEntity(string $key): string + { + $mcEntity = 'unknown'; + + if ($this->audienceDefinition->hasMergeVar($key)) { + $mcEntity = 'mergeVar'; + } elseif (in_array($key, $this->interestCategories)) { + $mcEntity = 'interestCategory'; + } + return $mcEntity; + } + + /** + * Return a selected audience definition for which to create form + * + * @return AudienceDefinition + */ + protected function getAudienceDefinition(): AudienceDefinition + { + + $singleList = SingleList::fromArray(['id'=>$this->listId]); + + $audienceDefinition = (new GetAudienceDefinitionData($this->mailchimpApi))->handle($singleList); + return $audienceDefinition; + } + + /** + * Get the newly created form Id + * @return int + */ + public function getFormId():int + { + return $this->formId; + } + /** + * Get the constructed Ninja Form + * @return NF_Abstracts_ModelFactory + */ + public function getNinjaForm():NF_Abstracts_ModelFactory + { + return $this->nfForm; + } +} diff --git a/src/Handlers/ConstructActionEntity.php b/src/Handlers/ConstructActionEntity.php new file mode 100644 index 0000000..9203f81 --- /dev/null +++ b/src/Handlers/ConstructActionEntity.php @@ -0,0 +1,112 @@ +nfMailchimp = $nfMailchimp; + $this->instantiateActionEntity(); + + $this->addGlobalSettings(); + $this->addActionSettings(); + } + + /** + * Add global settings + */ + public function addGlobalSettings() + { + + $apiSettings['id'] = 'mail_chimp'; + $apiSettings['label'] = 'Mailchimp'; + $apiSettings['apiSettings'] = [ + 'ninja_forms_mc_api'=>[ + 'id' => 'ninja_forms_mc_api', + 'label' => 'API Key', + 'expectedDataType' => 'userProvidedString' + ] + ]; + + $this->actionEntity->setApiSettings(ApiSettings::fromArray($apiSettings)); + } + + /** + * Add action settings used in NF Action + */ + protected function addActionSettings() + { + $actionSettings = ActionSettings::fromArray(array( + 'double_opt_in' => array( + 'name' => 'double_opt_in', + 'type' => 'toggle', + 'label' => __('Require subscribers to confirm their subscription', 'ninja-forms-mail-chimp'), + 'group' => 'advanced', + 'width' => 'full', + 'value' => 0 + ) + )); + $this->actionEntity->setActionSettings($actionSettings); + } + /** + * Initialize an ActionEntity with standard values + */ + protected function instantiateActionEntity() + { + $array = [ + 'name' => 'mailchimp', // Must match existing Mailchimp plugin action name + 'nicename' => 'Mailchimp', + 'tags' => ['newsletter'], + 'timing' => 'normal', + 'priority' => 10 + ]; + + $this->actionEntity = ActionEntity::fromArray($array); + } + + /** + * Get the constructed Action Entity + * @return ActionEntity + */ + public function getActionEntity(): ActionEntity + { + + return $this->actionEntity; + } +} diff --git a/src/Handlers/ConstructApiSubscriberFromActionSettings.php b/src/Handlers/ConstructApiSubscriberFromActionSettings.php new file mode 100644 index 0000000..0b136d0 --- /dev/null +++ b/src/Handlers/ConstructApiSubscriberFromActionSettings.php @@ -0,0 +1,296 @@ +actionSettingsDataHandler = $actionSettingsDataHandler; + $this->subscriberBuilder = $subscriberBuilder; + $this->audienceDefinition = $this->subscriberBuilder->getAudienceDefinition(); + $this->listId = $this->audienceDefinition->getListId(); + } + + public function handle(): ConstructApiSubscriberFromActionSettings + { + try { + $this->extractSubmissionData(); + return $this; + } catch (\Exception $e) { + throw $e; + } + } + /** + * Extract SubmissionData to construct Subscriber + */ + protected function extractSubmissionData() + { + $this->addEmailAddress(); + $this->addStatus(); + $this->addMergeFields(); + $this->addInterests(); + $this->addTags(); + } + + /** + * Add email address + * + * Email address key is known from Standard Subscriber Field entity + */ + protected function addEmailAddress() + { + $emailAddress = $this->actionSettingsDataHandler->getValue($this->listId . '_email_address', ''); + + $this->subscriberBuilder->setEmailAddress($emailAddress); + } + + /** + * Add status + * + * Required field; default value `subscribed` if not set + */ + protected function addStatus() + { + $doubleOptIn = $this->actionSettingsDataHandler->getValue('double_opt_in', "0"); + + if ("1" === $doubleOptIn) { + $status = 'pending'; + } else { + $status = 'subscribed'; + } + + $this->subscriberBuilder->setStatus($status); + } + + /** + * Add MergeFields in Audience Definition, add any values from Submission Data + * + */ + protected function addMergeFields() + { + $mergeFields = $this->audienceDefinition->mergeFields->getMergeVars(); + + /** @var MergeVar $mergeField */ + foreach ($mergeFields as $mergeField) { + $mergeVarTag = $mergeField->getTag(); + + $value = $this->actionSettingsDataHandler->getValue($this->listId . '_' . $mergeVarTag, null); + + $mergeVarType = $mergeField->getType(); + + if ('address' === $mergeVarType && \is_string($value)) { + $value = $this->constructAddressObject($value); + } + + if (!is_null($value) && !empty($value)) { + $this->subscriberBuilder->setMergeField($mergeVarTag, $value); + } + } + } + + /** + * Construct address array from stringed fieldmap value + * + * Allows for the following incoming constructs: + * addr1, city, state, zip + * addr1, addr2, city, state, zip + * addr1, addr2, city, state, zip, country + * + * @param string $value + * @return array + */ + protected function constructAddressObject(string $value): array + { + $return = [ + 'addr1' => '', + 'addr2' => '', + 'city' => '', + 'state' => '', + 'zip' => '', + 'country' => 'US' + ]; + + $exploded = \explode(',', $value); + $trimmed = array_map('trim', $exploded); + $count = count($exploded); + + switch ($count) { + + case 4: + $return['addr1'] = $trimmed[0]; + $return['city'] = $trimmed[1]; + $return['state'] = $trimmed[2]; + $return['zip'] = $trimmed[3]; + break; + case 5: + $return['addr1'] = $trimmed[0]; + $return['addr2'] = $trimmed[1]; + $return['city'] = $trimmed[2]; + $return['state'] = $trimmed[3]; + $return['zip'] = $trimmed[4]; + break; + case 6: + $return['addr1'] = $trimmed[0]; + $return['addr2'] = $trimmed[1]; + $return['city'] = $trimmed[2]; + $return['state'] = $trimmed[3]; + $return['zip'] = $trimmed[4]; + $return['country'] = $trimmed[5]; + } + + return $return; + } + + /** + * Add submission's interests if those interests apply to AudienceDefinition + */ + protected function addInterests() + { + $allowedInterests = array_keys($this->audienceDefinition->interests->getInterests()); + + $interestValueString = $this->actionSettingsDataHandler->getValue($this->listId . '_interests', ''); + + $submittedInterestValues = $this->extractSubmittedInterestValues($interestValueString); + + $presetInterestValues = $this->extractPresetInterestValuesForList($this->listId, $this->actionSettingsDataHandler->toArray()); + + $interestValues = $this->constructInterestValueArray($submittedInterestValues, $presetInterestValues); + + foreach ($interestValues as $value) { + if (in_array($value, $allowedInterests)) { + $this->subscriberBuilder->addInterest($value); + } + } + } + + /** + * Prefer user-submitted over action-submitted interest selection + * + * @return array + */ + protected function constructInterestValueArray(array $submittedInterestValues, array $presetInterestValues): array + { + $return = []; + + if (empty($submittedInterestValues) && !empty($presetInterestValues)) { + + $return = $presetInterestValues; + } else { + + $return = $submittedInterestValues; + } + + return $return; + } + + /** + * Extract interest values from comma delineated string + * + * @param string $interestValueString + * @return array + */ + protected function extractSubmittedInterestValues(string $interestValueString): array + { + $interestValueArray = explode(',', $interestValueString); + + $return = array_values(array_map('trim', array_filter($interestValueArray))); + + return $return; + } + + /** + * Extract preset interest values + * + * @param string $listId + * @param array $actionSettings + * @return array + */ + protected function extractPresetInterestValuesForList(string $listId, array $actionSettings): array + { + $return = []; + foreach ($actionSettings as $key => $value) { + $explodedKey = \explode('_', $key); + + if ( + $explodedKey[0] === $listId + && "1" == $value + && isset($explodedKey[2]) + ) { + $return[] = $explodedKey[2]; + } + } + + return $return; + } + + /** + * Iterate values in SubmissionData tags, add if allowed in AudienceDefinition + */ + protected function addTags() + { + /** @var Segments $tagSegments */ + // get array keys of interest in the audience definition + $tagSegments = ($this->audienceDefinition->tags->getTags()); + // get all values in comma-delineated string, removing empty values and whitespace + $values = array_map('trim', array_filter(explode(',', $this->actionSettingsDataHandler->getValue($this->listId.'_tags', '')))); + $enableNewTags =(int)$this->actionSettingsDataHandler->getValue('enable_new_tags', 0); + + if (!empty($values)) { + foreach ($values as $value) { + if ($enableNewTags===1|| $tagSegments->hasSegment($value)) { + $this->subscriberBuilder->addTag($value); + } + } + } + } + + /** + * Get constructed subscriber + * @return Subscriber + */ + public function getSubscriber(): Subscriber + { + return $this->subscriberBuilder->getSubscriber(); + } + + /** @inheritdoc */ + public function getRequestBody(): array + { + + return $this->subscriberBuilder->getRequestBody(); + } + + /** @inheritdoc */ + public function getEmailAddress(): string + { + return $this->subscriberBuilder->getEmailAddress(); + } +} diff --git a/src/Handlers/CreateAutogenerateModal.php b/src/Handlers/CreateAutogenerateModal.php new file mode 100644 index 0000000..b774afa --- /dev/null +++ b/src/Handlers/CreateAutogenerateModal.php @@ -0,0 +1,148 @@ +initializeModal(); + $this->openModalContent(); + $selectMarkup = $this->generateSelectOptionMarkup($lists); + $this->modal->appendModalContent($selectMarkup); + $this->addFormTitleInput(); + $this->closeModalContent(); + return $this->modal; + } + + /** + * Initialize standard settings + */ + public function initializeModal(): Modal + { + $this->modal = Modal::fromArray([ + 'id' => 'mailchimp-autogenerate', + 'title' => 'Mailchimp Signup Form', + 'type'=>'autogenerate', + 'templateDesc' => 'Create a fully customizable but ready-to-use Mailchimp signup form using any Audience in your Mailchimp account.', + 'modalTitle' => 'Mailchimp Signup Form' + ]); + + return $this->modal; + } + + /** + * Add opening HTML for modal content + */ + protected function openModalContent() + { + $restUrl = \rest_url(); + + $this->modal->setModalContent(''); + } +} diff --git a/src/Handlers/GetNfStructuredLists.php b/src/Handlers/GetNfStructuredLists.php new file mode 100644 index 0000000..cdc547c --- /dev/null +++ b/src/Handlers/GetNfStructuredLists.php @@ -0,0 +1,230 @@ +mailchimpApi = $mailchimpApi; + } + + /** + * Get Mailchimp lists structure for NF use + * + * @return array + */ + public function getLists(): array + { + $getLists = new GetLists($this->mailchimpApi); + + $listCollection = $getLists->requestLists()->getLists(); + + $return = $this->extractListData($listCollection); + + return $return; + } + + /** + * Extract list data as used by Ninja Forms Newsletter action + * @param array $listCollection + * @return array + */ + protected function extractListData(array $listCollection): array + { + /** @var SingleList $list */ + $nfMailchimpLists = []; + foreach ($listCollection as $list) { + // Create/update a setting with the the ID and name of the list. + Ninja_Forms()->update_setting('mail_chimp_list_' . $list->getId(), $list->getName()); + + // Build the array of lists. + $nfMailchimpLists[] = array( + 'value' => $list->getId(), + 'label' => $list->getName(), + 'groups' => $this->getListInterestCategories($list->getId()), + 'fields' => $this->getMergeVars($list->getId()) + ); + } + + return $nfMailchimpLists; + } + + + /** + * Get Interest Categories for a given list id + * @param string $listId + * @return array + */ + protected function getListInterestCategories($listId): array + { + + $getInterestCategoriesAction = new GetInterestCategories($this->mailchimpApi); + + $interestCategoriesCollection = $getInterestCategoriesAction->requestInterestCategories($listId)->getInterestCategories(); + + $categories = $this->consolidateInterestsAcrossCategories($listId, $interestCategoriesCollection); + + Ninja_Forms()->update_setting('nf_mailchimp_categories_' . $listId, $categories); + + return $categories; + } + + /** + * Consolidate interests across all interest categories, structured for NF Newsletter Action + * @param string $listId + * @param array $interestCategoriesCollection + * @return array + */ + protected function consolidateInterestsAcrossCategories(string $listId, array $interestCategoriesCollection): array + { + $interestsAllCategories = []; + // Loop over the categories we get back from the API. + foreach ($interestCategoriesCollection as $category) { + // Gets our interests lists. + $interests = $this->getInterests($listId, $category->getId()); + + // Loops over interests and builds interest list. + $addedInterests = $this->constructInterestsActionStructure($listId, $interests); + + $interestsAllCategories = array_merge($interestsAllCategories, $addedInterests); + } + return $interestsAllCategories; + } + + + /** + * Get interests for a given list id and interest category id + * @param string $listId + * @param string $interestCategoryId + * @return array + */ + protected function getInterests($listId, $interestCategoryId): array + { + + $getInterests = new GetInterests($this->mailchimpApi); + + $interestsCollection = $getInterests->requestInterests($listId, $interestCategoryId)->getInterests(); + + $interests = $this->constructInterestsArray($interestsCollection); + return $interests; + } + + /** + * Return indexed array of name/id pairs for interests collection + * @param array $interestsCollection + * @return array + */ + protected function constructInterestsArray(array $interestsCollection): array + { + $interests = []; + foreach ($interestsCollection as $interest) { + // Build our array. + $interests[] = array( + 'name' => $interest->getName(), + 'id' => $interest->getId() + ); + } + return $interests; + } + + /** + * Construct array of interests into NF standard structure + * + * Glues the listId, interest Id, and interest name in an underscore- + * delineated structure, parsed to construct Action Settings + * @param string $listId + * @param array $interests + * @return array + */ + protected function constructInterestsActionStructure(string $listId, array $interests): array + { + $categories = []; + foreach ($interests as $interest) { + $categories[] = array( + 'value' => $listId . '_group_' . $interest['id'] . '_' . $interest['name'], + 'label' => $interest['name'], + ); + } + return $categories; + } + + /** + * Get Merge Vars for a given list id + * @param string $listId + * @return array + */ + protected function getMergeVars(string $listId): array + { + $getMergeVars = new GetMergeFields($this->mailchimpApi); + + $mergeVarsCollection = $getMergeVars->requestMergeFields($listId)->getMergeVars(); + + $mergeVars = $this->buildMergeVars($mergeVarsCollection, $listId); + + return $mergeVars; + } + + /** + * Build MergeVars array from a collection + * @param array $mergeVarsCollection + * @param string $listId + * @return array + */ + protected function buildMergeVars($mergeVarsCollection, $listId): array + { + + /** @var MergeVar $mergeVar */ + // Email field is required for all new mailing list sign ups, + // but is not pulled in through the api so we need to build it ourselves. + $mergeVars[] = array( + 'value' => $listId . '_email_address', + 'label' => 'Email' . ' (required)', + ); + + // Loop over the fields and... + foreach ($mergeVarsCollection as $mergeVar) { + // If the has required text... + if (true == $mergeVar->getRequired()) { + // ...add html to apply a required tag. + $required_text = ' (required)'; + } else { + // ...otherwise leave this variable empty. + $required_text = ''; + } + + // Build our fields array. + $mergeVars[] = array( + 'value' => $listId . '_' . $mergeVar->getTag(), + 'label' => $mergeVar->getName() . $required_text + ); + } + + // Added by SRS + // @todo: deliver this value externally - it is shared with form autogeneration + // so use a single source for better maintained code see AutogenerateForm + $mergeVars[] = array( + 'value' => $listId . '_interests', + 'label' => 'User Selected Interests' + ); + + $mergeVars[] = array( + 'value' => $listId . '_tags', + 'label' => 'Tags, comma-separated' + ); + + return $mergeVars; + } +} diff --git a/src/Handlers/MailchimpOptIn.php b/src/Handlers/MailchimpOptIn.php new file mode 100644 index 0000000..d2e7b62 --- /dev/null +++ b/src/Handlers/MailchimpOptIn.php @@ -0,0 +1,29 @@ +_nicename = __('Mailchimp Opt-In', 'ninja-forms'); + } +} diff --git a/src/Handlers/MailchimpSubscribeActionProcessHandler.php b/src/Handlers/MailchimpSubscribeActionProcessHandler.php new file mode 100644 index 0000000..df1f405 --- /dev/null +++ b/src/Handlers/MailchimpSubscribeActionProcessHandler.php @@ -0,0 +1,346 @@ +getValue('opt_in', true); + + if (!$optIn) { + return [ + 'type'=>'exited', + 'context'=>'MailchimpSubscribeActionProcessHandler_OptOut', + 'message'=>'Submission opted out' + ]; + } + + $this->structureSubmissionData($submissionData); + + $this->form = $form; + + $apiKey = $this->submissionData->getValue('apiKey'); + if (isset($this->audienceDefinitions[$this->listId])) { + $audienceDefinition = $this->audienceDefinitions[$this->listId]; + } else { + try { + $audienceDefinition = ( + new GetAudienceDefinitionData( + $this->mailchimpApiFactory->listsApi($apiKey, $this->httpClient), + (new SingleList())->setId($this->listId) + ) + )->handle(); + } catch (\Exception $exception) { + $this->response = [ + 'type'=>'error', + 'context' => 'MailchimpSubscribeActionProcessHandler_GetAudienceDefinitionData', + 'message' => $exception->getMessage(), + 'diagnostics' => '' + ] + ; + + return $this->response; + } + } + $this->addAudienceDefinition($audienceDefinition); + $this->constructSubscriber(); + $this->subscribeToList(); + + if (is_a($this->response, \Exception::class)) { + return [ + 'type' => 'error', + 'context' => 'MailchimpSubscribeActionProcessHandler_Response', + 'note' => $this->response->getMessage() + ]; + } + return $this->response; + } + + /** + * Extract processing data from form fields to return key-value pairs + * + * Some data required by submission action is contained within form + * fields. Given the form fields data upon submission, extract the + * required data to return it as key-value pairs such that it can be + * added to the submission data and processed + * @param array $data Form field process data + * @return array + */ + public function extractFormFieldProcessingData(array $data): array { + $formFieldProcessingData = []; + + $formFieldProcessingData['opt_in'] = $this->isOptIn($data['fields']); + + return $formFieldProcessingData; + } + + /** + * Return bool - if this sub has an opt-in field, is it checked? If no opt-in field, default to true + * @param array $fields + * @return bool + */ + protected function isOptIn(array $fields):bool + { + // Set true flag for later use. + $opt_in = true; + + // Loop over the fields from the form data and... + foreach ($fields as $field) { + // ...If the field type is equal to Mailchimp Opt continue. + if ('mailchimp-optin' != $field[ 'type' ]) { + continue; + } + + // ...If the field value is the field value is false change the optin flag to false. + if (! $field[ 'value' ]) { + $opt_in = false; + } + } + return $opt_in; + } + + + + /** + * Structure submission data to Mailchimp requirements + * + * @param SubmissionDataContract $submissionData + * @return SubmissionDataContract + */ + public function structureSubmissionData(SubmissionDataContract $submissionData): SubmissionDataContract + { + $this->submissionData = $submissionData; + $this->setListId(); + $this->setStatus(); + if (0 === strlen($this->listId)) { + return $this->submissionData; + } + + $apiKey = $this->getApiKey(); + $this->submissionData->addData('apiKey', $apiKey); + $this->extractListData(); + $this->extractEmailAddress(); + $this->extractPreselectedInterests(); + $this->appendUserSelectedInterests(); + $this->extractTags(); + $this->implodeTagsAndInterests(); + $this->setMergeVars(); + + return $this->submissionData; + } + + /** + * Sets listId from NF's newsletter_list value + */ + protected function setListId() + { + $listId = $this->submissionData->getValue('newsletter_list', ''); + $this->listId = $listId; + $this->submissionData->addData('listId', $this->listId); + } + + /** + * Extract all data keyed on submitted listId + */ + protected function extractListData() + { + $existing = $this->submissionData->toArray(); + + $prefix = $this->listId . '_'; + + foreach ($existing as $key => $value) { + if (0 === strpos($key, $prefix)) { + $this->listData[str_replace($prefix, '', $key)] = $value; + } + } + } + + /** + * Extract email address for selected list + */ + protected function extractEmailAddress() + { + $prefix = $this->listId . '_'; + $emailAddress = $this->submissionData->getValue($prefix.'email_address', ''); + $this->submissionData->addData('email_address', $emailAddress); + + // unset from listData + unset($this->listData['email_address']); + } + + /** + * Extract interest groups manually set in Mailchimp action + */ + protected function extractPreselectedInterests() + { + + $prefix = 'group_'; + foreach ($this->listData as $key => $value) { + if (0 === strpos($key, $prefix)) { + $exploded = explode('_', $key); + + if (isset($exploded[1]) && 1===intval($value)) { + $this->interests[] = $exploded[1]; + } + + // remove from listData after moving to interests + unset($this->listData[$key]); + } + } + } + + /** + * Append user selected interests as array of interest Ids + */ + protected function appendUserSelectedInterests(): void + { + if (!isset($this->listData['interests'])) { + return; + } + + $userSelectedInterests = explode(',', $this->listData['interests']); + + $this->interests = array_merge($this->interests, $userSelectedInterests); + + // remove from listData + unset($this->listData['interests']); + } + + /** + * Implode interests into expected comma-delimited string + */ + protected function implodeTagsAndInterests() + { + if (is_array($this->interests)) { + $this->submissionData->addData('interests', implode(',', $this->interests)); + } + if (is_array($this->tags)) { + $this->submissionData->addData('tags', implode(',', $this->tags)); + } + } + + /** + * Extract tags + * + */ + protected function extractTags(): void + { + if (!isset($this->listData['tags'])) { + return; + } + + $tagArray = explode(',', $this->listData['tags']); + + $this->tags = $tagArray; + + // remove from listData + unset($this->listData['tags']); + } + + /** + * Set merge tags; these are what's left after extracting other types + */ + protected function setMergeVars() + { + foreach ($this->listData as $key => $value) { + $this->submissionData->addData($key, $value); + unset($this->listData[$key]); + } + } + + /** + * Set status based on double opt in + * + * If double opt in set to "1", set status to pending, otherwise set to + * "subscribed" + */ + protected function setStatus() + { + + $doubleOptIn = $this->submissionData->getValue('double_opt_in', "0"); + + if ("1"=== $doubleOptIn) { + $this->submissionData->addData('status', 'pending'); + } else { + $this->submissionData->addData('status', 'subscribed'); + } + } + /** + * Get API Key from Ninja Forms settings + * @todo: Replace hardcoded with global settings entity version + */ + protected function getApiKey():string + { + $apiKey = trim(Ninja_Forms()->get_setting('ninja_forms_mc_api'), ''); + return $apiKey; + } + /** + * Return Ninja Forms $data submission after processing + * @return array + */ + public function getPostProcessData(): array + { + + return $this->response; + } +} diff --git a/src/Handlers/OutputResponseDataMetabox.php b/src/Handlers/OutputResponseDataMetabox.php new file mode 100644 index 0000000..22c4b91 --- /dev/null +++ b/src/Handlers/OutputResponseDataMetabox.php @@ -0,0 +1,112 @@ +_title = 'Mailchimp Response'; + } + + public function render_metabox($post, $metabox) + { + if (!$this->sub->get_extra_value('mailchimp')) { + $this->addNoResponseDataMarkup(); + } else { + $this->extractResponseData(); + $this->markup = "
"; + foreach ($this->responseData as $responseData) { + $this->markup .= $this->markupResponseData($responseData); + } + $this->markup.="
"; + } + echo $this->markup; + } + + /** + * Markup response data for HTML output + * @param ResponseData $responseData + * @return string + */ + protected function markupResponseData(ResponseData $responseData): string + { + + $markup = "
" . esc_html($responseData->getContext()). "
"; + $markup .= "
Result: " . $responseData->getType() . "
"; + $markup .= ('' === $responseData->getMessage()) ? '' : + "
Exception: " . esc_html($responseData->getMessage()) . "
"; + $markup .= ('' === $responseData->getDiagnostics()) ? '' : + "
Diagnostics: " . esc_html($responseData->getDiagnostics()) . "
"; + $markup .= $this->prettyPrintResponse($responseData); + $markup .= ('' === $responseData->getNote()) ? '' : + "
Notes: " . esc_html($responseData->getNote()) . "
"; + + return $markup; + } + + /** + * Return reader friendly output conditionally for know response data structures + * @param ResponseData $responseData + * @return string + */ + protected function prettyPrintResponse(ResponseData $responseData):string + { + $return = ('' === $responseData->getResponse()) ? '' : + "
RawResponse: " . esc_html($responseData->getResponse()) . "
"; + + if ('SubscribeFormActionHandler_subscribeToList'===$responseData->getContext()&& + 'success'=== $responseData->getType()) { + $subscriber = Subscriber::fromArray(json_decode($responseData->getResponse(), true)); + $return ="
Subscriber Info:
" + ."
Email:". esc_html($subscriber->email_address) ."
" + ."
Status:". esc_html($subscriber->status) ."
" + ."
List Id:". esc_html($subscriber->listId) ."
" + + ; + } + return $return; + } + /** + * Construct collection of ResponseData entities + */ + protected function extractResponseData() + { + $mailchimpSubmissionData = $this->sub->get_extra_value('mailchimp'); + if (isset($mailchimpSubmissionData['responseData']) && is_array($mailchimpSubmissionData['responseData'])) { + foreach ($mailchimpSubmissionData['responseData'] as $responseDataArray) { + $this->responseData[] = ResponseData::fromArray($responseDataArray); + } + } + } + + /** + * Add markup for no response data available + */ + protected function addNoResponseDataMarkup() + { + $markup = "
" + . "No response data available for this submission" + . "
"; + + $this->markup .= $markup; + } +} diff --git a/src/Hooks/NinjaFormsRegisterActions.php b/src/Hooks/NinjaFormsRegisterActions.php new file mode 100644 index 0000000..73d7933 --- /dev/null +++ b/src/Hooks/NinjaFormsRegisterActions.php @@ -0,0 +1,53 @@ +mailchimpApi); + + // Push our action, keyed on action key + $return[$myAction->getActionKey()] = $myAction; + + // Register your additional actions by keying an instatiated object here + + // Ensure you RETURN the array + return $return; + } + + /** + * Set the value of mailchimpApi + * + * @return NinjaFormsRegisterActions + */ + public function setMailchimpApi(MailchimpApi $mailchimpApi): NinjaFormsRegisterActions + { + $this->mailchimpApi = $mailchimpApi; + + return $this; + } +} diff --git a/src/NinjaFormsMailchimp.php b/src/NinjaFormsMailchimp.php new file mode 100644 index 0000000..b921083 --- /dev/null +++ b/src/NinjaFormsMailchimp.php @@ -0,0 +1,194 @@ +nfBridge = $nfBridge; + return $this; + } + + /** @inheritDoc */ + public function getNfBridge(): NfBridgeContract + { + return $this->nfBridge; + } + + /** @inheritDoc */ + public function getIdentifier(): string + { + return self::IDENTIFIER; + } + + /** + * Create Wordpress REST API endpoints + * + * @since 3.2.1 + * + * @uses "rest_api_init" hook. + */ + public function initApi(): void + { + $api = new CreateWordPressEndpoints('register_rest_route', self::RESTROUTE); + + //Authorization for all REST API endpoints + $authorizer = new AuthorizeRequestWithWordPressUser('manage_options'); + + //Get Autogenerate Form Endpoint + // AutogenerateFormEndpoint triggers form building and is not cached for that reason + $endpoint = new AutogenerateFormEndpoint(); + $autogenerateForm = new AutogenerateForm($this->mailchimpApi); + $endpoint->setAutogenerateForm($autogenerateForm); + $endpoint->addAuthorizer($authorizer); + $api->registerRouteWithWordPress( + $endpoint + ); + } + + /** + * Register Mailchimp Opt In Field + * + * Carryover from NF Mailchimp 3.0 version + * + * @param array $actions + * @return array $actions + */ + public function registerOptIn($actions) + { + $actions['mailchimp-optin'] = new MailchimpOptIn(); + + return $actions; + } + + /** + * Initialize submission metabox for NF core <3.6 + */ + public function setupAdmin() + { + new OutputResponseDataMetabox(); + } + + + /** + * Register the Subscribe action wtih Ninja Forms + * + * API Key is set initially, but this can be re-set dynamically + */ + public function addSubscribeAction() + { + $apiKey = \Ninja_Forms()->get_setting('ninja_forms_mc_api', ''); + + $this->mailchimpApi->setApiKey($apiKey); + + (new NinjaFormsRegisterActions()) + ->setMailchimpApi($this->mailchimpApi) + ->registerHooks(); + + // Add installtion-wide settings + (new NinjaFormsPluginSettingsGroups())->addFilter(); + (new NinjaFormsPluginSettings())->addFilter(); + } + + /** + * Craates modal with Add New form autogeneration buttons + * @param array $templates + * @return array + */ + public function registerAutogenerateModal($templates) + { + $lists = (new GetNfStructuredLists($this->mailchimpApi))->getLists(); + + if (!empty($lists)) { + $modal = (new CreateAutogenerateModal())->handle($lists); + + $templates[$modal->getId()] = $modal->toArray(); + } + + // Remove the Mailchimp ad if present + if (isset($templates['mailchimp-signup'])) { + unset($templates['mailchimp-signup']); + } + + return $templates; + } + + + /** + * Add a metabox constructor to the react.js submissions page + * + * @param array $metaboxHandlers + * @return array + */ + public function addMetabox(array $metaboxHandlers): array + { + $metaboxHandlers['mailchimp'] = 'NFMailchimp\NinjaForms\Mailchimp\Admin\SubmissionDiagnosticsMetabox'; + + return $metaboxHandlers; + } + + /** + * Set the value of mailchimpApi + * + * @return NinjaFormsMailchimp + */ + public function setMailchimpApi($mailchimpApi): NinjaFormsMailchimp + { + $this->mailchimpApi = $mailchimpApi; + return $this; + } +} diff --git a/src/deprecated/Mailchimp.php b/src/deprecated/Mailchimp.php new file mode 100644 index 0000000..735e315 --- /dev/null +++ b/src/deprecated/Mailchimp.php @@ -0,0 +1,271 @@ + "Mailchimp_ValidationError", + "ServerError_MethodUnknown" => "Mailchimp_ServerError_MethodUnknown", + "ServerError_InvalidParameters" => "Mailchimp_ServerError_InvalidParameters", + "Unknown_Exception" => "Mailchimp_Unknown_Exception", + "Request_TimedOut" => "Mailchimp_Request_TimedOut", + "Zend_Uri_Exception" => "Mailchimp_Zend_Uri_Exception", + "PDOException" => "Mailchimp_PDOException", + "Avesta_Db_Exception" => "Mailchimp_Avesta_Db_Exception", + "XML_RPC2_Exception" => "Mailchimp_XML_RPC2_Exception", + "XML_RPC2_FaultException" => "Mailchimp_XML_RPC2_FaultException", + "Too_Many_Connections" => "Mailchimp_Too_Many_Connections", + "Parse_Exception" => "Mailchimp_Parse_Exception", + "User_Unknown" => "Mailchimp_User_Unknown", + "User_Disabled" => "Mailchimp_User_Disabled", + "User_DoesNotExist" => "Mailchimp_User_DoesNotExist", + "User_NotApproved" => "Mailchimp_User_NotApproved", + "Invalid_ApiKey" => "Mailchimp_Invalid_ApiKey", + "User_UnderMaintenance" => "Mailchimp_User_UnderMaintenance", + "Invalid_AppKey" => "Mailchimp_Invalid_AppKey", + "Invalid_IP" => "Mailchimp_Invalid_IP", + "User_DoesExist" => "Mailchimp_User_DoesExist", + "User_InvalidRole" => "Mailchimp_User_InvalidRole", + "User_InvalidAction" => "Mailchimp_User_InvalidAction", + "User_MissingEmail" => "Mailchimp_User_MissingEmail", + "User_CannotSendCampaign" => "Mailchimp_User_CannotSendCampaign", + "User_MissingModuleOutbox" => "Mailchimp_User_MissingModuleOutbox", + "User_ModuleAlreadyPurchased" => "Mailchimp_User_ModuleAlreadyPurchased", + "User_ModuleNotPurchased" => "Mailchimp_User_ModuleNotPurchased", + "User_NotEnoughCredit" => "Mailchimp_User_NotEnoughCredit", + "MC_InvalidPayment" => "Mailchimp_MC_InvalidPayment", + "List_DoesNotExist" => "Mailchimp_List_DoesNotExist", + "List_InvalidInterestFieldType" => "Mailchimp_List_InvalidInterestFieldType", + "List_InvalidOption" => "Mailchimp_List_InvalidOption", + "List_InvalidUnsubMember" => "Mailchimp_List_InvalidUnsubMember", + "List_InvalidBounceMember" => "Mailchimp_List_InvalidBounceMember", + "List_AlreadySubscribed" => "Mailchimp_List_AlreadySubscribed", + "List_NotSubscribed" => "Mailchimp_List_NotSubscribed", + "List_InvalidImport" => "Mailchimp_List_InvalidImport", + "MC_PastedList_Duplicate" => "Mailchimp_MC_PastedList_Duplicate", + "MC_PastedList_InvalidImport" => "Mailchimp_MC_PastedList_InvalidImport", + "Email_AlreadySubscribed" => "Mailchimp_Email_AlreadySubscribed", + "Email_AlreadyUnsubscribed" => "Mailchimp_Email_AlreadyUnsubscribed", + "Email_NotExists" => "Mailchimp_Email_NotExists", + "Email_NotSubscribed" => "Mailchimp_Email_NotSubscribed", + "List_MergeFieldRequired" => "Mailchimp_List_MergeFieldRequired", + "List_CannotRemoveEmailMerge" => "Mailchimp_List_CannotRemoveEmailMerge", + "List_Merge_InvalidMergeID" => "Mailchimp_List_Merge_InvalidMergeID", + "List_TooManyMergeFields" => "Mailchimp_List_TooManyMergeFields", + "List_InvalidMergeField" => "Mailchimp_List_InvalidMergeField", + "List_InvalidInterestGroup" => "Mailchimp_List_InvalidInterestGroup", + "List_TooManyInterestGroups" => "Mailchimp_List_TooManyInterestGroups", + "Campaign_DoesNotExist" => "Mailchimp_Campaign_DoesNotExist", + "Campaign_StatsNotAvailable" => "Mailchimp_Campaign_StatsNotAvailable", + "Campaign_InvalidAbsplit" => "Mailchimp_Campaign_InvalidAbsplit", + "Campaign_InvalidContent" => "Mailchimp_Campaign_InvalidContent", + "Campaign_InvalidOption" => "Mailchimp_Campaign_InvalidOption", + "Campaign_InvalidStatus" => "Mailchimp_Campaign_InvalidStatus", + "Campaign_NotSaved" => "Mailchimp_Campaign_NotSaved", + "Campaign_InvalidSegment" => "Mailchimp_Campaign_InvalidSegment", + "Campaign_InvalidRss" => "Mailchimp_Campaign_InvalidRss", + "Campaign_InvalidAuto" => "Mailchimp_Campaign_InvalidAuto", + "MC_ContentImport_InvalidArchive" => "Mailchimp_MC_ContentImport_InvalidArchive", + "Campaign_BounceMissing" => "Mailchimp_Campaign_BounceMissing", + "Campaign_InvalidTemplate" => "Mailchimp_Campaign_InvalidTemplate", + "Invalid_EcommOrder" => "Mailchimp_Invalid_EcommOrder", + "Absplit_UnknownError" => "Mailchimp_Absplit_UnknownError", + "Absplit_UnknownSplitTest" => "Mailchimp_Absplit_UnknownSplitTest", + "Absplit_UnknownTestType" => "Mailchimp_Absplit_UnknownTestType", + "Absplit_UnknownWaitUnit" => "Mailchimp_Absplit_UnknownWaitUnit", + "Absplit_UnknownWinnerType" => "Mailchimp_Absplit_UnknownWinnerType", + "Absplit_WinnerNotSelected" => "Mailchimp_Absplit_WinnerNotSelected", + "Invalid_Analytics" => "Mailchimp_Invalid_Analytics", + "Invalid_DateTime" => "Mailchimp_Invalid_DateTime", + "Invalid_Email" => "Mailchimp_Invalid_Email", + "Invalid_SendType" => "Mailchimp_Invalid_SendType", + "Invalid_Template" => "Mailchimp_Invalid_Template", + "Invalid_TrackingOptions" => "Mailchimp_Invalid_TrackingOptions", + "Invalid_Options" => "Mailchimp_Invalid_Options", + "Invalid_Folder" => "Mailchimp_Invalid_Folder", + "Invalid_URL" => "Mailchimp_Invalid_URL", + "Module_Unknown" => "Mailchimp_Module_Unknown", + "MonthlyPlan_Unknown" => "Mailchimp_MonthlyPlan_Unknown", + "Order_TypeUnknown" => "Mailchimp_Order_TypeUnknown", + "Invalid_PagingLimit" => "Mailchimp_Invalid_PagingLimit", + "Invalid_PagingStart" => "Mailchimp_Invalid_PagingStart", + "Max_Size_Reached" => "Mailchimp_Max_Size_Reached", + "MC_SearchException" => "Mailchimp_MC_SearchException", + "Goal_SaveFailed" => "Mailchimp_Goal_SaveFailed", + "Conversation_DoesNotExist" => "Mailchimp_Conversation_DoesNotExist", + "Conversation_ReplySaveFailed" => "Mailchimp_Conversation_ReplySaveFailed", + "File_Not_Found_Exception" => "Mailchimp_File_Not_Found_Exception", + "Folder_Not_Found_Exception" => "Mailchimp_Folder_Not_Found_Exception", + "Folder_Exists_Exception" => "Mailchimp_Folder_Exists_Exception" + ); + + public function __construct($apikey = null, $opts = array()) + { + if (!$apikey) { + $apikey = getenv('MAILCHIMP_APIKEY'); + } + + if (!$apikey) { + $apikey = $this->readConfigs(); + } + + if (!$apikey) { + throw new Mailchimp_Error('You must provide a MailChimp API key'); + } + + $this->apikey = $apikey; + $dc = "us1"; + + if (strstr($this->apikey, "-")) { + list($key, $dc) = explode("-", $this->apikey, 2); + if (!$dc) { + $dc = "us1"; + } + } + + $this->root = str_replace('https://api', 'https://' . $dc . '.api', $this->root); + $this->root = rtrim($this->root, '/') . '/'; + + if (!isset($opts['timeout']) || !is_int($opts['timeout'])) { + $opts['timeout'] = 600; + } + if (isset($opts['debug'])) { + $this->debug = true; + } + + + $this->ch = curl_init(); + + if (! isset($opts['ssl_verifypeer'])) { + $opts['ssl_verifypeer'] = true; + } + + if (isset($opts['CURLOPT_FOLLOWLOCATION']) && $opts['CURLOPT_FOLLOWLOCATION'] === true) { + curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); + } + + curl_setopt($this->ch, CURLOPT_USERAGENT, 'MailChimp-PHP/2.0.5'); + curl_setopt($this->ch, CURLOPT_POST, true); + curl_setopt($this->ch, CURLOPT_HEADER, false); + curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($this->ch, CURLOPT_TIMEOUT, $opts['timeout']); + curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $opts['ssl_verifypeer']); + + $this->folders = new Mailchimp_Folders($this); + $this->templates = new Mailchimp_Templates($this); + $this->users = new Mailchimp_Users($this); + $this->helper = new Mailchimp_Helper($this); + $this->mobile = new Mailchimp_Mobile($this); + $this->conversations = new Mailchimp_Conversations($this); + $this->ecomm = new Mailchimp_Ecomm($this); + $this->neapolitan = new Mailchimp_Neapolitan($this); + $this->lists = new Mailchimp_Lists($this); + $this->campaigns = new Mailchimp_Campaigns($this); + $this->vip = new Mailchimp_Vip($this); + $this->reports = new Mailchimp_Reports($this); + $this->gallery = new Mailchimp_Gallery($this); + $this->goal = new Mailchimp_Goal($this); + } + + public function __destruct() + { + curl_close($this->ch); + } + + public function call($url, $params) + { + $params['apikey'] = $this->apikey; + + $params = json_encode($params); + $ch = $this->ch; + + curl_setopt($ch, CURLOPT_URL, $this->root . $url . '.json'); + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); + curl_setopt($ch, CURLOPT_POSTFIELDS, $params); + curl_setopt($ch, CURLOPT_VERBOSE, $this->debug); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + + $start = microtime(true); + $this->log('Call to ' . $this->root . $url . '.json: ' . $params); + if ($this->debug) { + $curl_buffer = fopen('php://memory', 'w+'); + curl_setopt($ch, CURLOPT_STDERR, $curl_buffer); + } + + $response_body = curl_exec($ch); + + $info = curl_getinfo($ch); + $time = microtime(true) - $start; + if ($this->debug) { + rewind($curl_buffer); + $this->log(stream_get_contents($curl_buffer)); + fclose($curl_buffer); + } + $this->log('Completed in ' . number_format($time * 1000, 2) . 'ms'); + $this->log('Got response: ' . $response_body); + + if (curl_error($ch)) { + throw new Mailchimp_HttpError("API call to $url failed: " . curl_error($ch)); + } + $result = json_decode($response_body, true); + + if (floor($info['http_code'] / 100) >= 4) { + throw $this->castError($result); + } + + return $result; + } + + public function readConfigs() + { + $paths = array('~/.mailchimp.key', '/etc/mailchimp.key'); + foreach ($paths as $path) { + if (file_exists($path)) { + $apikey = trim(file_get_contents($path)); + if ($apikey) { + return $apikey; + } + } + } + return false; + } + + public function castError($result) + { + if ($result['status'] !== 'error' || !$result['name']) { + throw new Mailchimp_Error('We received an unexpected error: ' . json_encode($result)); + } + + $class = (isset(self::$error_map[$result['name']])) ? self::$error_map[$result['name']] : 'Mailchimp_Error'; + return new $class($result['error'], $result['code']); + } + + public function log($msg) + { + if ($this->debug) { + error_log($msg); + } + } +} diff --git a/src/deprecated/Mailchimp/Campaigns.php b/src/deprecated/Mailchimp/Campaigns.php new file mode 100644 index 0000000..7ac6f19 --- /dev/null +++ b/src/deprecated/Mailchimp/Campaigns.php @@ -0,0 +1,393 @@ +master = $master; + } + + /** + * Get the content (both html and text) for a campaign either as it would appear in the campaign archive or as the raw, original content + * @param string $cid + * @param associative_array $options + * - view string optional one of "archive" (default), "preview" (like our popup-preview) or "raw" + * - email associative_array optional if provided, view is "archive" or "preview", the campaign's list still exists, and the requested record is subscribed to the list. the returned content will be populated with member data populated. a struct with one of the following keys - failing to provide anything will produce an error relating to the email address. If multiple keys are provided, the first one from the following list that we find will be used, the rest will be ignored. + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array containing all content for the campaign + * - html string The HTML content used for the campaign with merge tags intact + * - text string The Text content used for the campaign with merge tags intact + */ + public function content($cid, $options = array()) + { + $_params = array("cid" => $cid, "options" => $options); + return $this->master->call('campaigns/content', $_params); + } + + /** + * Create a new draft campaign to send. You can not have more than 32,000 campaigns in your account. + * @param string $type + * @param associative_array $options + * - list_id string the list to send this campaign to- get lists using lists/list() + * - subject string the subject line for your campaign message + * - from_email string the From: email address for your campaign message + * - from_name string the From: name for your campaign message (not an email address) + * - to_name string the To: name recipients will see (not email address) + * - template_id int optional - use this user-created template to generate the HTML content of the campaign (takes precendence over other template options) + * - gallery_template_id int optional - use a template from the public gallery to generate the HTML content of the campaign (takes precendence over base template options) + * - base_template_id int optional - use this a base/start-from-scratch template to generate the HTML content of the campaign + * - folder_id int optional - automatically file the new campaign in the folder_id passed. Get using folders/list() - note that Campaigns and Autoresponders have separate folder setups + * - tracking associative_array optional - set which recipient actions will be tracked. Click tracking can not be disabled for Free accounts. + * - opens bool whether to track opens, defaults to true + * - html_clicks bool whether to track clicks in HTML content, defaults to true + * - text_clicks bool whether to track clicks in Text content, defaults to false + * - title string optional - an internal name to use for this campaign. By default, the campaign subject will be used. + * - authenticate boolean optional - set to true to enable SenderID, DomainKeys, and DKIM authentication, defaults to false. + * - analytics associative_array optional - one or more of these keys set to the tag to use - that can be any custom text (up to 50 bytes) + * - google string for Google Analytics tracking + * - clicktale string for ClickTale tracking + * - gooal string for Goal tracking (the extra 'o' in the param name is not a typo) + * - auto_footer boolean optional Whether or not we should auto-generate the footer for your content. Mostly useful for content from URLs or Imports + * - inline_css boolean optional Whether or not css should be automatically inlined when this campaign is sent, defaults to false. + * - generate_text boolean optional Whether of not to auto-generate your Text content from the HTML content. Note that this will be ignored if the Text part of the content passed is not empty, defaults to false. + * - auto_tweet boolean optional If set, this campaign will be auto-tweeted when it is sent - defaults to false. Note that if a Twitter account isn't linked, this will be silently ignored. + * - auto_fb_post array optional If set, this campaign will be auto-posted to the page_ids contained in the array. If a Facebook account isn't linked or the account does not have permission to post to the page_ids requested, those failures will be silently ignored. + * - fb_comments boolean optional If true, the Facebook comments (and thus the archive bar will be displayed. If false, Facebook comments will not be enabled (does not imply no archive bar, see previous link). Defaults to "true". + * - timewarp boolean optional If set, this campaign must be scheduled 24 hours in advance of sending - default to false. Only valid for "regular" campaigns and "absplit" campaigns that split on schedule_time. + * - ecomm360 boolean optional If set, our Ecommerce360 tracking will be enabled for links in the campaign + * - crm_tracking array optional If set, an array of structs to enable CRM tracking for: + * - salesforce associative_array optional Enable SalesForce push back + * - campaign bool optional - if true, create a Campaign object and update it with aggregate stats + * - notes bool optional - if true, attempt to update Contact notes based on email address + * - highrise associative_array optional Enable Highrise push back + * - campaign bool optional - if true, create a Kase object and update it with aggregate stats + * - notes bool optional - if true, attempt to update Contact notes based on email address + * - capsule associative_array optional Enable Capsule push back (only notes are supported) + * - notes bool optional - if true, attempt to update Contact notes based on email address + * @param associative_array $content + * - html string for raw/pasted HTML content + * - sections associative_array when using a template instead of raw HTML, each key should be the unique mc:edit area name from the template. + * - text string for the plain-text version + * - url string to have us pull in content from a URL. Note, this will override any other content options - for lists with Email Format options, you'll need to turn on generate_text as well + * - archive string to send a Base64 encoded archive file for us to import all media from. Note, this will override any other content options - for lists with Email Format options, you'll need to turn on generate_text as well + * - archive_type string optional - only necessary for the "archive" option. Supported formats are: zip, tar.gz, tar.bz2, tar, tgz, tbz . If not included, we will default to zip + * @param associative_array $segment_opts + * @param associative_array $type_opts + * - rss associative_array For RSS Campaigns this, struct should contain: + * - url string the URL to pull RSS content from - it will be verified and must exist + * - schedule string optional one of "daily", "weekly", "monthly" - defaults to "daily" + * - schedule_hour string optional an hour between 0 and 24 - default to 4 (4am local time) - applies to all schedule types + * - schedule_weekday string optional for "weekly" only, a number specifying the day of the week to send: 0 (Sunday) - 6 (Saturday) - defaults to 1 (Monday) + * - schedule_monthday string optional for "monthly" only, a number specifying the day of the month to send (1 - 28) or "last" for the last day of a given month. Defaults to the 1st day of the month + * - days associative_array optional used for "daily" schedules only, an array of the ISO-8601 weekday numbers to send on + * - 1 bool optional Monday, defaults to true + * - 2 bool optional Tuesday, defaults to true + * - 3 bool optional Wednesday, defaults to true + * - 4 bool optional Thursday, defaults to true + * - 5 bool optional Friday, defaults to true + * - 6 bool optional Saturday, defaults to true + * - 7 bool optional Sunday, defaults to true + * - absplit associative_array For A/B Split campaigns, this struct should contain: + * - split_test string The values to segment based on. Currently, one of: "subject", "from_name", "schedule". NOTE, for "schedule", you will need to call campaigns/schedule() separately! + * - pick_winner string How the winner will be picked, one of: "opens" (by the open_rate), "clicks" (by the click rate), "manual" (you pick manually) + * - wait_units int optional the default time unit to wait before auto-selecting a winner - use "3600" for hours, "86400" for days. Defaults to 86400. + * - wait_time int optional the number of units to wait before auto-selecting a winner - defaults to 1, so if not set, a winner will be selected after 1 Day. + * - split_size int optional this is a percentage of what size the Campaign's List plus any segmentation options results in. "schedule" type forces 50%, all others default to 10% + * - from_name_a string optional sort of, required when split_test is "from_name" + * - from_name_b string optional sort of, required when split_test is "from_name" + * - from_email_a string optional sort of, required when split_test is "from_name" + * - from_email_b string optional sort of, required when split_test is "from_name" + * - subject_a string optional sort of, required when split_test is "subject" + * - subject_b string optional sort of, required when split_test is "subject" + * - auto associative_array For AutoResponder campaigns, this struct should contain: + * - offset-units string one of "hourly", "day", "week", "month", "year" - required + * - offset-time string optional, sort of - the number of units must be a number greater than 0 for signup based autoresponders, ignored for "hourly" + * - offset-dir string either "before" or "after", ignored for "hourly" + * - event string optional "signup" (default) to base this members added to a list, "date", "annual", or "birthday" to base this on merge field in the list, "campaignOpen" or "campaignClicka" to base this on any activity for a campaign, "campaignClicko" to base this on clicks on a specific URL in a campaign, "mergeChanged" to base this on a specific merge field being changed to a specific value + * - event-datemerge string optional sort of, this is required if the event is "date", "annual", "birthday", or "mergeChanged" + * - campaign_id string optional sort of, required for "campaignOpen", "campaignClicka", or "campaignClicko" + * - campaign_url string optional sort of, required for "campaignClicko" + * - schedule_hour int The hour of the day - 24 hour format in GMT - the autoresponder should be triggered, ignored for "hourly" + * - use_import_time boolean whether or not imported subscribers (ie, any non-double optin subscribers) will receive + * - days associative_array optional used for "daily" schedules only, an array of the ISO-8601 weekday numbers to send on< + * - 1 bool optional Monday, defaults to true + * - 2 bool optional Tuesday, defaults to true + * - 3 bool optional Wednesday, defaults to true + * - 4 bool optional Thursday, defaults to true + * - 5 bool optional Friday, defaults to true + * - 6 bool optional Saturday, defaults to true + * - 7 bool optional Sunday, defaults to true + * @return associative_array the new campaign's details - will return same data as single campaign from campaigns/list() + */ + public function create($type, $options, $content, $segment_opts = null, $type_opts = null) + { + $_params = array("type" => $type, "options" => $options, "content" => $content, "segment_opts" => $segment_opts, "type_opts" => $type_opts); + return $this->master->call('campaigns/create', $_params); + } + + /** + * Delete a campaign. Seriously, "poof, gone!" - be careful! Seriously, no one can undelete these. + * @param string $cid + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function delete($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/delete', $_params); + } + + /** + * Get the list of campaigns and their details matching the specified filters + * @param associative_array $filters + * - campaign_id string optional - return the campaign using a know campaign_id. Accepts multiples separated by commas when not using exact matching. + * - parent_id string optional - return the child campaigns using a known parent campaign_id. Accepts multiples separated by commas when not using exact matching. + * - list_id string optional - the list to send this campaign to - get lists using lists/list(). Accepts multiples separated by commas when not using exact matching. + * - folder_id int optional - only show campaigns from this folder id - get folders using folders/list(). Accepts multiples separated by commas when not using exact matching. + * - template_id int optional - only show campaigns using this template id - get templates using templates/list(). Accepts multiples separated by commas when not using exact matching. + * - status string optional - return campaigns of a specific status - one of "sent", "save", "paused", "schedule", "sending". Accepts multiples separated by commas when not using exact matching. + * - type string optional - return campaigns of a specific type - one of "regular", "plaintext", "absplit", "rss", "auto". Accepts multiples separated by commas when not using exact matching. + * - from_name string optional - only show campaigns that have this "From Name" + * - from_email string optional - only show campaigns that have this "Reply-to Email" + * - title string optional - only show campaigns that have this title + * - subject string optional - only show campaigns that have this subject + * - sendtime_start string optional - only show campaigns that have been sent since this date/time (in GMT) - - 24 hour format in GMT, eg "2013-12-30 20:30:00" - if this is invalid the whole call fails + * - sendtime_end string optional - only show campaigns that have been sent before this date/time (in GMT) - - 24 hour format in GMT, eg "2013-12-30 20:30:00" - if this is invalid the whole call fails + * - uses_segment boolean - whether to return just campaigns with or without segments + * - exact boolean optional - flag for whether to filter on exact values when filtering, or search within content for filter values - defaults to true. Using this disables the use of any filters that accept multiples. + * @param int $start + * @param int $limit + * @param string $sort_field + * @param string $sort_dir + * @return associative_array containing a count of all matching campaigns, the specific ones for the current page, and any errors from the filters provided + * - total int the total number of campaigns matching the filters passed in + * - data array structs for each campaign being returned + * - id string Campaign Id (used for all other campaign functions) + * - web_id int The Campaign id used in our web app, allows you to create a link directly to it + * - list_id string The List used for this campaign + * - folder_id int The Folder this campaign is in + * - template_id int The Template this campaign uses + * - content_type string How the campaign's content is put together - one of 'template', 'html', 'url' + * - title string Title of the campaign + * - type string The type of campaign this is (regular,plaintext,absplit,rss,inspection,auto) + * - create_time string Creation time for the campaign + * - send_time string Send time for the campaign - also the scheduled time for scheduled campaigns. + * - emails_sent int Number of emails email was sent to + * - status string Status of the given campaign (save,paused,schedule,sending,sent) + * - from_name string From name of the given campaign + * - from_email string Reply-to email of the given campaign + * - subject string Subject of the given campaign + * - to_name string Custom "To:" email string using merge variables + * - archive_url string Archive link for the given campaign + * - inline_css boolean Whether or not the campaign content's css was auto-inlined + * - analytics string Either "google" if enabled or "N" if disabled + * - analytics_tag string The name/tag the campaign's links were tagged with if analytics were enabled. + * - authenticate boolean Whether or not the campaign was authenticated + * - ecomm360 boolean Whether or not ecomm360 tracking was appended to links + * - auto_tweet boolean Whether or not the campaign was auto tweeted after sending + * - auto_fb_post string A comma delimited list of Facebook Profile/Page Ids the campaign was posted to after sending. If not used, blank. + * - auto_footer boolean Whether or not the auto_footer was manually turned on + * - timewarp boolean Whether or not the campaign used Timewarp + * - timewarp_schedule string The time, in GMT, that the Timewarp campaign is being sent. For A/B Split campaigns, this is blank and is instead in their schedule_a and schedule_b in the type_opts array + * - parent_id string the unique id of the parent campaign (currently only valid for rss children). Will be blank for non-rss child campaigns or parent campaign has been deleted. + * - is_child boolean true if this is an RSS child campaign. Will return true even if the parent campaign has been deleted. + * - tests_sent string tests sent + * - tests_remain int test sends remaining + * - tracking associative_array the various tracking options used + * - html_clicks boolean whether or not tracking for html clicks was enabled. + * - text_clicks boolean whether or not tracking for text clicks was enabled. + * - opens boolean whether or not opens tracking was enabled. + * - segment_text string a string marked-up with HTML explaining the segment used for the campaign in plain English + * - segment_opts array the segment used for the campaign - can be passed to campaigns/segment-test or campaigns/create() + * - saved_segment associative_array if a saved segment was used (match+conditions returned above): + * - id int the saved segment id + * - type string the saved segment type + * - name string the saved segment name + * - type_opts associative_array the type-specific options for the campaign - can be passed to campaigns/create() + * - comments_total int total number of comments left on this campaign + * - comments_unread int total number of unread comments for this campaign based on the login the apikey belongs to + * - summary associative_array if available, the basic aggregate stats returned by reports/summary + * - errors array structs of any errors found while loading lists - usually just from providing invalid list ids + * - filter string the filter that caused the failure + * - value string the filter value that caused the failure + * - code int the error code + * - error string the error message + */ + public function getList($filters = array(), $start = 0, $limit = 25, $sort_field = 'create_time', $sort_dir = 'DESC') + { + $_params = array("filters" => $filters, "start" => $start, "limit" => $limit, "sort_field" => $sort_field, "sort_dir" => $sort_dir); + return $this->master->call('campaigns/list', $_params); + } + + /** + * Pause an AutoResponder or RSS campaign from sending + * @param string $cid + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function pause($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/pause', $_params); + } + + /** + * Returns information on whether a campaign is ready to send and possible issues we may have detected with it - very similar to the confirmation step in the app. + * @param string $cid + * @return associative_array containing: + * - is_ready bool whether or not you're going to be able to send this campaign + * - items array an array of structs explaining basically what the app's confirmation step would + * - type string the item type - generally success, warning, or error + * - heading string the item's heading in the app + * - details string the item's details from the app, sans any html tags/links + */ + public function ready($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/ready', $_params); + } + + /** + * Replicate a campaign. + * @param string $cid + * @return associative_array the matching campaign's details - will return same data as single campaign from campaigns/list() + */ + public function replicate($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/replicate', $_params); + } + + /** + * Resume sending an AutoResponder or RSS campaign + * @param string $cid + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function resume($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/resume', $_params); + } + + /** + * Schedule a campaign to be sent in the future + * @param string $cid + * @param string $schedule_time + * @param string $schedule_time_b + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function schedule($cid, $schedule_time, $schedule_time_b = null) + { + $_params = array("cid" => $cid, "schedule_time" => $schedule_time, "schedule_time_b" => $schedule_time_b); + return $this->master->call('campaigns/schedule', $_params); + } + + /** + * Schedule a campaign to be sent in batches sometime in the future. Only valid for "regular" campaigns + * @param string $cid + * @param string $schedule_time + * @param int $num_batches + * @param int $stagger_mins + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function scheduleBatch($cid, $schedule_time, $num_batches = 2, $stagger_mins = 5) + { + $_params = array("cid" => $cid, "schedule_time" => $schedule_time, "num_batches" => $num_batches, "stagger_mins" => $stagger_mins); + return $this->master->call('campaigns/schedule-batch', $_params); + } + + /** + * Allows one to test their segmentation rules before creating a campaign using them. + * @param string $list_id + * @param associative_array $options + * - saved_segment_id string a saved segment id from lists/segments() - this will take precendence, otherwise the match+conditions are required. + * - match string controls whether to use AND or OR when applying your options - expects "any" (for OR) or "all" (for AND) + * - conditions array of up to 5 structs for different criteria to apply while segmenting. Each criteria row must contain 3 keys - "field", "op", and "value" - and possibly a fourth, "extra", based on these definitions: + * @return associative_array with a single entry: + * - total int The total number of subscribers matching your segmentation options + */ + public function segmentTest($list_id, $options) + { + $_params = array("list_id" => $list_id, "options" => $options); + return $this->master->call('campaigns/segment-test', $_params); + } + + /** + * Send a given campaign immediately. For RSS campaigns, this will "start" them. + * @param string $cid + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function send($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/send', $_params); + } + + /** + * Send a test of this campaign to the provided email addresses + * @param string $cid + * @param array $test_emails + * @param string $send_type + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function sendTest($cid, $test_emails = array(), $send_type = 'html') + { + $_params = array("cid" => $cid, "test_emails" => $test_emails, "send_type" => $send_type); + return $this->master->call('campaigns/send-test', $_params); + } + + /** + * Get the HTML template content sections for a campaign. Note that this will return very jagged, non-standard results based on the template +a campaign is using. You only want to use this if you want to allow editing template sections in your application. + * @param string $cid + * @return associative_array content containing all content section for the campaign - section name are dependent upon the template used and thus can't be documented + */ + public function templateContent($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/template-content', $_params); + } + + /** + * Unschedule a campaign that is scheduled to be sent in the future + * @param string $cid + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function unschedule($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('campaigns/unschedule', $_params); + } + + /** + * Update just about any setting besides type for a campaign that has not been sent. See campaigns/create() for details. +Caveats:
+ * @param string $cid + * @param string $name + * @param array $value + * @return associative_array updated campaign details and any errors + * - data associative_array the update campaign details - will return same data as single campaign from campaigns/list() + * - errors array for "options" only - structs containing: + * - code int the error code + * - message string the full error message + * - name string the parameter name that failed + */ + public function update($cid, $name, $value) + { + $_params = array("cid" => $cid, "name" => $name, "value" => $value); + return $this->master->call('campaigns/update', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Conversations.php b/src/deprecated/Mailchimp/Conversations.php new file mode 100644 index 0000000..881ca0b --- /dev/null +++ b/src/deprecated/Mailchimp/Conversations.php @@ -0,0 +1,82 @@ +master = $master; + } + + /** + * Retrieve conversation metadata, includes message data for the most recent message in the conversation + * @param string $list_id + * @param string $leid + * @param string $campaign_id + * @param int $start + * @param int $limit + * @return associative_array Conversation data and metadata + * - count int Total number of conversations, irrespective of pagination. + * - data array An array of structs representing individual conversations + * - unique_id string A string identifying this particular conversation + * - message_count int The total number of messages in this conversation + * - campaign_id string The unique identifier of the campaign this conversation is associated with + * - list_id string The unique identifier of the list this conversation is associated with + * - unread_messages int The number of messages in this conversation which have not yet been read. + * - from_label string A label representing the sender of this message. + * - from_email string The email address of the sender of this message. + * - subject string The subject of the message. + * - timestamp string Date the message was either sent or received. + * - last_message associative_array The most recent message in the conversation + * - from_label string A label representing the sender of this message. + * - from_email string The email address of the sender of this message. + * - subject string The subject of the message. + * - message string The plain-text content of the message. + * - read boolean Whether or not this message has been marked as read. + * - timestamp string Date the message was either sent or received. + */ + public function getList($list_id = null, $leid = null, $campaign_id = null, $start = 0, $limit = 25) + { + $_params = array("list_id" => $list_id, "leid" => $leid, "campaign_id" => $campaign_id, "start" => $start, "limit" => $limit); + return $this->master->call('conversations/list', $_params); + } + + /** + * Retrieve conversation messages + * @param string $conversation_id + * @param boolean $mark_as_read + * @param int $start + * @param int $limit + * @return associative_array Message data and metadata + * - count int The number of messages in this conversation, irrespective of paging. + * - data array An array of structs representing each message in a conversation + * - from_label string A label representing the sender of this message. + * - from_email string The email address of the sender of this message. + * - subject string The subject of the message. + * - message string The plain-text content of the message. + * - read boolean Whether or not this message has been marked as read. + * - timestamp string Date the message was either sent or received. + */ + public function messages($conversation_id, $mark_as_read = false, $start = 0, $limit = 25) + { + $_params = array("conversation_id" => $conversation_id, "mark_as_read" => $mark_as_read, "start" => $start, "limit" => $limit); + return $this->master->call('conversations/messages', $_params); + } + + /** + * Retrieve conversation messages + * @param string $conversation_id + * @param string $message + * @return associative_array Message data from the created message + * - from_label string A label representing the sender of this message. + * - from_email string The email address of the sender of this message. + * - subject string The subject of the message. + * - message string The plain-text content of the message. + * - read boolean Whether or not this message has been marked as read. + * - timestamp string Date the message was either sent or received. + */ + public function reply($conversation_id, $message) + { + $_params = array("conversation_id" => $conversation_id, "message" => $message); + return $this->master->call('conversations/reply', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Ecomm.php b/src/deprecated/Mailchimp/Ecomm.php new file mode 100644 index 0000000..10071d7 --- /dev/null +++ b/src/deprecated/Mailchimp/Ecomm.php @@ -0,0 +1,88 @@ +master = $master; + } + + /** + * Import Ecommerce Order Information to be used for Segmentation. This will generally be used by ecommerce package plugins +provided by us or by 3rd part system developers. + * @param associative_array $order + * - id string the Order Id + * - campaign_id string optional the Campaign Id to track this order against (see the "mc_cid" query string variable a campaign passes) + * - email_id string optional (kind of) the Email Id of the subscriber we should attach this order to (see the "mc_eid" query string variable a campaign passes) - required if campaign_id is passed, otherwise either this or email is required. If both are provided, email_id takes precedence + * - email string optional (kind of) the Email Address we should attach this order to - either this or email_id is required. If both are provided, email_id takes precedence + * - total double The Order Total (ie, the full amount the customer ends up paying) + * - order_date string optional the date of the order - if this is not provided, we will default the date to now. Should be in the format of 2012-12-30 + * - shipping double optional the total paid for Shipping Fees + * - tax double optional the total tax paid + * - store_id string a unique id for the store sending the order in (32 bytes max) + * - store_name string optional a "nice" name for the store - typically the base web address (ie, "store.mailchimp.com"). We will automatically update this if it changes (based on store_id) + * - items array structs for each individual line item including: + * - line_num int optional the line number of the item on the order. We will generate these if they are not passed + * - product_id int the store's internal Id for the product. Lines that do no contain this will be skipped + * - sku string optional the store's internal SKU for the product. (max 30 bytes) + * - product_name string the product name for the product_id associated with this item. We will auto update these as they change (based on product_id) + * - category_id int (required) the store's internal Id for the (main) category associated with this product. Our testing has found this to be a "best guess" scenario + * - category_name string (required) the category name for the category_id this product is in. Our testing has found this to be a "best guess" scenario. Our plugins walk the category heirarchy up and send "Root - SubCat1 - SubCat4", etc. + * - qty double optional the quantity of the item ordered - defaults to 1 + * - cost double optional the cost of a single item (ie, not the extended cost of the line) - defaults to 0 + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function orderAdd($order) + { + $_params = array("order" => $order); + return $this->master->call('ecomm/order-add', $_params); + } + + /** + * Delete Ecommerce Order Information used for segmentation. This will generally be used by ecommerce package plugins +that we provide or by 3rd part system developers. + * @param string $store_id + * @param string $order_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function orderDel($store_id, $order_id) + { + $_params = array("store_id" => $store_id, "order_id" => $order_id); + return $this->master->call('ecomm/order-del', $_params); + } + + /** + * Retrieve the Ecommerce Orders for an account + * @param string $cid + * @param int $start + * @param int $limit + * @param string $since + * @return associative_array the total matching orders and the specific orders for the requested page + * - total int the total matching orders + * - data array structs for each order being returned + * - store_id string the store id generated by the plugin used to uniquely identify a store + * - store_name string the store name collected by the plugin - often the domain name + * - order_id string the internal order id the store tracked this order by + * - email string the email address that received this campaign and is associated with this order + * - order_total double the order total + * - tax_total double the total tax for the order (if collected) + * - ship_total double the shipping total for the order (if collected) + * - order_date string the date the order was tracked - from the store if possible, otherwise the GMT time we received it + * - items array structs for each line item on this order.: + * - line_num int the line number + * - product_id int the product id + * - product_name string the product name + * - product_sku string the sku for the product + * - product_category_id int the category id for the product + * - product_category_name string the category name for the product + * - qty int the quantity ordered + * - cost double the cost of the item + */ + public function orders($cid = null, $start = 0, $limit = 100, $since = null) + { + $_params = array("cid" => $cid, "start" => $start, "limit" => $limit, "since" => $since); + return $this->master->call('ecomm/orders', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Exceptions.php b/src/deprecated/Mailchimp/Exceptions.php new file mode 100644 index 0000000..ceb51fe --- /dev/null +++ b/src/deprecated/Mailchimp/Exceptions.php @@ -0,0 +1,754 @@ +master = $master; + } + + /** + * Add a new folder to file campaigns, autoresponders, or templates in + * @param string $name + * @param string $type + * @return associative_array with a single value: + * - folder_id int the folder_id of the newly created folder. + */ + public function add($name, $type) + { + $_params = array("name" => $name, "type" => $type); + return $this->master->call('folders/add', $_params); + } + + /** + * Delete a campaign, autoresponder, or template folder. Note that this will simply make whatever was in the folder appear unfiled, no other data is removed + * @param int $fid + * @param string $type + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function del($fid, $type) + { + $_params = array("fid" => $fid, "type" => $type); + return $this->master->call('folders/del', $_params); + } + + /** + * List all the folders of a certain type + * @param string $type + * @return array structs for each folder, including: + * - folder_id int Folder Id for the given folder, this can be used in the campaigns/list() function to filter on. + * - name string Name of the given folder + * - date_created string The date/time the folder was created + * - type string The type of the folders being returned, just to make sure you know. + * - cnt int number of items in the folder. + */ + public function getList($type) + { + $_params = array("type" => $type); + return $this->master->call('folders/list', $_params); + } + + /** + * Update the name of a folder for campaigns, autoresponders, or templates + * @param int $fid + * @param string $name + * @param string $type + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function update($fid, $name, $type) + { + $_params = array("fid" => $fid, "name" => $name, "type" => $type); + return $this->master->call('folders/update', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Gallery.php b/src/deprecated/Mailchimp/Gallery.php new file mode 100644 index 0000000..c39d463 --- /dev/null +++ b/src/deprecated/Mailchimp/Gallery.php @@ -0,0 +1,112 @@ +master = $master; + } + + /** + * Return a section of the image gallery + * @param associative_array $opts + * - type string optional the gallery type to return - images or files - default to images + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - sort_by string optional field to sort by - one of size, time, name - defaults to time + * - sort_dir string optional field to sort by - one of asc, desc - defaults to desc + * - search_term string optional a term to search for in names + * - folder_id int optional to return files that are in a specific folder. id returned by the list-folders call + * @return associative_array the matching gallery items + * - total int the total matching items + * - data array structs for each item included in the set, including: + * - id int the id of the file + * - name string the file name + * - time string the creation date for the item + * - size int the file size in bytes + * - full string the url to the actual item in the gallery + * - thumb string a url for a thumbnail that can be used to represent the item, generally an image thumbnail or an icon for a file type + */ + public function getList($opts = array()) + { + $_params = array("opts" => $opts); + return $this->master->call('gallery/list', $_params); + } + + /** + * Return a list of the folders available to the file gallery + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - search_term string optional a term to search for in names + * @return associative_array the matching gallery folders + * - total int the total matching folders + * - data array structs for each folder included in the set, including: + * - id int the id of the folder + * - name string the file name + * - file_count int the number of files in the folder + */ + public function listFolders($opts = array()) + { + $_params = array("opts" => $opts); + return $this->master->call('gallery/list-folders', $_params); + } + + /** + * Adds a folder to the file gallery + * @param string $name + * @return associative_array the new data for the created folder + * - data.id int the id of the new folder + */ + public function addFolder($name) + { + $_params = array("name" => $name); + return $this->master->call('gallery/add-folder', $_params); + } + + /** + * Remove a folder + * @param int $folder_id + * @return boolean true/false for success/failure + */ + public function removeFolder($folder_id) + { + $_params = array("folder_id" => $folder_id); + return $this->master->call('gallery/remove-folder', $_params); + } + + /** + * Add a file to a folder + * @param int $file_id + * @param int $folder_id + * @return boolean true/false for success/failure + */ + public function addFileToFolder($file_id, $folder_id) + { + $_params = array("file_id" => $file_id, "folder_id" => $folder_id); + return $this->master->call('gallery/add-file-to-folder', $_params); + } + + /** + * Remove a file from a folder + * @param int $file_id + * @param int $folder_id + * @return boolean true/false for success/failure + */ + public function removeFileFromFolder($file_id, $folder_id) + { + $_params = array("file_id" => $file_id, "folder_id" => $folder_id); + return $this->master->call('gallery/remove-file-from-folder', $_params); + } + + /** + * Remove all files from a folder (Note that the files are not deleted, they are only removed from the folder) + * @param int $folder_id + * @return boolean true/false for success/failure + */ + public function removeAllFilesFromFolder($folder_id) + { + $_params = array("folder_id" => $folder_id); + return $this->master->call('gallery/remove-all-files-from-folder', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Goal.php b/src/deprecated/Mailchimp/Goal.php new file mode 100644 index 0000000..0af6e3d --- /dev/null +++ b/src/deprecated/Mailchimp/Goal.php @@ -0,0 +1,50 @@ +master = $master; + } + + /** + * Retrieve goal event data for a particular list member. Note: only unique events are returned. If a user triggers +a particular event multiple times, you will still only receive one entry for that event. + * @param string $list_id + * @param associative_array $email + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @param int $start + * @param int $limit + * @return associative_array Event data and metadata + * - data array An array of goal data structs for the specified list member in the following format + * - event string The URL or name of the event that was triggered + * - last_visited_at string A timestamp in the format 'YYYY-MM-DD HH:MM:SS' that represents the last time this event was seen. + * - total int The total number of events that match your criteria. + */ + public function events($list_id, $email, $start = 0, $limit = 25) + { + $_params = array("list_id" => $list_id, "email" => $email, "start" => $start, "limit" => $limit); + return $this->master->call('goal/events', $_params); + } + + /** + * This allows programmatically trigger goal event collection without the use of front-end code. + * @param string $list_id + * @param associative_array $email + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @param string $campaign_id + * @param string $event + * @return associative_array Event data for the submitted event + * - event string The URL or name of the event that was triggered + * - last_visited_at string A timestamp in the format 'YYYY-MM-DD HH:MM:SS' that represents the last time this event was seen. + */ + public function recordEvent($list_id, $email, $campaign_id, $event) + { + $_params = array("list_id" => $list_id, "email" => $email, "campaign_id" => $campaign_id, "event" => $event); + return $this->master->call('goal/record-event', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Helper.php b/src/deprecated/Mailchimp/Helper.php new file mode 100644 index 0000000..d1c06c3 --- /dev/null +++ b/src/deprecated/Mailchimp/Helper.php @@ -0,0 +1,246 @@ +master = $master; + } + + /** + * Retrieve lots of account information including payments made, plan info, some account stats, installed modules, +contact info, and more. No private information like Credit Card numbers is available. + * @param array $exclude + * @return associative_array containing the details for the account tied to this API Key + * - username string The company name associated with the account + * - user_id string The Account user unique id (for building some links) + * - is_trial bool Whether the Account is in Trial mode (can only send campaigns to less than 100 emails) + * - is_approved bool Whether the Account has been approved for purchases + * - has_activated bool Whether the Account has been activated + * - timezone string The timezone for the Account - default is "US/Eastern" + * - plan_type string Plan Type - "monthly", "payasyougo", or "free" + * - plan_low int only for Monthly plans - the lower tier for list size + * - plan_high int only for Monthly plans - the upper tier for list size + * - plan_start_date string only for Monthly plans - the start date for a monthly plan + * - emails_left int only for Free and Pay-as-you-go plans emails credits left for the account + * - pending_monthly bool Whether the account is finishing Pay As You Go credits before switching to a Monthly plan + * - first_payment string date of first payment + * - last_payment string date of most recent payment + * - times_logged_in int total number of times the account has been logged into via the web + * - last_login string date/time of last login via the web + * - affiliate_link string Monkey Rewards link for our Affiliate program + * - industry string the user's selected industry + * - contact associative_array Contact details for the account + * - fname string First Name + * - lname string Last Name + * - email string Email Address + * - company string Company Name + * - address1 string Address Line 1 + * - address2 string Address Line 2 + * - city string City + * - state string State or Province + * - zip string Zip or Postal Code + * - country string Country name + * - url string Website URL + * - phone string Phone number + * - fax string Fax number + * - modules array a struct for each addon module installed in the account + * - id string An internal module id + * - name string The module name + * - added string The date the module was added + * - data associative_array Any extra data associated with this module as key=>value pairs + * - orders array a struct for each order for the account + * - order_id int The order id + * - type string The order type - either "monthly" or "credits" + * - amount double The order amount + * - date string The order date + * - credits_used double The total credits used + * - rewards associative_array Rewards details for the account including credits & inspections earned, number of referrals, referral details, and rewards used + * - referrals_this_month int the total number of referrals this month + * - notify_on string whether or not we notify the user when rewards are earned + * - notify_email string the email address address used for rewards notifications + * - credits associative_array Email credits earned: + * - this_month int credits earned this month + * - total_earned int credits earned all time + * - remaining int credits remaining + * - inspections associative_array Inbox Inspections earned: + * - this_month int credits earned this month + * - total_earned int credits earned all time + * - remaining int credits remaining + * - referrals array a struct for each referral, including: + * - name string the name of the account + * - email string the email address associated with the account + * - signup_date string the signup date for the account + * - type string the source for the referral + * - applied array a struct for each applied rewards, including: + * - value int the number of credits user + * - date string the date applied + * - order_id int the order number credits were applied to + * - order_desc string the order description + * - integrations array a struct for each connected integrations that can be used with campaigns, including: + * - id int an internal id for the integration + * - name string the integration name + * - list_id string either "_any_" when globally accessible or the list id it's valid for use against + * - user_id string if applicable, the user id for the integrated system + * - account string if applicable, the user/account name for the integrated system + * - profiles array For Facebook, users/page that can be posted to. + * - id string the user or page id + * - name string the user or page name + * - is_page bool whether this is a user or a page + */ + public function accountDetails($exclude = array()) + { + $_params = array("exclude" => $exclude); + return $this->master->call('helper/account-details', $_params); + } + + /** + * Retrieve minimal data for all Campaigns a member was sent + * @param associative_array $email + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @param associative_array $options + * - list_id string optional A list_id to limit the campaigns to + * @return array an array of structs containing campaign data for each matching campaign (ordered by send time ascending), including: + * - id string the campaign unique id + * - title string the campaign's title + * - subject string the campaign's subject + * - send_time string the time the campaign was sent + * - type string the campaign type + */ + public function campaignsForEmail($email, $options = null) + { + $_params = array("email" => $email, "options" => $options); + return $this->master->call('helper/campaigns-for-email', $_params); + } + + /** + * Return the current Chimp Chatter messages for an account. + * @return array An array of structs containing data for each chatter message + * - message string The chatter message + * - type string The type of the message - one of lists:new-subscriber, lists:unsubscribes, lists:profile-updates, campaigns:facebook-likes, campaigns:facebook-comments, campaigns:forward-to-friend, lists:imports, or campaigns:inbox-inspections + * - url string a url into the web app that the message could link to, if applicable + * - list_id string the list_id a message relates to, if applicable. Deleted lists will return -DELETED- + * - campaign_id string the list_id a message relates to, if applicable. Deleted campaigns will return -DELETED- + * - update_time string The date/time the message was last updated + */ + public function chimpChatter() + { + $_params = array(); + return $this->master->call('helper/chimp-chatter', $_params); + } + + /** + * Have HTML content auto-converted to a text-only format. You can send: plain HTML, an existing Campaign Id, or an existing Template Id. Note that this will not save anything to or update any of your lists, campaigns, or templates. +It's also not just Lynx and is very fine tuned for our template layouts - your mileage may vary. + * @param string $type + * @param associative_array $content + * - html string optional a single string value, + * - cid string a valid Campaign Id + * - user_template_id string the id of a user template + * - base_template_id string the id of a built in base/basic template + * - gallery_template_id string the id of a built in gallery template + * - url string a valid & public URL to pull html content from + * @return associative_array the content pass in converted to text. + * - text string the converted html + */ + public function generateText($type, $content) + { + $_params = array("type" => $type, "content" => $content); + return $this->master->call('helper/generate-text', $_params); + } + + /** + * Send your HTML content to have the CSS inlined and optionally remove the original styles. + * @param string $html + * @param bool $strip_css + * @return associative_array with a "html" key + * - html string Your HTML content with all CSS inlined, just like if we sent it. + */ + public function inlineCss($html, $strip_css = false) + { + $_params = array("html" => $html, "strip_css" => $strip_css); + return $this->master->call('helper/inline-css', $_params); + } + + /** + * Retrieve minimal List data for all lists a member is subscribed to. + * @param associative_array $email + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return array An array of structs with info on the list_id the member is subscribed to. + * - id string the list unique id + * - web_id int the id referenced in web interface urls + * - name string the list name + */ + public function listsForEmail($email) + { + $_params = array("email" => $email); + return $this->master->call('helper/lists-for-email', $_params); + } + + /** + * "Ping" the MailChimp API - a simple method you can call that will return a constant value as long as everything is good. Note +than unlike most all of our methods, we don't throw an Exception if we are having issues. You will simply receive a different +string back that will explain our view on what is going on. + * @return associative_array a with a "msg" key + * - msg string containing "Everything's Chimpy!" if everything is chimpy, otherwise returns an error message + */ + public function ping() + { + $_params = array(); + return $this->master->call('helper/ping', $_params); + } + + /** + * Search all campaigns for the specified query terms + * @param string $query + * @param int $offset + * @param string $snip_start + * @param string $snip_end + * @return associative_array containing the total matches and current results + * - total int total campaigns matching + * - results array matching campaigns and snippets + * - snippet string the matching snippet for the campaign + * - campaign associative_array the matching campaign's details - will return same data as single campaign from campaigns/list() + */ + public function searchCampaigns($query, $offset = 0, $snip_start = null, $snip_end = null) + { + $_params = array("query" => $query, "offset" => $offset, "snip_start" => $snip_start, "snip_end" => $snip_end); + return $this->master->call('helper/search-campaigns', $_params); + } + + /** + * Search account wide or on a specific list using the specified query terms + * @param string $query + * @param string $id + * @param int $offset + * @return associative_array An array of both exact matches and partial matches over a full search + * - exact_matches associative_array containing the exact email address matches and current results + * - total int total members matching + * - members array each entry will be struct matching the data format for a single member as returned by lists/member-info() + * - full_search associative_array containing the total matches and current results + * - total int total members matching + * - members array each entry will be struct matching the data format for a single member as returned by lists/member-info() + */ + public function searchMembers($query, $id = null, $offset = 0) + { + $_params = array("query" => $query, "id" => $id, "offset" => $offset); + return $this->master->call('helper/search-members', $_params); + } + + /** + * Retrieve all domain verification records for an account + * @return array structs for each domain verification has been attempted for + * - domain string the verified domain + * - status string the status of the verification - either "verified" or "pending" + * - email string the email address used for verification - "pre-existing" if we automatically backfilled it at some point + */ + public function verifiedDomains() + { + $_params = array(); + return $this->master->call('helper/verified-domains', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Lists.php b/src/deprecated/Mailchimp/Lists.php new file mode 100644 index 0000000..4349e9f --- /dev/null +++ b/src/deprecated/Mailchimp/Lists.php @@ -0,0 +1,944 @@ +master = $master; + } + + /** + * Get all email addresses that complained about a campaign sent to a list + * @param string $id + * @param int $start + * @param int $limit + * @param string $since + * @return associative_array the total of all reports and the specific reports reports this page + * - total int the total number of matching abuse reports + * - data array structs for the actual data for each reports, including: + * - date string date+time the abuse report was received and processed + * - email string the email address that reported abuse + * - campaign_id string the unique id for the campaign that report was made against + * - type string an internal type generally specifying the originating mail provider - may not be useful outside of filling report views + */ + public function abuseReports($id, $start = 0, $limit = 500, $since = null) + { + $_params = array("id" => $id, "start" => $start, "limit" => $limit, "since" => $since); + return $this->master->call('lists/abuse-reports', $_params); + } + + /** + * Access up to the previous 180 days of daily detailed aggregated activity stats for a given list. Does not include AutoResponder activity. + * @param string $id + * @return array of structs containing daily values, each containing: + */ + public function activity($id) + { + $_params = array("id" => $id); + return $this->master->call('lists/activity', $_params); + } + + /** + * Subscribe a batch of email addresses to a list at once. If you are using a serialized version of the API, we strongly suggest that you +only run this method as a POST request, and not a GET request. Maximum batch sizes vary based on the amount of data in each record, +though you should cap them at 5k - 10k records, depending on your experience. These calls are also long, so be sure you increase your timeout values. + * @param string $id + * @param array $batch + * - email associative_array a struct with one of the following keys - failing to provide anything will produce an error relating to the email address. Provide multiples and we'll use the first we see in this same order. + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * - email_type string for the email type option (html or text) + * - merge_vars associative_array data for the various list specific and special merge vars documented in lists/subscribe + * @param boolean $double_optin + * @param boolean $update_existing + * @param boolean $replace_interests + * @return associative_array struct of result counts and associated data + * - add_count int Number of email addresses that were successfully added + * - adds array array of structs for each add + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - update_count int Number of email addresses that were successfully updated + * - updates array array of structs for each update + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - error_count int Number of email addresses that failed during addition/updating + * - errors array array of error structs including: + * - email string whatever was passed in the batch record's email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - code int the error code + * - error string the full error message + * - row associative_array the row from the batch that caused the error + */ + public function batchSubscribe($id, $batch, $double_optin = true, $update_existing = false, $replace_interests = true) + { + $_params = array("id" => $id, "batch" => $batch, "double_optin" => $double_optin, "update_existing" => $update_existing, "replace_interests" => $replace_interests); + return $this->master->call('lists/batch-subscribe', $_params); + } + + /** + * Unsubscribe a batch of email addresses from a list + * @param string $id + * @param array $batch + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @param boolean $delete_member + * @param boolean $send_goodbye + * @param boolean $send_notify + * @return array Array of structs containing results and any errors that occurred + * - success_count int Number of email addresses that were successfully removed + * - error_count int Number of email addresses that failed during addition/updating + * - errors array array of error structs including: + * - email string whatever was passed in the batch record's email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - code int the error code + * - error string the full error message + */ + public function batchUnsubscribe($id, $batch, $delete_member = false, $send_goodbye = true, $send_notify = false) + { + $_params = array("id" => $id, "batch" => $batch, "delete_member" => $delete_member, "send_goodbye" => $send_goodbye, "send_notify" => $send_notify); + return $this->master->call('lists/batch-unsubscribe', $_params); + } + + /** + * Retrieve the clients that the list's subscribers have been tagged as being used based on user agents seen. Made possible by user-agent-string.info + * @param string $id + * @return associative_array the desktop and mobile user agents in use on the list + * - desktop associative_array desktop user agents and percentages + * - penetration double the percent of desktop clients in use + * - clients array array of structs for each client including: + * - client string the common name for the client + * - icon string a url to an image representing this client + * - percent string percent of list using the client + * - members string total members using the client + * - mobile associative_array mobile user agents and percentages + * - penetration double the percent of mobile clients in use + * - clients array array of structs for each client including: + * - client string the common name for the client + * - icon string a url to an image representing this client + * - percent string percent of list using the client + * - members string total members using the client + */ + public function clients($id) + { + $_params = array("id" => $id); + return $this->master->call('lists/clients', $_params); + } + + /** + * Access the Growth History by Month in aggregate or for a given list. + * @param string $id + * @return array array of structs containing months and growth data + * - month string The Year and Month in question using YYYY-MM format + * - existing int number of existing subscribers to start the month + * - imports int number of subscribers imported during the month + * - optins int number of subscribers who opted-in during the month + */ + public function growthHistory($id = null) + { + $_params = array("id" => $id); + return $this->master->call('lists/growth-history', $_params); + } + + /** + * Get the list of interest groupings for a given list, including the label, form information, and included groups for each + * @param string $id + * @param bool $counts + * @return array array of structs of the interest groupings for the list + * - id int The id for the Grouping + * - name string Name for the Interest groups + * - form_field string Gives the type of interest group: checkbox,radio,select + * - groups array Array structs of the grouping options (interest groups) including: + * - bit string the bit value - not really anything to be done with this + * - name string the name of the group + * - display_order string the display order of the group, if set + * - subscribers int total number of subscribers who have this group if "counts" is true. otherwise empty + */ + public function interestGroupings($id, $counts = false) + { + $_params = array("id" => $id, "counts" => $counts); + return $this->master->call('lists/interest-groupings', $_params); + } + + /** + * Add a single Interest Group - if interest groups for the List are not yet enabled, adding the first +group will automatically turn them on. + * @param string $id + * @param string $group_name + * @param int $grouping_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function interestGroupAdd($id, $group_name, $grouping_id = null) + { + $_params = array("id" => $id, "group_name" => $group_name, "grouping_id" => $grouping_id); + return $this->master->call('lists/interest-group-add', $_params); + } + + /** + * Delete a single Interest Group - if the last group for a list is deleted, this will also turn groups for the list off. + * @param string $id + * @param string $group_name + * @param int $grouping_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function interestGroupDel($id, $group_name, $grouping_id = null) + { + $_params = array("id" => $id, "group_name" => $group_name, "grouping_id" => $grouping_id); + return $this->master->call('lists/interest-group-del', $_params); + } + + /** + * Change the name of an Interest Group + * @param string $id + * @param string $old_name + * @param string $new_name + * @param int $grouping_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function interestGroupUpdate($id, $old_name, $new_name, $grouping_id = null) + { + $_params = array("id" => $id, "old_name" => $old_name, "new_name" => $new_name, "grouping_id" => $grouping_id); + return $this->master->call('lists/interest-group-update', $_params); + } + + /** + * Add a new Interest Grouping - if interest groups for the List are not yet enabled, adding the first +grouping will automatically turn them on. + * @param string $id + * @param string $name + * @param string $type + * @param array $groups + * @return associative_array with a single entry: + * - id int the new grouping id if the request succeeds, otherwise an error will be thrown + */ + public function interestGroupingAdd($id, $name, $type, $groups) + { + $_params = array("id" => $id, "name" => $name, "type" => $type, "groups" => $groups); + return $this->master->call('lists/interest-grouping-add', $_params); + } + + /** + * Delete an existing Interest Grouping - this will permanently delete all contained interest groups and will remove those selections from all list members + * @param int $grouping_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function interestGroupingDel($grouping_id) + { + $_params = array("grouping_id" => $grouping_id); + return $this->master->call('lists/interest-grouping-del', $_params); + } + + /** + * Update an existing Interest Grouping + * @param int $grouping_id + * @param string $name + * @param string $value + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function interestGroupingUpdate($grouping_id, $name, $value) + { + $_params = array("grouping_id" => $grouping_id, "name" => $name, "value" => $value); + return $this->master->call('lists/interest-grouping-update', $_params); + } + + /** + * Retrieve the locations (countries) that the list's subscribers have been tagged to based on geocoding their IP address + * @param string $id + * @return array array of locations + * - country string the country name + * - cc string the ISO 3166 2 digit country code + * - percent double the percent of subscribers in the country + * - total double the total number of subscribers in the country + */ + public function locations($id) + { + $_params = array("id" => $id); + return $this->master->call('lists/locations', $_params); + } + + /** + * Get the most recent 100 activities for particular list members (open, click, bounce, unsub, abuse, sent to, etc.) + * @param string $id + * @param array $emails + * - email string an email address - for new subscribers obviously this should be used + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array of data and success/error counts + * - success_count int the number of subscribers successfully found on the list + * - error_count int the number of subscribers who were not found on the list + * - errors array array of error structs including: + * - email string whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - error string the error message + * - code string the error code + * - data array an array of structs where each activity record has: + * - email string whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - activity array an array of structs containing the activity, including: + * - action string The action name, one of: open, click, bounce, unsub, abuse, sent, queued, ecomm, mandrill_send, mandrill_hard_bounce, mandrill_soft_bounce, mandrill_open, mandrill_click, mandrill_spam, mandrill_unsub, mandrill_reject + * - timestamp string The date+time of the action (GMT) + * - url string For click actions, the url clicked, otherwise this is empty + * - type string If there's extra bounce, unsub, etc data it will show up here. + * - campaign_id string The campaign id the action was related to, if it exists - otherwise empty (ie, direct unsub from list) + * - campaign_data associative_array If not deleted, the campaigns/list data for the campaign + */ + public function memberActivity($id, $emails) + { + $_params = array("id" => $id, "emails" => $emails); + return $this->master->call('lists/member-activity', $_params); + } + + /** + * Get all the information for particular members of a list + * @param string $id + * @param array $emails + * - email string an email address - for new subscribers obviously this should be used + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array of data and success/error counts + * - success_count int the number of subscribers successfully found on the list + * - error_count int the number of subscribers who were not found on the list + * - errors array array of error structs including: + * - email associative_array whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - error string the error message + * - data array array of structs for each valid list member + * - id string The unique id (euid) for this email address on an account + * - email string The email address associated with this record + * - email_type string The type of emails this customer asked to get: html or text + * - merges associative_array a struct containing a key for each merge tags and the data for those tags for this email address, plus: + * - GROUPINGS array if Interest groupings are enabled, this will exist with structs for each grouping: + * - id int the grouping id + * - name string the interest group name + * - groups array structs for each group in the grouping + * - name string the group name + * - interested bool whether the member has this group selected + * - status string The subscription status for this email address, either pending, subscribed, unsubscribed, or cleaned + * - ip_signup string IP Address this address signed up from. This may be blank if single optin is used. + * - timestamp_signup string The date+time the double optin was initiated. This may be blank if single optin is used. + * - ip_opt string IP Address this address opted in from. + * - timestamp_opt string The date+time the optin completed + * - member_rating int the rating of the subscriber. This will be 1 - 5 as described here + * - campaign_id string If the user is unsubscribed and they unsubscribed from a specific campaign, that campaign_id will be listed, otherwise this is not returned. + * - lists array An array of structs for the other lists this member belongs to + * - id string the list id + * - status string the members status on that list + * - timestamp string The date+time this email address entered it's current status + * - info_changed string The last time this record was changed. If the record is old enough, this may be blank. + * - web_id int The Member id used in our web app, allows you to create a link directly to it + * - leid int The Member id used in our web app, allows you to create a link directly to it + * - list_id string The list id the for the member record being returned + * - list_name string The list name the for the member record being returned + * - language string if set/detected, a language code from here + * - is_gmonkey bool Whether the member is a Golden Monkey or not. + * - geo associative_array the geographic information if we have it. including: + * - latitude string the latitude + * - longitude string the longitude + * - gmtoff string GMT offset + * - dstoff string GMT offset during daylight savings (if DST not observered, will be same as gmtoff) + * - timezone string the timezone we've place them in + * - cc string 2 digit ISO-3166 country code + * - region string generally state, province, or similar + * - clients associative_array the client we've tracked the address as using with two keys: + * - name string the common name of the client + * - icon_url string a url representing a path to an icon representing this client + * - static_segments array structs for each static segments the member is a part of including: + * - id int the segment id + * - name string the name given to the segment + * - added string the date the member was added + * - notes array structs for each note entered for this member. For each note: + * - id int the note id + * - note string the text entered + * - created string the date the note was created + * - updated string the date the note was last updated + * - created_by_name string the name of the user who created the note. This can change as users update their profile. + */ + public function memberInfo($id, $emails) + { + $_params = array("id" => $id, "emails" => $emails); + return $this->master->call('lists/member-info', $_params); + } + + /** + * Get all of the list members for a list that are of a particular status and potentially matching a segment. This will cause locking, so don't run multiples at once. Are you trying to get a dump including lots of merge +data or specific members of a list? If so, checkout the List Export API + * @param string $id + * @param string $status + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - sort_field string optional the data field to sort by - mergeX (1-30), your custom merge tags, "email", "rating","last_update_time", or "optin_time" - invalid fields will be ignored + * - sort_dir string optional the direct - ASC or DESC. defaults to ASC (case insensitive) + * - segment associative_array a properly formatted segment that works with campaigns/segment-test + * @return associative_array of the total records matched and limited list member data for this page + * - total int the total matching records + * - data array structs for each member as returned by member-info + */ + public function members($id, $status = 'subscribed', $opts = array()) + { + $_params = array("id" => $id, "status" => $status, "opts" => $opts); + return $this->master->call('lists/members', $_params); + } + + /** + * Add a new merge tag to a given list + * @param string $id + * @param string $tag + * @param string $name + * @param associative_array $options + * - field_type string optional one of: text, number, radio, dropdown, date, address, phone, url, imageurl, zip, birthday - defaults to text + * - req boolean optional indicates whether the field is required - defaults to false + * - public boolean optional indicates whether the field is displayed in public - defaults to true + * - show boolean optional indicates whether the field is displayed in the app's list member view - defaults to true + * - order int The order this merge tag should be displayed in - this will cause existing values to be reset so this fits + * - default_value string optional the default value for the field. See lists/subscribe() for formatting info. Defaults to blank - max 255 bytes + * - helptext string optional the help text to be used with some newer forms. Defaults to blank - max 255 bytes + * - choices array optional kind of - an array of strings to use as the choices for radio and dropdown type fields + * - dateformat string optional only valid for birthday and date fields. For birthday type, must be "MM/DD" (default) or "DD/MM". For date type, must be "MM/DD/YYYY" (default) or "DD/MM/YYYY". Any other values will be converted to the default. + * - phoneformat string optional "US" is the default - any other value will cause them to be unformatted (international) + * - defaultcountry string optional the ISO 3166 2 digit character code for the default country. Defaults to "US". Anything unrecognized will be converted to the default. + * @return associative_array the full data for the new merge var, just like merge-vars returns + * - name string Name/description of the merge field + * - req bool Denotes whether the field is required (true) or not (false) + * - field_type string The "data type" of this merge var. One of: email, text, number, radio, dropdown, date, address, phone, url, imageurl + * - public bool Whether or not this field is visible to list subscribers + * - show bool Whether the field is displayed in thelist dashboard + * - order string The order this field displays in on forms + * - default string The default value for this field + * - helptext string The helptext for this field + * - size string The width of the field to be used + * - tag string The merge tag that's used for forms and lists/subscribe() and lists/update-member() + * - choices array the options available for radio and dropdown field types + * - id int an unchanging id for the merge var + */ + public function mergeVarAdd($id, $tag, $name, $options = array()) + { + $_params = array("id" => $id, "tag" => $tag, "name" => $name, "options" => $options); + return $this->master->call('lists/merge-var-add', $_params); + } + + /** + * Delete a merge tag from a given list and all its members. Seriously - the data is removed from all members as well! +Note that on large lists this method may seem a bit slower than calls you typically make. + * @param string $id + * @param string $tag + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function mergeVarDel($id, $tag) + { + $_params = array("id" => $id, "tag" => $tag); + return $this->master->call('lists/merge-var-del', $_params); + } + + /** + * Completely resets all data stored in a merge var on a list. All data is removed and this action can not be undone. + * @param string $id + * @param string $tag + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function mergeVarReset($id, $tag) + { + $_params = array("id" => $id, "tag" => $tag); + return $this->master->call('lists/merge-var-reset', $_params); + } + + /** + * Sets a particular merge var to the specified value for every list member. Only merge var ids 1 - 30 may be modified this way. This is generally a dirty method +unless you're fixing data since you should probably be using default_values and/or conditional content. as with lists/merge-var-reset(), this can not be undone. + * @param string $id + * @param string $tag + * @param string $value + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function mergeVarSet($id, $tag, $value) + { + $_params = array("id" => $id, "tag" => $tag, "value" => $value); + return $this->master->call('lists/merge-var-set', $_params); + } + + /** + * Update most parameters for a merge tag on a given list. You cannot currently change the merge type + * @param string $id + * @param string $tag + * @param associative_array $options + * @return associative_array the full data for the new merge var, just like merge-vars returns + * - name string Name/description of the merge field + * - req bool Denotes whether the field is required (true) or not (false) + * - field_type string The "data type" of this merge var. One of: email, text, number, radio, dropdown, date, address, phone, url, imageurl + * - public bool Whether or not this field is visible to list subscribers + * - show bool Whether the field is displayed in thelist dashboard + * - order string The order this field to displays in on forms + * - default string The default value for this field + * - helptext string The helptext for this field + * - size string The width of the field to be used + * - tag string The merge tag that's used for forms and lists/subscribe() and lists/update-member() + * - choices array the options available for radio and dropdown field types + * - id int an unchanging id for the merge var + */ + public function mergeVarUpdate($id, $tag, $options) + { + $_params = array("id" => $id, "tag" => $tag, "options" => $options); + return $this->master->call('lists/merge-var-update', $_params); + } + + /** + * Get the list of merge tags for a given list, including their name, tag, and required setting + * @param array $id + * @return associative_array of data and success/error counts + * - success_count int the number of subscribers successfully found on the list + * - error_count int the number of subscribers who were not found on the list + * - data array of structs for the merge tags on each list + * - id string the list id + * - name string the list name + * - merge_vars array of structs for each merge var + * - name string Name of the merge field + * - req bool Denotes whether the field is required (true) or not (false) + * - field_type string The "data type" of this merge var. One of the options accepted by field_type in lists/merge-var-add + * - public bool Whether or not this field is visible to list subscribers + * - show bool Whether the list owner has this field displayed on their list dashboard + * - order string The order the list owner has set this field to display in + * - default string The default value the list owner has set for this field + * - helptext string The helptext for this field + * - size string The width of the field to be used + * - tag string The merge tag that's used for forms and lists/subscribe() and listUpdateMember() + * - choices array For radio and dropdown field types, an array of the options available + * - id int an unchanging id for the merge var + * - errors array of error structs + * - id string the passed list id that failed + * - code int the resulting error code + * - msg string the resulting error message + */ + public function mergeVars($id) + { + $_params = array("id" => $id); + return $this->master->call('lists/merge-vars', $_params); + } + + /** + * Retrieve all of Segments for a list. + * @param string $id + * @param string $type + * @return associative_array with 2 keys: + * - static array of structs with data for each segment + * - id int the id of the segment + * - name string the name for the segment + * - created_date string the date+time the segment was created + * - last_update string the date+time the segment was last updated (add or del) + * - last_reset string the date+time the segment was last reset (ie had all members cleared from it) + * - saved array of structs with data for each segment + * - id int the id of the segment + * - name string the name for the segment + * - segment_opts string same match+conditions struct typically used + * - segment_text string a textual description of the segment match/conditions + * - created_date string the date+time the segment was created + * - last_update string the date+time the segment was last updated (add or del) + */ + public function segments($id, $type = null) + { + $_params = array("id" => $id, "type" => $type); + return $this->master->call('lists/segments', $_params); + } + + /** + * Save a segment against a list for later use. There is no limit to the number of segments which can be saved. Static Segments are not tied +to any merge data, interest groups, etc. They essentially allow you to configure an unlimited number of custom segments which will have standard performance. +When using proper segments, Static Segments are one of the available options for segmentation just as if you used a merge var (and they can be used with other segmentation +options), though performance may degrade at that point. Saved Segments (called "auto-updating" in the app) are essentially just the match+conditions typically +used. + * @param string $id + * @param associative_array $opts + * - type string either "static" or "saved" + * - name string a unique name per list for the segment - 100 byte maximum length, anything longer will throw an error + * - segment_opts associative_array for "saved" only, the standard segment match+conditions, just like campaigns/segment-test + * - match string "any" or "all" + * - conditions array structs for each condition, just like campaigns/segment-test + * @return associative_array with a single entry: + * - id int the id of the new segment, otherwise an error will be thrown. + */ + public function segmentAdd($id, $opts) + { + $_params = array("id" => $id, "opts" => $opts); + return $this->master->call('lists/segment-add', $_params); + } + + /** + * Delete a segment. Note that this will, of course, remove any member affiliations with any static segments deleted + * @param string $id + * @param int $seg_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function segmentDel($id, $seg_id) + { + $_params = array("id" => $id, "seg_id" => $seg_id); + return $this->master->call('lists/segment-del', $_params); + } + + /** + * Allows one to test their segmentation rules before creating a campaign using them - this is no different from campaigns/segment-test() and will eventually replace it. +For the time being, the crazy segmenting condition documentation will continue to live over there. + * @param string $list_id + * @param associative_array $options + * @return associative_array with a single entry: + * - total int The total number of subscribers matching your segmentation options + */ + public function segmentTest($list_id, $options) + { + $_params = array("list_id" => $list_id, "options" => $options); + return $this->master->call('lists/segment-test', $_params); + } + + /** + * Update an existing segment. The list and type can not be changed. + * @param string $id + * @param int $seg_id + * @param associative_array $opts + * - name string a unique name per list for the segment - 100 byte maximum length, anything longer will throw an error + * - segment_opts associative_array for "saved" only, the standard segment match+conditions, just like campaigns/segment-test + * - match string "any" or "all" + * - conditions array structs for each condition, just like campaigns/segment-test + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function segmentUpdate($id, $seg_id, $opts) + { + $_params = array("id" => $id, "seg_id" => $seg_id, "opts" => $opts); + return $this->master->call('lists/segment-update', $_params); + } + + /** + * Save a segment against a list for later use. There is no limit to the number of segments which can be saved. Static Segments are not tied +to any merge data, interest groups, etc. They essentially allow you to configure an unlimited number of custom segments which will have standard performance. +When using proper segments, Static Segments are one of the available options for segmentation just as if you used a merge var (and they can be used with other segmentation +options), though performance may degrade at that point. + * @param string $id + * @param string $name + * @return associative_array with a single entry: + * - id int the id of the new segment, otherwise an error will be thrown. + */ + public function staticSegmentAdd($id, $name) + { + $_params = array("id" => $id, "name" => $name); + return $this->master->call('lists/static-segment-add', $_params); + } + + /** + * Delete a static segment. Note that this will, of course, remove any member affiliations with the segment + * @param string $id + * @param int $seg_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function staticSegmentDel($id, $seg_id) + { + $_params = array("id" => $id, "seg_id" => $seg_id); + return $this->master->call('lists/static-segment-del', $_params); + } + + /** + * Add list members to a static segment. It is suggested that you limit batch size to no more than 10,000 addresses per call. Email addresses must exist on the list +in order to be included - this will not subscribe them to the list! + * @param string $id + * @param int $seg_id + * @param array $batch + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array an array with the results of the operation + * - success_count int the total number of successful updates (will include members already in the segment) + * - errors array structs for each error including: + * - email string whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - code string the error code + * - error string the full error message + */ + public function staticSegmentMembersAdd($id, $seg_id, $batch) + { + $_params = array("id" => $id, "seg_id" => $seg_id, "batch" => $batch); + return $this->master->call('lists/static-segment-members-add', $_params); + } + + /** + * Remove list members from a static segment. It is suggested that you limit batch size to no more than 10,000 addresses per call. Email addresses must exist on the list +in order to be removed - this will not unsubscribe them from the list! + * @param string $id + * @param int $seg_id + * @param array $batch + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array an array with the results of the operation + * - success_count int the total number of successful removals + * - error_count int the total number of unsuccessful removals + * - errors array structs for each error including: + * - email string whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - code string the error code + * - error string the full error message + */ + public function staticSegmentMembersDel($id, $seg_id, $batch) + { + $_params = array("id" => $id, "seg_id" => $seg_id, "batch" => $batch); + return $this->master->call('lists/static-segment-members-del', $_params); + } + + /** + * Resets a static segment - removes all members from the static segment. Note: does not actually affect list member data + * @param string $id + * @param int $seg_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function staticSegmentReset($id, $seg_id) + { + $_params = array("id" => $id, "seg_id" => $seg_id); + return $this->master->call('lists/static-segment-reset', $_params); + } + + /** + * Retrieve all of the Static Segments for a list. + * @param string $id + * @param boolean $get_counts + * @param int $start + * @param int $limit + * @return array an of structs with data for each static segment + * - id int the id of the segment + * - name string the name for the segment + * - member_count int the total number of subscribed members currently in a segment + * - created_date string the date+time the segment was created + * - last_update string the date+time the segment was last updated (add or del) + * - last_reset string the date+time the segment was last reset (ie had all members cleared from it) + */ + public function staticSegments($id, $get_counts = true, $start = 0, $limit = null) + { + $_params = array("id" => $id, "get_counts" => $get_counts, "start" => $start, "limit" => $limit); + return $this->master->call('lists/static-segments', $_params); + } + + /** + * Subscribe the provided email to a list. By default this sends a confirmation email - you will not see new members until the link contained in it is clicked! + * @param string $id + * @param associative_array $email + * - email string an email address - for new subscribers obviously this should be used + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @param associative_array $merge_vars + * - new-email string set this to change the email address. This is only respected on calls using update_existing or when passed to lists/update. + * - groupings array of Interest Grouping structs. Each should contain: + * - id int Grouping "id" from lists/interest-groupings (either this or name must be present) - this id takes precedence and can't change (unlike the name) + * - name string Grouping "name" from lists/interest-groupings (either this or id must be present) + * - groups array an array of valid group names for this grouping. + * - optin_ip string Set the Opt-in IP field. Abusing this may cause your account to be suspended. We do validate this and it must not be a private IP address. + * - optin_time string Set the Opt-in Time field. Abusing this may cause your account to be suspended. We do validate this and it must be a valid date. Use - 24 hour format in GMT, eg "2013-12-30 20:30:00" to be safe. Generally, though, anything strtotime() understands we'll understand - http://us2.php.net/strtotime + * - mc_location associative_array Set the member's geographic location either by optin_ip or geo data. + * - latitude string use the specified latitude (longitude must exist for this to work) + * - longitude string use the specified longitude (latitude must exist for this to work) + * - anything string if this (or any other key exists here) we'll try to use the optin ip. NOTE - this will slow down each subscribe call a bit, especially for lat/lng pairs in sparsely populated areas. Currently our automated background processes can and will overwrite this based on opens and clicks. + * - mc_language string Set the member's language preference. Supported codes are fully case-sensitive and can be found here. + * - mc_notes array of structs for managing notes - it may contain: + * - note string the note to set. this is required unless you're deleting a note + * - id int the note id to operate on. not including this (or using an invalid id) causes a new note to be added + * - action string if the "id" key exists and is valid, an "update" key may be set to "append" (default), "prepend", "replace", or "delete" to handle how we should update existing notes. "delete", obviously, will only work with a valid "id" - passing that along with "note" and an invalid "id" is wrong and will be ignored. + * @param string $email_type + * @param bool $double_optin + * @param bool $update_existing + * @param bool $replace_interests + * @param bool $send_welcome + * @return associative_array the ids for this subscriber + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + */ + public function subscribe($id, $email, $merge_vars = null, $email_type = 'html', $double_optin = true, $update_existing = false, $replace_interests = true, $send_welcome = false) + { + $_params = array("id" => $id, "email" => $email, "merge_vars" => $merge_vars, "email_type" => $email_type, "double_optin" => $double_optin, "update_existing" => $update_existing, "replace_interests" => $replace_interests, "send_welcome" => $send_welcome); + return $this->master->call('lists/subscribe', $_params); + } + + /** + * Unsubscribe the given email address from the list + * @param string $id + * @param associative_array $email + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @param boolean $delete_member + * @param boolean $send_goodbye + * @param boolean $send_notify + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function unsubscribe($id, $email, $delete_member = false, $send_goodbye = true, $send_notify = true) + { + $_params = array("id" => $id, "email" => $email, "delete_member" => $delete_member, "send_goodbye" => $send_goodbye, "send_notify" => $send_notify); + return $this->master->call('lists/unsubscribe', $_params); + } + + /** + * Edit the email address, merge fields, and interest groups for a list member. If you are doing a batch update on lots of users, +consider using lists/batch-subscribe() with the update_existing and possible replace_interests parameter. + * @param string $id + * @param associative_array $email + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @param array $merge_vars + * @param string $email_type + * @param boolean $replace_interests + * @return associative_array the ids for this subscriber + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + */ + public function updateMember($id, $email, $merge_vars, $email_type = '', $replace_interests = true) + { + $_params = array("id" => $id, "email" => $email, "merge_vars" => $merge_vars, "email_type" => $email_type, "replace_interests" => $replace_interests); + return $this->master->call('lists/update-member', $_params); + } + + /** + * Add a new Webhook URL for the given list + * @param string $id + * @param string $url + * @param associative_array $actions + * - subscribe bool optional as subscribes occur, defaults to true + * - unsubscribe bool optional as subscribes occur, defaults to true + * - profile bool optional as profile updates occur, defaults to true + * - cleaned bool optional as emails are cleaned from the list, defaults to true + * - upemail bool optional when subscribers change their email address, defaults to true + * - campaign bool option when a campaign is sent or canceled, defaults to true + * @param associative_array $sources + * - user bool optional user/subscriber initiated actions, defaults to true + * - admin bool optional admin actions in our web app, defaults to true + * - api bool optional actions that happen via API calls, defaults to false + * @return associative_array with a single entry: + * - id int the id of the new webhook, otherwise an error will be thrown. + */ + public function webhookAdd($id, $url, $actions = array(), $sources = array()) + { + $_params = array("id" => $id, "url" => $url, "actions" => $actions, "sources" => $sources); + return $this->master->call('lists/webhook-add', $_params); + } + + /** + * Delete an existing Webhook URL from a given list + * @param string $id + * @param string $url + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function webhookDel($id, $url) + { + $_params = array("id" => $id, "url" => $url); + return $this->master->call('lists/webhook-del', $_params); + } + + /** + * Return the Webhooks configured for the given list + * @param string $id + * @return array of structs for each webhook + * - url string the URL for this Webhook + * - actions associative_array the possible actions and whether they are enabled + * - subscribe bool triggered when subscribes happen + * - unsubscribe bool triggered when unsubscribes happen + * - profile bool triggered when profile updates happen + * - cleaned bool triggered when a subscriber is cleaned (bounced) from a list + * - upemail bool triggered when a subscriber's email address is changed + * - campaign bool triggered when a campaign is sent or canceled + * - sources associative_array the possible sources and whether they are enabled + * - user bool whether user/subscriber triggered actions are returned + * - admin bool whether admin (manual, in-app) triggered actions are returned + * - api bool whether api triggered actions are returned + */ + public function webhooks($id) + { + $_params = array("id" => $id); + return $this->master->call('lists/webhooks', $_params); + } + + /** + * Retrieve all of the lists defined for your user account + * @param associative_array $filters + * - list_id string optional - return a single list using a known list_id. Accepts multiples separated by commas when not using exact matching + * - list_name string optional - only lists that match this name + * - from_name string optional - only lists that have a default from name matching this + * - from_email string optional - only lists that have a default from email matching this + * - from_subject string optional - only lists that have a default from email matching this + * - created_before string optional - only show lists that were created before this date+time - 24 hour format in GMT, eg "2013-12-30 20:30:00" + * - created_after string optional - only show lists that were created since this date+time - 24 hour format in GMT, eg "2013-12-30 20:30:00" + * - exact boolean optional - flag for whether to filter on exact values when filtering, or search within content for filter values - defaults to true + * @param int $start + * @param int $limit + * @param string $sort_field + * @param string $sort_dir + * @return associative_array result of the operation including valid data and any errors + * - total int the total number of lists which matched the provided filters + * - data array structs for the lists which matched the provided filters, including the following + * - id string The list id for this list. This will be used for all other list management functions. + * - web_id int The list id used in our web app, allows you to create a link directly to it + * - name string The name of the list. + * - date_created string The date that this list was created. + * - email_type_option boolean Whether or not the List supports multiple formats for emails or just HTML + * - use_awesomebar boolean Whether or not campaigns for this list use the Awesome Bar in archives by default + * - default_from_name string Default From Name for campaigns using this list + * - default_from_email string Default From Email for campaigns using this list + * - default_subject string Default Subject Line for campaigns using this list + * - default_language string Default Language for this list's forms + * - list_rating double An auto-generated activity score for the list (0 - 5) + * - subscribe_url_short string Our eepurl shortened version of this list's subscribe form (will not change) + * - subscribe_url_long string The full version of this list's subscribe form (host will vary) + * - beamer_address string The email address to use for this list's Email Beamer + * - visibility string Whether this list is Public (pub) or Private (prv). Used internally for projects like Wavelength + * - stats associative_array various stats and counts for the list - many of these are cached for at least 5 minutes + * - member_count double The number of active members in the given list. + * - unsubscribe_count double The number of members who have unsubscribed from the given list. + * - cleaned_count double The number of members cleaned from the given list. + * - member_count_since_send double The number of active members in the given list since the last campaign was sent + * - unsubscribe_count_since_send double The number of members who have unsubscribed from the given list since the last campaign was sent + * - cleaned_count_since_send double The number of members cleaned from the given list since the last campaign was sent + * - campaign_count double The number of campaigns in any status that use this list + * - grouping_count double The number of Interest Groupings for this list + * - group_count double The number of Interest Groups (regardless of grouping) for this list + * - merge_var_count double The number of merge vars for this list (not including the required EMAIL one) + * - avg_sub_rate double the average number of subscribe per month for the list (empty value if we haven't calculated this yet) + * - avg_unsub_rate double the average number of unsubscribe per month for the list (empty value if we haven't calculated this yet) + * - target_sub_rate double the target subscription rate for the list to keep it growing (empty value if we haven't calculated this yet) + * - open_rate double the average open rate per campaign for the list (empty value if we haven't calculated this yet) + * - click_rate double the average click rate per campaign for the list (empty value if we haven't calculated this yet) + * - modules array Any list specific modules installed for this list (example is SocialPro) + * - errors array structs of any errors found while loading lists - usually just from providing invalid list ids + * - param string the data that caused the failure + * - code int the error code + * - error string the error message + */ + public function getList($filters = array(), $start = 0, $limit = 25, $sort_field = 'created', $sort_dir = 'DESC') + { + $_params = array("filters" => $filters, "start" => $start, "limit" => $limit, "sort_field" => $sort_field, "sort_dir" => $sort_dir); + return $this->master->call('lists/list', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Mobile.php b/src/deprecated/Mailchimp/Mobile.php new file mode 100644 index 0000000..923d733 --- /dev/null +++ b/src/deprecated/Mailchimp/Mobile.php @@ -0,0 +1,9 @@ +master = $master; + } +} diff --git a/src/deprecated/Mailchimp/Neapolitan.php b/src/deprecated/Mailchimp/Neapolitan.php new file mode 100644 index 0000000..8154b58 --- /dev/null +++ b/src/deprecated/Mailchimp/Neapolitan.php @@ -0,0 +1,9 @@ +master = $master; + } +} diff --git a/src/deprecated/Mailchimp/Reports.php b/src/deprecated/Mailchimp/Reports.php new file mode 100644 index 0000000..50910da --- /dev/null +++ b/src/deprecated/Mailchimp/Reports.php @@ -0,0 +1,476 @@ +master = $master; + } + + /** + * Get all email addresses that complained about a given campaign + * @param string $cid + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - since string optional pull only messages since this time - 24 hour format in GMT, eg "2013-12-30 20:30:00" + * @return associative_array abuse report data for this campaign + * - total int the total reports matched + * - data array a struct for the each report, including: + * - date string date/time the abuse report was received and processed + * - member string the email address that reported abuse - will only contain email if the list or member has been removed + * - type string an internal type generally specifying the originating mail provider - may not be useful outside of filling report views + */ + public function abuse($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/abuse', $_params); + } + + /** + * Retrieve the text presented in our app for how a campaign performed and any advice we may have for you - best +suited for display in customized reports pages. Note: some messages will contain HTML - clean tags as necessary + * @param string $cid + * @return array of structs for advice on the campaign's performance, each containing: + * - msg string the advice message + * - type string the "type" of the message. one of: negative, positive, or neutral + */ + public function advice($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('reports/advice', $_params); + } + + /** + * Retrieve the most recent full bounce message for a specific email address on the given campaign. +Messages over 30 days old are subject to being removed + * @param string $cid + * @param associative_array $email + * - email string an email address - this is recommended for this method + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array the full bounce message for this email+campaign along with some extra data. + * - date string date the bounce was received and processed + * - member associative_array the member record as returned by lists/member-info() + * - message string the entire bounce message received + */ + public function bounceMessage($cid, $email) + { + $_params = array("cid" => $cid, "email" => $email); + return $this->master->call('reports/bounce-message', $_params); + } + + /** + * Retrieve the full bounce messages for the given campaign. Note that this can return very large amounts +of data depending on how large the campaign was and how much cruft the bounce provider returned. Also, +messages over 30 days old are subject to being removed + * @param string $cid + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - since string optional pull only messages since this time - 24 hour format in GMT, eg "2013-12-30 20:30:00" + * @return associative_array data for the full bounce messages for this campaign + * - total int that total number of bounce messages for the campaign + * - data array structs containing the data for this page + * - date string date the bounce was received and processed + * - member associative_array the member record as returned by lists/member-info() + * - message string the entire bounce message received + */ + public function bounceMessages($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/bounce-messages', $_params); + } + + /** + * Return the list of email addresses that clicked on a given url, and how many times they clicked + * @param string $cid + * @param int $tid + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - sort_field string optional the data to sort by - "clicked" (order clicks occurred, default) or "clicks" (total number of opens). Invalid fields will fall back on the default. + * - sort_dir string optional the direct - ASC or DESC. defaults to ASC (case insensitive) + * @return associative_array containing the total records matched and the specific records for this page + * - total int the total number of records matched + * - data array structs for each email addresses that click the requested url + * - member associative_array the member record as returned by lists/member-info() + * - clicks int Total number of times the URL was clicked by this email address + */ + public function clickDetail($cid, $tid, $opts = array()) + { + $_params = array("cid" => $cid, "tid" => $tid, "opts" => $opts); + return $this->master->call('reports/click-detail', $_params); + } + + /** + * The urls tracked and their click counts for a given campaign. + * @param string $cid + * @return associative_array including: + * - total array structs for each url tracked for the full campaign + * - url string the url being tracked - urls are tracked individually, so duplicates can exist with vastly different stats + * - clicks int Number of times the specific link was clicked + * - clicks_percent double the percentage of total clicks "clicks" represents + * - unique int Number of unique people who clicked on the specific link + * - unique_percent double the percentage of unique clicks "unique" represents + * - tid int the tracking id used in campaign links - used primarily for reports/click-activity. also can be used to order urls by the order they appeared in the campaign to recreate our heat map. + * - a array if this was an absplit campaign, stat structs for the a group + * - url string the url being tracked - urls are tracked individually, so duplicates can exist with vastly different stats + * - clicks int Number of times the specific link was clicked + * - clicks_percent double the percentage of total clicks "clicks" represents + * - unique int Number of unique people who clicked on the specific link + * - unique_percent double the percentage of unique clicks "unique" represents + * - tid int the tracking id used in campaign links - used primarily for reports/click-activity. also can be used to order urls by the order they appeared in the campaign to recreate our heat map. + * - b array if this was an absplit campaign, stat structs for the b group + * - url string the url being tracked - urls are tracked individually, so duplicates can exist with vastly different stats + * - clicks int Number of times the specific link was clicked + * - clicks_percent double the percentage of total clicks "clicks" represents + * - unique int Number of unique people who clicked on the specific link + * - unique_percent double the percentage of unique clicks "unique" represents + * - tid int the tracking id used in campaign links - used primarily for reports/click-activity. also can be used to order urls by the order they appeared in the campaign to recreate our heat map. + */ + public function clicks($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('reports/clicks', $_params); + } + + /** + * Retrieve the Ecommerce Orders tracked by ecomm/order-add() + * @param string $cid + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - since string optional pull only messages since this time - 24 hour format in GMT, eg "2013-12-30 20:30:00" + * @return associative_array the total matching orders and the specific orders for the requested page + * - total int the total matching orders + * - data array structs for the actual data for each order being returned + * - store_id string the store id generated by the plugin used to uniquely identify a store + * - store_name string the store name collected by the plugin - often the domain name + * - order_id string the internal order id the store tracked this order by + * - member associative_array the member record as returned by lists/member-info() that received this campaign and is associated with this order + * - order_total double the order total + * - tax_total double the total tax for the order (if collected) + * - ship_total double the shipping total for the order (if collected) + * - order_date string the date the order was tracked - from the store if possible, otherwise the GMT time we received it + * - lines array structs containing details of the order: + * - line_num int the line number assigned to this line + * - product_id int the product id assigned to this item + * - product_name string the product name + * - product_sku string the sku for the product + * - product_category_id int the id for the product category + * - product_category_name string the product category name + * - qty double optional the quantity of the item ordered - defaults to 1 + * - cost double optional the cost of a single item (ie, not the extended cost of the line) - defaults to 0 + */ + public function ecommOrders($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/ecomm-orders', $_params); + } + + /** + * Retrieve the eepurl stats from the web/Twitter mentions for this campaign + * @param string $cid + * @return associative_array containing tweets, retweets, clicks, and referrer related to using the campaign's eepurl + * - twitter associative_array various Twitter related stats + * - tweets int Total number of tweets seen + * - first_tweet string date and time of the first tweet seen + * - last_tweet string date and time of the last tweet seen + * - retweets int Total number of retweets seen + * - first_retweet string date and time of the first retweet seen + * - last_retweet string date and time of the last retweet seen + * - statuses array an structs for statuses recorded including: + * - status string the text of the tweet/update + * - screen_name string the screen name as recorded when first seen + * - status_id string the status id of the tweet (they are really unsigned 64 bit ints) + * - datetime string the date/time of the tweet + * - is_retweet bool whether or not this was a retweet + * - clicks associative_array stats related to click-throughs on the eepurl + * - clicks int Total number of clicks seen + * - first_click string date and time of the first click seen + * - last_click string date and time of the first click seen + * - locations array structs for geographic locations including: + * - country string the country name the click was tracked to + * - region string the region in the country the click was tracked to (if available) + * - referrers array structs for referrers, including + * - referrer string the referrer, truncated to 100 bytes + * - clicks int Total number of clicks seen from this referrer + * - first_click string date and time of the first click seen from this referrer + * - last_click string date and time of the first click seen from this referrer + */ + public function eepurl($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('reports/eepurl', $_params); + } + + /** + * Given a campaign and email address, return the entire click and open history with timestamps, ordered by time. If you need to dump the full activity for a campaign +and/or get incremental results, you should use the campaignSubscriberActivity Export API method, +not this, especially for large campaigns. + * @param string $cid + * @param array $emails + * - email string an email address + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array of data and success/error counts + * - success_count int the number of subscribers successfully found on the list + * - error_count int the number of subscribers who were not found on the list + * - errors array array of error structs including: + * - email string whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - msg string the error message + * - data array an array of structs where each activity record has: + * - email string whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - member associative_array the member record as returned by lists/member-info() + * - activity array an array of structs containing the activity, including: + * - action string The action name - either open or click + * - timestamp string The date/time of the action (GMT) + * - url string For click actions, the url clicked, otherwise this is empty + * - ip string The IP address the activity came from + */ + public function memberActivity($cid, $emails) + { + $_params = array("cid" => $cid, "emails" => $emails); + return $this->master->call('reports/member-activity', $_params); + } + + /** + * Retrieve the list of email addresses that did not open a given campaign + * @param string $cid + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * @return associative_array a total of all matching emails and the specific emails for this page + * - total int the total number of members who didn't open the campaign + * - data array structs for each campaign member matching as returned by lists/member-info() + */ + public function notOpened($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/not-opened', $_params); + } + + /** + * Retrieve the list of email addresses that opened a given campaign with how many times they opened + * @param string $cid + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * - sort_field string optional the data to sort by - "opened" (order opens occurred, default) or "opens" (total number of opens). Invalid fields will fall back on the default. + * - sort_dir string optional the direct - ASC or DESC. defaults to ASC (case insensitive) + * @return associative_array containing the total records matched and the specific records for this page + * - total int the total number of records matched + * - data array structs for the actual opens data, including: + * - member associative_array the member record as returned by lists/member-info() + * - opens int Total number of times the campaign was opened by this email address + */ + public function opened($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/opened', $_params); + } + + /** + * Get the top 5 performing email domains for this campaign. Users wanting more than 5 should use campaign reports/member-activity() +or campaignEmailStatsAIMAll() and generate any additional stats they require. + * @param string $cid + * @return array domains structs for each email domains and their associated stats + * - domain string Domain name or special "Other" to roll-up stats past 5 domains + * - total_sent int Total Email across all domains - this will be the same in every row + * - emails int Number of emails sent to this domain + * - bounces int Number of bounces + * - opens int Number of opens + * - clicks int Number of clicks + * - unsubs int Number of unsubs + * - delivered int Number of deliveries + * - emails_pct int Percentage of emails that went to this domain (whole number) + * - bounces_pct int Percentage of bounces from this domain (whole number) + * - opens_pct int Percentage of opens from this domain (whole number) + * - clicks_pct int Percentage of clicks from this domain (whole number) + * - unsubs_pct int Percentage of unsubs from this domain (whole number) + */ + public function domainPerformance($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('reports/domain-performance', $_params); + } + + /** + * Retrieve the countries/regions and number of opens tracked for each. Email address are not returned. + * @param string $cid + * @return array an array of country structs where opens occurred + * - code string The ISO3166 2 digit country code + * - name string A version of the country name, if we have it + * - opens int The total number of opens that occurred in the country + * - regions array structs of data for each sub-region in the country + * - code string An internal code for the region. When this is blank, it indicates we know the country, but not the region + * - name string The name of the region, if we have one. For blank "code" values, this will be "Rest of Country" + * - opens int The total number of opens that occurred in the country + */ + public function geoOpens($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('reports/geo-opens', $_params); + } + + /** + * Retrieve the Google Analytics data we've collected for this campaign. Note, requires Google Analytics Add-on to be installed and configured. + * @param string $cid + * @return array of structs for analytics we've collected for the passed campaign. + * - visits int number of visits + * - pages int number of page views + * - new_visits int new visits recorded + * - bounces int vistors who "bounced" from your site + * - time_on_site double the total time visitors spent on your sites + * - goal_conversions int number of goals converted + * - goal_value double value of conversion in dollars + * - revenue double revenue generated by campaign + * - transactions int number of transactions tracked + * - ecomm_conversions int number Ecommerce transactions tracked + * - goals array structs containing goal names and number of conversions + * - name string the name of the goal + * - conversions int the number of conversions for the goal + */ + public function googleAnalytics($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('reports/google-analytics', $_params); + } + + /** + * Get email addresses the campaign was sent to + * @param string $cid + * @param associative_array $opts + * - status string optional the status to pull - one of 'sent', 'hard' (bounce), or 'soft' (bounce). By default, all records are returned + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * @return associative_array a total of all matching emails and the specific emails for this page + * - total int the total number of members for the campaign and status + * - data array structs for each campaign member matching + * - member associative_array the member record as returned by lists/member-info() + * - status string the status of the send - one of 'sent', 'hard', 'soft' + * - absplit_group string if this was an absplit campaign, one of 'a','b', or 'winner' + * - tz_group string if this was an timewarp campaign the timezone GMT offset the member was included in + */ + public function sentTo($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/sent-to', $_params); + } + + /** + * Get the URL to a customized VIP Report for the specified campaign and optionally send an email to someone with links to it. Note subsequent calls will overwrite anything already set for the same campign (eg, the password) + * @param string $cid + * @param array $opts + * - to_email string optional - optional, comma delimited list of email addresses to share the report with - no value means an email will not be sent + * - theme_id int optional - either a global or a user-specific theme id. Currently this needs to be pulled out of either the Share Report or Cobranding web views by grabbing the "theme" attribute from the list presented. + * - css_url string optional - a link to an external CSS file to be included after our default CSS (http://vip-reports.net/css/vip.css) only if loaded via the "secure_url" - max 255 bytes + * @return associative_array details for the shared report, including: + * - title string The Title of the Campaign being shared + * - url string The URL to the shared report + * - secure_url string The URL to the shared report, including the password (good for loading in an IFRAME). For non-secure reports, this will not be returned + * - password string If secured, the password for the report, otherwise this field will not be returned + */ + public function share($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/share', $_params); + } + + /** + * Retrieve relevant aggregate campaign statistics (opens, bounces, clicks, etc.) + * @param string $cid + * @return associative_array the statistics for this campaign + * - syntax_errors int Number of email addresses in campaign that had syntactical errors. + * - hard_bounces int Number of email addresses in campaign that hard bounced. + * - soft_bounces int Number of email addresses in campaign that soft bounced. + * - unsubscribes int Number of email addresses in campaign that unsubscribed. + * - abuse_reports int Number of email addresses in campaign that reported campaign for abuse. + * - forwards int Number of times email was forwarded to a friend. + * - forwards_opens int Number of times a forwarded email was opened. + * - opens int Number of times the campaign was opened. + * - last_open string Date of the last time the email was opened. + * - unique_opens int Number of people who opened the campaign. + * - clicks int Number of times a link in the campaign was clicked. + * - unique_clicks int Number of unique recipient/click pairs for the campaign. + * - last_click string Date of the last time a link in the email was clicked. + * - users_who_clicked int Number of unique recipients who clicked on a link in the campaign. + * - emails_sent int Number of email addresses campaign was sent to. + * - unique_likes int total number of unique likes (Facebook) + * - recipient_likes int total number of recipients who liked (Facebook) the campaign + * - facebook_likes int total number of likes (Facebook) that came from Facebook + * - industry associative_array Various rates/percentages for the account's selected industry - empty otherwise. These will vary across calls, do not use them for anything important. + * - type string the selected industry + * - open_rate float industry open rate + * - click_rate float industry click rate + * - bounce_rate float industry bounce rate + * - unopen_rate float industry unopen rate + * - unsub_rate float industry unsub rate + * - abuse_rate float industry abuse rate + * - absplit associative_array If this was an absplit campaign, stats for the A and B groups will be returned - otherwise this is empty + * - bounces_a int bounces for the A group + * - bounces_b int bounces for the B group + * - forwards_a int forwards for the A group + * - forwards_b int forwards for the B group + * - abuse_reports_a int abuse reports for the A group + * - abuse_reports_b int abuse reports for the B group + * - unsubs_a int unsubs for the A group + * - unsubs_b int unsubs for the B group + * - recipients_click_a int clicks for the A group + * - recipients_click_b int clicks for the B group + * - forwards_opens_a int opened forwards for the A group + * - forwards_opens_b int opened forwards for the B group + * - opens_a int total opens for the A group + * - opens_b int total opens for the B group + * - last_open_a string date/time of last open for the A group + * - last_open_b string date/time of last open for the BG group + * - unique_opens_a int unique opens for the A group + * - unique_opens_b int unique opens for the B group + * - timewarp array If this campaign was a Timewarp campaign, an array of structs from each timezone stats exist for. Each will contain: + * - opens int opens for this timezone + * - last_open string the date/time of the last open for this timezone + * - unique_opens int the unique opens for this timezone + * - clicks int the total clicks for this timezone + * - last_click string the date/time of the last click for this timezone + * - unique_opens int the unique clicks for this timezone + * - bounces int the total bounces for this timezone + * - total int the total number of members sent to in this timezone + * - sent int the total number of members delivered to in this timezone + * - timeseries array structs for the first 24 hours of the campaign, per-hour stats: + * - timestamp string The timestemp in Y-m-d H:00:00 format + * - emails_sent int the total emails sent during the hour + * - unique_opens int unique opens seen during the hour + * - recipients_click int unique clicks seen during the hour + */ + public function summary($cid) + { + $_params = array("cid" => $cid); + return $this->master->call('reports/summary', $_params); + } + + /** + * Get all unsubscribed email addresses for a given campaign + * @param string $cid + * @param associative_array $opts + * - start int optional for large data sets, the page number to start at - defaults to 1st page of data (page 0) + * - limit int optional for large data sets, the number of results to return - defaults to 25, upper limit set at 100 + * @return associative_array a total of all unsubscribed emails and the specific members for this page + * - total int the total number of unsubscribes for the campaign + * - data array structs for the email addresses that unsubscribed + * - member string the member that unsubscribed as returned by lists/member-info() + * - reason string the reason collected for the unsubscribe. If populated, one of 'NORMAL','NOSIGNUP','INAPPROPRIATE','SPAM','OTHER' + * - reason_text string if the reason is OTHER, the text entered. + */ + public function unsubscribes($cid, $opts = array()) + { + $_params = array("cid" => $cid, "opts" => $opts); + return $this->master->call('reports/unsubscribes', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Templates.php b/src/deprecated/Mailchimp/Templates.php new file mode 100644 index 0000000..18c1ba2 --- /dev/null +++ b/src/deprecated/Mailchimp/Templates.php @@ -0,0 +1,119 @@ +master = $master; + } + + /** + * Create a new user template, NOT campaign content. These templates can then be applied while creating campaigns. + * @param string $name + * @param string $html + * @param int $folder_id + * @return associative_array with a single element: + * - template_id int the new template id, otherwise an error is thrown. + */ + public function add($name, $html, $folder_id = null) + { + $_params = array("name" => $name, "html" => $html, "folder_id" => $folder_id); + return $this->master->call('templates/add', $_params); + } + + /** + * Delete (deactivate) a user template + * @param int $template_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function del($template_id) + { + $_params = array("template_id" => $template_id); + return $this->master->call('templates/del', $_params); + } + + /** + * Pull details for a specific template to help support editing + * @param int $template_id + * @param string $type + * @return associative_array info to be used when editing + * - default_content associative_array the default content broken down into the named editable sections for the template - dependant upon template, so not documented + * - sections associative_array the valid editable section names - dependant upon template, so not documented + * - source string the full source of the template as if you exported it via our template editor + * - preview string similar to the source, but the rendered version of the source from our popup preview + */ + public function info($template_id, $type = 'user') + { + $_params = array("template_id" => $template_id, "type" => $type); + return $this->master->call('templates/info', $_params); + } + + /** + * Retrieve various templates available in the system, allowing some thing similar to our template gallery to be created. + * @param associative_array $types + * - user boolean Custom templates for this user account. Defaults to true. + * - gallery boolean Templates from our Gallery. Note that some templates that require extra configuration are withheld. (eg, the Etsy template). Defaults to false. + * - base boolean Our "start from scratch" extremely basic templates. Defaults to false. As of the 9.0 update, "base" templates are no longer available via the API because they are now all saved Drag & Drop templates. + * @param associative_array $filters + * - category string optional for Gallery templates only, limit to a specific template category + * - folder_id string user templates, limit to this folder_id + * - include_inactive boolean user templates are not deleted, only set inactive. defaults to false. + * - inactive_only boolean only include inactive user templates. defaults to false. + * - include_drag_and_drop boolean Include templates created and saved using the new Drag & Drop editor. Note: You will not be able to edit or create new drag & drop templates via this API. This is useful only for creating a new campaign based on a drag & drop template. + * @return associative_array for each type + * - user array matching user templates, if requested. + * - id int Id of the template + * - name string Name of the template + * - layout string General description of the layout of the template + * - category string The category for the template, if there is one. + * - preview_image string If we've generated it, the url of the preview image for the template. We do out best to keep these up to date, but Preview image urls are not guaranteed to be available + * - date_created string The date/time the template was created + * - active boolean whether or not the template is active and available for use. + * - edit_source boolean Whether or not you are able to edit the source of a template. + * - folder_id boolean if it's in one, the folder id + * - gallery array matching gallery templates, if requested. + * - id int Id of the template + * - name string Name of the template + * - layout string General description of the layout of the template + * - category string The category for the template, if there is one. + * - preview_image string If we've generated it, the url of the preview image for the template. We do out best to keep these up to date, but Preview image urls are not guaranteed to be available + * - date_created string The date/time the template was created + * - active boolean whether or not the template is active and available for use. + * - edit_source boolean Whether or not you are able to edit the source of a template. + * - base array matching base templates, if requested. (Will always be empty as of 9.0) + */ + public function getList($types = array(), $filters = array()) + { + $_params = array("types" => $types, "filters" => $filters); + return $this->master->call('templates/list', $_params); + } + + /** + * Undelete (reactivate) a user template + * @param int $template_id + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function undel($template_id) + { + $_params = array("template_id" => $template_id); + return $this->master->call('templates/undel', $_params); + } + + /** + * Replace the content of a user template, NOT campaign content. + * @param int $template_id + * @param associative_array $values + * - name string the name for the template - names must be unique and a max of 50 bytes + * - html string a string specifying the entire template to be created. This is NOT campaign content. They are intended to utilize our template language. + * - folder_id int the folder to put this template in - 0 or a blank values will remove it from a folder. + * @return associative_array with a single entry: + * - complete bool whether the call worked. reallistically this will always be true as errors will be thrown otherwise. + */ + public function update($template_id, $values) + { + $_params = array("template_id" => $template_id, "values" => $values); + return $this->master->call('templates/update', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Users.php b/src/deprecated/Mailchimp/Users.php new file mode 100644 index 0000000..b3650ce --- /dev/null +++ b/src/deprecated/Mailchimp/Users.php @@ -0,0 +1,111 @@ +master = $master; + } + + /** + * Invite a user to your account + * @param string $email + * @param string $role + * @param string $msg + * @return associative_array the method completion status + * - status string The status (success) of the call if it completed. Otherwise an error is thrown. + */ + public function invite($email, $role = 'viewer', $msg = '') + { + $_params = array("email" => $email, "role" => $role, "msg" => $msg); + return $this->master->call('users/invite', $_params); + } + + /** + * Resend an invite a user to your account. Note, if the same address has been invited multiple times, this will simpy re-send the most recent invite + * @param string $email + * @return associative_array the method completion status + * - status string The status (success) of the call if it completed. Otherwise an error is thrown. + */ + public function inviteResend($email) + { + $_params = array("email" => $email); + return $this->master->call('users/invite-resend', $_params); + } + + /** + * Revoke an invitation sent to a user to your account. Note, if the same address has been invited multiple times, this will simpy revoke the most recent invite + * @param string $email + * @return associative_array the method completion status + * - status string The status (success) of the call if it completed. Otherwise an error is thrown. + */ + public function inviteRevoke($email) + { + $_params = array("email" => $email); + return $this->master->call('users/invite-revoke', $_params); + } + + /** + * Retrieve the list of pending users invitations have been sent for. + * @return array structs for each invitation, including: + * - email string the email address the invitation was sent to + * - role string the role that will be assigned if they accept + * - sent_at string the time the invitation was sent. this will change if it's resent. + * - expiration string the expiration time for the invitation. this will change if it's resent. + * - msg string the welcome message included with the invitation + */ + public function invites() + { + $_params = array(); + return $this->master->call('users/invites', $_params); + } + + /** + * Revoke access for a specified login + * @param string $username + * @return associative_array the method completion status + * - status string The status (success) of the call if it completed. Otherwise an error is thrown. + */ + public function loginRevoke($username) + { + $_params = array("username" => $username); + return $this->master->call('users/login-revoke', $_params); + } + + /** + * Retrieve the list of active logins. + * @return array structs for each user, including: + * - id int the login id for this login + * - username string the username used to log in + * - name string a display name for the account - empty first/last names will return the username + * - email string the email tied to the account used for passwords resets and the ilk + * - role string the role assigned to the account + * - avatar string if available, the url for the login's avatar + * - global_user_id int the globally unique user id for the user account connected to + * - dc_unique_id string the datacenter unique id for the user account connected to, like helper/account-details + */ + public function logins() + { + $_params = array(); + return $this->master->call('users/logins', $_params); + } + + /** + * Retrieve the profile for the login owning the provided API Key + * @return associative_array the current user's details, including: + * - id int the login id for this login + * - username string the username used to log in + * - name string a display name for the account - empty first/last names will return the username + * - email string the email tied to the account used for passwords resets and the ilk + * - role string the role assigned to the account + * - avatar string if available, the url for the login's avatar + * - global_user_id int the globally unique user id for the user account connected to + * - dc_unique_id string the datacenter unique id for the user account connected to, like helper/account-details + * - account_name string The name of the account to which the API key belongs + */ + public function profile() + { + $_params = array(); + return $this->master->call('users/profile', $_params); + } +} diff --git a/src/deprecated/Mailchimp/Vip.php b/src/deprecated/Mailchimp/Vip.php new file mode 100644 index 0000000..f198a3c --- /dev/null +++ b/src/deprecated/Mailchimp/Vip.php @@ -0,0 +1,114 @@ +master = $master; + } + + /** + * Retrieve all Activity (opens/clicks) for VIPs over the past 10 days + * @return array structs for each activity recorded. + * - action string The action taken - either "open" or "click" + * - timestamp string The datetime the action occurred in GMT + * - url string IF the action is a click, the url that was clicked + * - unique_id string The campaign_id of the List the Member appears on + * - title string The campaign title + * - list_name string The name of the List the Member appears on + * - list_id string The id of the List the Member appears on + * - email string The email address of the member + * - fname string IF a FNAME merge field exists on the list, that value for the member + * - lname string IF a LNAME merge field exists on the list, that value for the member + * - member_rating int the rating of the subscriber. This will be 1 - 5 as described here + * - member_since string the datetime the member was added and/or confirmed + * - geo associative_array the geographic information if we have it. including: + * - latitude string the latitude + * - longitude string the longitude + * - gmtoff string GMT offset + * - dstoff string GMT offset during daylight savings (if DST not observered, will be same as gmtoff + * - timezone string the timezone we've place them in + * - cc string 2 digit ISO-3166 country code + * - region string generally state, province, or similar + */ + public function activity() + { + $_params = array(); + return $this->master->call('vip/activity', $_params); + } + + /** + * Add VIPs (previously called Golden Monkeys) + * @param string $id + * @param array $emails + * - email string an email address - for new subscribers obviously this should be used + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array of data and success/error counts + * - success_count int the number of successful adds + * - error_count int the number of unsuccessful adds + * - errors array array of error structs including: + * - email associative_array whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + * - code string the error code + * - error string the error message + * - data array array of structs for each member added + * - email associative_array whatever was passed in the email parameter + * - email string the email address added + * - euid string the email unique id + * - leid string the list member's truly unique id + */ + public function add($id, $emails) + { + $_params = array("id" => $id, "emails" => $emails); + return $this->master->call('vip/add', $_params); + } + + /** + * Remove VIPs - this does not affect list membership + * @param string $id + * @param array $emails + * - email string an email address - for new subscribers obviously this should be used + * - euid string the unique id for an email address (not list related) - the email "id" returned from listMemberInfo, Webhooks, Campaigns, etc. + * - leid string the list email id (previously called web_id) for a list-member-info type call. this doesn't change when the email address changes + * @return associative_array of data and success/error counts + * - success_count int the number of successful deletions + * - error_count int the number of unsuccessful deletions + * - errors array array of error structs including: + * - email associative_array whatever was passed in the email parameter + * - email string the email address + * - euid string the email unique id + * - leid string the list member's truly unique id + * - code string the error code + * - msg string the error message + * - data array array of structs for each member deleted + * - email associative_array whatever was passed in the email parameter + * - email string the email address + * - euid string the email unique id + * - leid string the list member's truly unique id + */ + public function del($id, $emails) + { + $_params = array("id" => $id, "emails" => $emails); + return $this->master->call('vip/del', $_params); + } + + /** + * Retrieve all Golden Monkey(s) for an account + * @return array structs for each Golden Monkey, including: + * - list_id string The id of the List the Member appears on + * - list_name string The name of the List the Member appears on + * - email string The email address of the member + * - fname string IF a FNAME merge field exists on the list, that value for the member + * - lname string IF a LNAME merge field exists on the list, that value for the member + * - member_rating int the rating of the subscriber. This will be 1 - 5 as described here + * - member_since string the datetime the member was added and/or confirmed + */ + public function members() + { + $_params = array(); + return $this->master->call('vip/members', $_params); + } +} diff --git a/src/deprecated/includes/class-notification-mailchimp.php b/src/deprecated/includes/class-notification-mailchimp.php new file mode 100644 index 0000000..9c743ce --- /dev/null +++ b/src/deprecated/includes/class-notification-mailchimp.php @@ -0,0 +1,220 @@ +name = __('MailChimp', 'ninja-forms-mc'); + } + + /** + * Output our edit screen + * + * @access public + * @since 1.3 + * @return void + */ + public function edit_screen($id = '') + { + + $lists = ninja_forms_mc_get_mailchimp_lists(); + + if (is_wp_error($lists) || ! is_array($lists)) { + return; + } + + $saved_id = nf_get_object_meta_value($id, 'list-id'); + ?> + + + + + + + + + + + + + + +

+ + + + + +


+ + + + + + + + $group) { ?> +

+ /> +
+ + +    /> +
+ +


+ +

+ + + + + + + + + + + + + notification($id)->get_setting('list-id'); + $groups = maybe_unserialize(Ninja_Forms()->notification($id)->get_setting('groups')); + $mapped_vars = maybe_unserialize(Ninja_Forms()->notification($id)->get_setting('merge-vars')); + $double_opt_in = Ninja_Forms()->notification($id)->get_setting('double-opt'); + $double_opt_in = ! empty($double_opt_in) && 'yes' === strtolower($double_opt_in); + $needs_opt_int = false; + $opted_in = true; + + // Check if Mail Chimp is enabled for this form + if (empty($list_id)) { + return; + } + + + // Get all the user submitted values + $all_fields = $ninja_forms_processing->get_all_fields(); + + // Look for an opt-in checkbox + foreach ($all_fields as $field_id => $value) { + $field = $ninja_forms_processing->get_field_settings($field_id); + + if ('_checkbox' !== $field['type']) { + continue; + } + + if (! empty($field['data']['nf_mc_opt_in'])) { + $opted_in = 'checked' === $all_fields[ $field_id ]; + } + } + + // Return if user did not opt in + if (! $opted_in) { + return; + } + + $subscriber = array( + 'merge_vars' => array( + 'optin_ip' => ninja_forms_get_ip() + ) + ); + + if (! empty($groups)) { + $groupings = array(); + + foreach ($groups as $group_id => $group) { + foreach ($group as $key => $g) { + // NF has a bug that adds 0 => 1 key value pair. It has to be removed since it's not a valid group + if (1 === intval($g)) { + unset($group[ $key ]); + } + } + + $groupings[] = array( + 'id' => $group_id, + 'groups' => array_values($group) + ); + } + + $subscriber['merge_vars']['groupings'] = $groupings; + } + + if (is_array($all_fields) && is_array($mapped_vars)) { //Make sure $all_fields is an array. + $mapped_vars = array_map(array( $this, 'sanitize_key' ), $mapped_vars); + + foreach ($mapped_vars as $var => $field_id) { + $subscriber['merge_vars'][ $var ] = isset($all_fields[ $field_id ]) ? $all_fields[ $field_id ] : ''; + } + + if (! empty($subscriber['merge_vars']['EMAIL'])) { + $subscriber['email'] = $subscriber['merge_vars']['EMAIL']; + } else { + // Loop through each of our submitted values and find an email + foreach ($all_fields as $field_id => $value) { + $field = $ninja_forms_processing->get_field_settings($field_id); + + if (! empty($field['data']['email']) && is_email($value)) { + $subscriber['email'] = $value; + } + } + } + + if (! empty($subscriber)) { + $success = ninja_forms_mc_subscribe_email($subscriber, $list_id, $double_opt_in); + } + } + } + + /** + * Removes field_ from field IDs + * + * @access public + * @since 1.3 + * @return int + */ + private function sanitize_key($key = '') + { + return absint(str_replace('field_', '', $key)); + } +} diff --git a/src/deprecated/includes/upgrades.php b/src/deprecated/includes/upgrades.php new file mode 100644 index 0000000..6aca37a --- /dev/null +++ b/src/deprecated/includes/upgrades.php @@ -0,0 +1,166 @@ +' . __('Ninja Forms needs to upgrade your MailChimp form settings, click %shere%s to start the upgrade.', 'ninja-forms') . '', + '', + '' + ); + } +} +add_action('admin_notices', 'ninja_forms_mailchimp_show_upgrade_notices'); + + +/** + * Upgrade handler + * + * @since 1.3 + * @return void + */ +if (!class_exists('NF_Step_Processing')) { + return false; +} +class Ninja_Forms_MC_Upgrade_13 extends NF_Step_Processing +{ + + function __construct() + { + $this->action = 'upgrade_13_mailchimp'; + + parent::__construct(); + } + + public function loading() + { + + // Get our total number of forms. + $form_count = nf_get_form_count(); + $completed_count = count(get_option('nf_mc_13_updated_forms', array())); + + if ($completed_count >= $form_count) { + return array( 'complete' => true ); + } + + // Get all our forms + $forms = ninja_forms_get_all_forms(true); + + $x = 1; + if (is_array($forms)) { + foreach ($forms as $form) { + $this->args['forms'][$x] = $form['id']; + $x++; + } + } + + if (empty($this->total_steps) || $this->total_steps <= 1) { + $this->total_steps = $form_count; + } + + $args = array( + 'total_steps' => $this->total_steps, + 'step' => 1, + ); + + $this->redirect = admin_url('admin.php?page=ninja-forms'); + + return $args; + } + + public function step() + { + + // Get our form ID + $form_id = $this->args['forms'][ $this->step ]; + + // Get a list of forms that we've already converted. + $completed_forms = get_option('nf_mc_13_updated_forms', array()); + + // Bail if we've already converted the notifications for this form. + if (in_array($form_id, $completed_forms)) { + return false; + } + + $settings = nf_get_form_settings($form_id); + + // Check if this is a MailChimp form + if (empty($settings['mailchimp_signup_form'])) { + return false; + } + + $list_id = $settings['ninja_forms_mc_list']; + $opt_in = isset($settings['ninja_forms_mc_double_opt_in']) ? 'yes' : 'no'; + + // Find email and name fields + $fields = nf_get_fields_by_form_id($form_id); + $merge_vars = array(); + + if (is_array($fields)) { + //Loop through each of our submitted values. + foreach ($fields as $field_id => $field) { + if (! empty($field['data']['email'])) { + $merge_vars['EMAIL'] = 'field_' . $field_id; + continue; + } + + if (! empty($field['data']['first_name'])) { + $merge_vars['FNAME'] = 'field_' . $field_id; + continue; + } + + if (! empty($field['data']['last_name'])) { + $merge_vars['LNAME'] = 'field_' . $field_id; + continue; + } + } + } + + $n_id = nf_insert_notification($form_id); + + // Update our notification name + Ninja_Forms()->notification($n_id)->activate(); + Ninja_Forms()->notification($n_id)->update_setting('type', 'mailchimp'); + Ninja_Forms()->notification($n_id)->update_setting('name', __('MailChimp', 'ninja-forms-mc')); + Ninja_Forms()->notification($n_id)->update_setting('list-id', $list_id); + Ninja_Forms()->notification($n_id)->update_setting('double-opt', $opt_in); + Ninja_Forms()->notification($n_id)->update_setting('merge-vars', $merge_vars); + + $completed_forms = get_option('nf_mc_13_updated_forms'); + if (! is_array($completed_forms) || empty($completed_forms)) { + $completed_forms = array( $form_id ); + } else { + $completed_forms[] = $form_id; + } + update_option('nf_mc_13_updated_forms', $completed_forms); + } + + public function complete() + { + update_option('nf_mc_13_upgrade_complete', true); + } +} + +if (is_admin()) { + $nf_mc_upgrade_13 = new Ninja_Forms_MC_Upgrade_13; +} diff --git a/src/deprecated/languages/ninja-forms-mc.mo b/src/deprecated/languages/ninja-forms-mc.mo new file mode 100644 index 0000000..e69de29 diff --git a/src/deprecated/languages/ninja-forms-mc.po b/src/deprecated/languages/ninja-forms-mc.po new file mode 100644 index 0000000..fd56ad7 --- /dev/null +++ b/src/deprecated/languages/ninja-forms-mc.po @@ -0,0 +1,96 @@ +msgid "" +msgstr "" +"Project-Id-Version: Ninja Forms - MailChimp\n" +"POT-Creation-Date: 2015-04-29 14:55-0600\n" +"PO-Revision-Date: 2015-04-29 14:55-0600\n" +"Last-Translator: Pippin Williamson \n" +"Language-Team: Pippin Williamson \n" +"Language: en\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.7.6\n" +"X-Poedit-Basepath: .\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-KeywordsList: __;_e;_x;_e;esc_attr_e\n" +"X-Poedit-SearchPath-0: ..\n" + +#: ../includes/class-notification-mailchimp.php:9 +msgid "MailChimp" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:31 +msgid "List" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:43 +msgid "Merge Vars" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:59 +msgid "Groups" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:76 +msgid "Select the groups you would like subscribers added to" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:81 +msgid "Double Opt-In" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:85 +msgid "Yes" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:86 +msgid "No" +msgstr "" + +#: ../includes/class-notification-mailchimp.php:88 +msgid "Should subscribers be required to confirm their susbcription?" +msgstr "" + +#: ../ninja-forms-mailchimp.php:90 +msgid " Mail Chimp" +msgstr "" + +#: ../ninja-forms-mailchimp.php:94 +msgid "Mail Chimp API Key" +msgstr "" + +#: ../ninja-forms-mailchimp.php:95 +msgid "" +"Enter your Mail Chimp API key. This is found in your MailChimp \"Extras\" " +"settings and looks like this: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxx" +msgstr "" + +#: ../ninja-forms-mailchimp.php:101 +msgid "Disable SSL Verification" +msgstr "" + +#: ../ninja-forms-mailchimp.php:102 +msgid "" +"If you receive an error about validating the SSL certificate, enable this " +"option" +msgstr "" + +#: ../ninja-forms-mailchimp.php:161 +msgid "The API key you have entered appears to be invalid" +msgstr "" + +#: ../ninja-forms-mailchimp.php:213 ../ninja-forms-mailchimp.php:221 +#: ../ninja-forms-mailchimp.php:308 +msgid "Error" +msgstr "" + +#: ../ninja-forms-mailchimp.php:308 +#, php-format +msgid "" +"The API key you have entered appears to be invalid. Please go back and re-" +"enter it. Error message: %s" +msgstr "" + +#: ../ninja-forms-mailchimp.php:429 +msgid "Enable Opt-In Checkbox for MailChimp" +msgstr "" diff --git a/src/deprecated/ninja-forms-mailchimp.php b/src/deprecated/ninja-forms-mailchimp.php new file mode 100644 index 0000000..fc9e0de --- /dev/null +++ b/src/deprecated/ninja-forms-mailchimp.php @@ -0,0 +1,442 @@ + +
+

+ Please contact your host: PHP cUrl is not installed. Mailchimp for Ninja Forms requires cUrl and will not function properly. ', 'ninja-forms-mailchimp'); ?> +

+
+ + 'Mail Chimp', + 'page' => 'ninja-forms-settings', + 'display_function' => '', + 'save_function' => 'ninja_forms_save_license_settings', + ); + ninja_forms_register_tab('mail_chimp', $tab_args); +} +add_action('admin_init', 'ninja_forms_mc_add_tab'); + + +/** + * PRegister the settings in the Mail Chimp Tab + * + * @since 1.0 + * @return void + */ +function ninja_forms_mc_add_plugin_settings() +{ + + if (! function_exists('ninja_forms_register_tab_metabox_options')) { + return; + } + + $mc_args = array( + 'page' => 'ninja-forms-settings', + 'tab' => 'mail_chimp', + 'slug' => 'mail_chimp', + 'title' => __(' Mail Chimp', 'ninja-forms-mc'), + 'settings' => array( + array( + 'name' => 'ninja_forms_mc_api', + 'label' => __('Mail Chimp API Key', 'ninja-forms-mc'), + 'desc' => __('Enter your Mail Chimp API key. This is found in your MailChimp "Extras" settings and looks like this: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxx', 'ninja-forms-mc'), + 'type' => 'text', + 'size' => 'regular' + ), + array( + 'name' => 'ninja_forms_mc_disable_ssl_verify', + 'label' => __('Disable SSL Verification', 'ninja-forms-mc'), + 'desc' => __('If you receive an error about validating the SSL certificate, enable this option', 'ninja-forms-mc'), + 'type' => 'checkbox', + ) + ) + ); + ninja_forms_register_tab_metabox($mc_args); +} +add_action('admin_init', 'ninja_forms_mc_add_plugin_settings', 100); + +/** + * Retrieve an array of Mail Chimp lists + * + * @since 1.0 + * @return array + */ +function ninja_forms_mc_get_mailchimp_lists() +{ + + global $pagenow, $edd_settings_page; + + //if ( ! isset( $_GET['page'] ) || ! isset( $_GET['tab'] ) || $_GET['page'] != 'ninja-forms' || $_GET['tab'] != 'form_settings' ) + // return; + + $options = get_option("ninja_forms_settings"); + + if (isset($options['ninja_forms_mc_api']) && strlen(trim($options['ninja_forms_mc_api'])) > 0) { + $lists = get_transient('nf_mailchimp_lists'); + + if (false === $lists) { + $lists = array(); + if (! class_exists('Mailchimp')) { + require_once 'Mailchimp.php'; + } + + try { + $verify_ssl = isset($options['ninja_forms_mc_disable_ssl_verify']) ? false : true; + + $opts = array( + 'debug' => defined('WP_DEBUG') && WP_DEBUG, + 'ssl_verifypeer' => $verify_ssl, + ); + + $api = new Mailchimp(trim($options['ninja_forms_mc_api']), $opts); + $list_data = $api->call('lists/list', array( 'limit' => 100 )); + if ($list_data) { + foreach ($list_data['data'] as $key => $list) { + $lists[] = array( + 'value' => $list['id'], + 'name' => $list['name'] + ); + } + } + + set_transient('nf_mailchimp_lists', $lists, 60*60*60); + } catch (Exception $e) { + $lists = new WP_Error('invalid_api_key', __('The API key you have entered appears to be invalid', 'ninja-forms-mc')); + } + } + + return $lists; + } + return array(); +} + + +/** + * Subscribe an email address to a Mail Chimp list + * + * @since 1.0 + * @return bool + */ +function ninja_forms_mc_subscribe_email($subscriber = array(), $list_id = '', $double_opt = true) +{ + + $options = get_option("ninja_forms_settings"); + + if (empty($list_id) || empty($subscriber)) { + return false; + } + + if (! class_exists('Mailchimp')) { + require_once 'Mailchimp.php'; + } + + $verify_ssl = isset($options['ninja_forms_mc_disable_ssl_verify']) ? false : true; + + $opts = array( + 'debug' => defined('WP_DEBUG') && WP_DEBUG, + 'ssl_verifypeer' => $verify_ssl, + ); + + $api = new Mailchimp(trim($options['ninja_forms_mc_api']), $opts); + + try { + $result = $api->call('lists/subscribe', array( + 'id' => $list_id, + 'email' => array( 'email' => $subscriber['email'] ), + 'merge_vars' => $subscriber['merge_vars'], + 'double_optin' => $double_opt, + 'update_existing' => true, + 'replace_interests' => false, + 'send_welcome' => false, + )); + } catch (Mailchimp_Error $e) { + if (defined('WP_DEBUG') && WP_DEBUG) { + wp_die(__('Error', 'ninja-forms-mc'), print_r($e, true), array( 'response' => 400 )); + } + + $result = false; + } catch (Exception $e) { + if (defined('WP_DEBUG') && WP_DEBUG) { + wp_die(__('Error', 'ninja-forms-mc'), print_r($e, true), array( 'response' => 400 )); + } + + $result = false; + } + + return (bool) $result; +} + +/** + * Plugin Updater / licensing + * + * @since 1.0.2 + * @return void + */ + +function ninja_forms_mc_extension_setup_license() +{ + if (class_exists('NF_Extension_Updater')) { + $NF_Extension_Updater = new NF_Extension_Updater('MailChimp', '3.1.1', 'Pippin Williamson', __FILE__, 'mailchimp'); + } +} +add_action('admin_init', 'ninja_forms_mc_extension_setup_license'); + +if (! function_exists('ninja_forms_get_ip')) { + + /** + * Get User IP + * + * Returns the IP address of the current visitor + * + * @since 1.1 + * @return string $ip User's IP address + */ + function ninja_forms_get_ip() + { + + $ip = '127.0.0.1'; + + if (! empty($_SERVER['HTTP_CLIENT_IP'])) { + //check ip from share internet + $ip = $_SERVER['HTTP_CLIENT_IP']; + } elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + //to check ip is pass from proxy + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } elseif (! empty($_SERVER['REMOTE_ADDR'])) { + $ip = $_SERVER['REMOTE_ADDR']; + } + + return apply_filters('ninja_forms_get_ip', $ip); + } + +} + +/** + * Validate the API key upon save + * + * @since 1.1.3 + * @return void + */ +function ninja_forms_mc_validate_api_key() +{ + + if (! isset($_GET['page']) || 'ninja-forms-settings' != $_GET['page']) { + return; + } + + $options = get_option('ninja_forms_settings'); + + if (empty($options['ninja_forms_mc_api'])) { + return; + } + + if (! empty($_POST['ninja_forms_mc_api']) || ( isset($options['ninja_forms_mc_api']) && $options['ninja_forms_mc_api'] !== $_POST['ninja_forms_mc_api'] )) { + delete_transient('nf_mailchimp_lists'); + + if (! class_exists('Mailchimp')) { + require_once 'Mailchimp.php'; + } + + $verify_ssl = isset($options['ninja_forms_mc_disable_ssl_verify']) ? false : true; + + try { + $opts = array( + 'debug' => defined('WP_DEBUG') && WP_DEBUG, + 'ssl_verifypeer' => $verify_ssl, + ); + $api = new Mailchimp(trim($_POST['ninja_forms_mc_api']), $opts); + $list_data = $api->call('lists/list', array( 'limit' => 1 )); + } catch (Exception $e) { + wp_die(sprintf(__('The API key you have entered appears to be invalid. Please go back and re-enter it. Error message: %s', 'ninja-forms-mc'), $e->getMessage()), __('Error', 'ninja-forms-mc'), array( 'back_link' => true, 'response' => 401 )); + } + } +} +add_action('ninja_forms_save_admin_tab', 'ninja_forms_mc_validate_api_key'); + +/** + * Retrieve all merge vars + * + * @since 1.3 + * @return void + */ +function ninja_forms_mc_get_merge_vars($list_id = '') +{ + + if (! class_exists('Mailchimp')) { + require_once 'Mailchimp.php'; + } + + $options = get_option('ninja_forms_settings'); + + $verify_ssl = isset($options['ninja_forms_mc_disable_ssl_verify']) ? false : true; + + $opts = array( + 'debug' => defined('WP_DEBUG') && WP_DEBUG, + 'ssl_verifypeer' => $verify_ssl, + ); + + $api = new Mailchimp(trim($options['ninja_forms_mc_api']), $opts); + $vars = $api->lists->mergeVars(array( $list_id )); + + if (! empty($vars['data'][0])) { + return $vars['data'][0]['merge_vars']; + } + + return false; +} + +/** + * Retrieve all segments + * + * @since 1.3 + * @return void + */ +function ninja_forms_mc_get_groups($list_id = '') +{ + + if (! class_exists('Mailchimp')) { + require_once 'Mailchimp.php'; + } + + $data = get_transient('nf_mailchimp_groupings_' . $list_id); + + if (false === $data) { + $options = get_option('ninja_forms_settings'); + + $verify_ssl = isset($options['ninja_forms_mc_disable_ssl_verify']) ? false : true; + + $opts = array( + 'debug' => defined('WP_DEBUG') && WP_DEBUG, + 'ssl_verifypeer' => $verify_ssl, + ); + + $segs = array(); + $api = new Mailchimp(trim($options['ninja_forms_mc_api']), $opts); + $list_data = $api->call('lists/list', array( 'filters' => array( 'list_id' => $list_id ) )); + + if ($list_data['data'][0]['stats']['group_count'] > 0) { + $data = $api->lists->interestGroupings($list_id); + } + + set_transient('nf_mailchimp_groupings_' . $list_id, $data, 24*24*24); + } + + $groups_data = array(); + + if ($data && ! isset($data->status)) { + foreach ($data as $key => $grouping) { + if (is_array($grouping['groups'])) { + $groups_data[ $key ] = array( + 'id' => $grouping['id'], + 'name' => $grouping['name'], + 'groups' => array() + ); + + + foreach ($grouping['groups'] as $groups) { + $groups_data[ $key ]['groups'][] = array( + 'id' => $groups['id'], + 'name' => $groups['name'] + ); + } + } + } + } + + return $groups_data; +} + +/** + * Adds a MailChimp opt-in option to the checkbox field + * + * @since 1.3 + * @return void + */ +function ninja_forms_mc_field_checkbox_opt_in($field_id, $field_data) +{ + + $field = ninja_forms_get_field_by_id($field_id); + + if ('_checkbox' != $field['type']) { + return false; + } + + $nf_mc_opt_in = isset($field_data['nf_mc_opt_in']) ? $field_data['nf_mc_opt_in'] : ''; + ?> +
+ +
+ + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-return array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..c6b54af --- /dev/null +++ b/vendor/composer/InstalledVersions.php @@ -0,0 +1,352 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints($constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = require __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + $installed[] = self::$installed; + + return $installed; + } +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..0fb0a2c --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,10 @@ + $vendorDir . '/composer/InstalledVersions.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..15a2ff3 --- /dev/null +++ b/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/src'), + 'NFMailchimp\\EmailCRM\\' => array($baseDir . '/lib'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php new file mode 100644 index 0000000..1c79420 --- /dev/null +++ b/vendor/composer/autoload_real.php @@ -0,0 +1,36 @@ +register(true); + + return $loader; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 0000000..11b129a --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,41 @@ + + array ( + 'NFMailchimp\\NinjaForms\\Mailchimp\\' => 33, + 'NFMailchimp\\EmailCRM\\' => 21, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'NFMailchimp\\NinjaForms\\Mailchimp\\' => + array ( + 0 => __DIR__ . '/../..' . '/src', + ), + 'NFMailchimp\\EmailCRM\\' => + array ( + 0 => __DIR__ . '/../..' . '/lib', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit3493e98f53c33ecffbfa8de70086a92e::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit3493e98f53c33ecffbfa8de70086a92e::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit3493e98f53c33ecffbfa8de70086a92e::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 0000000..f20a6c4 --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": false, + "dev-package-names": [] +} diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php new file mode 100644 index 0000000..5be85b1 --- /dev/null +++ b/vendor/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => 'ninja-forms/ninja-forms-mailchimp', + 'pretty_version' => '3.3.6', + 'version' => '3.3.6.0', + 'reference' => '6693b6277e9ce187028e1eb7bf59f7ba6d74e72e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => false, + ), + 'versions' => array( + 'ninja-forms/ninja-forms-mailchimp' => array( + 'pretty_version' => '3.3.6', + 'version' => '3.3.6.0', + 'reference' => '6693b6277e9ce187028e1eb7bf59f7ba6d74e72e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +);