Advertisement
Guest User

Untitled

a guest
Feb 17th, 2015
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 34.73 KB | None | 0 0
  1. <?php
  2. /**
  3.  * @name iContactApi
  4.  * @package iContact
  5.  * @author iContact <www.icontact.com>
  6.  * @description This class is a wrapper for the iContact API.
  7.  * It makes integrating iContact into your app as simple as
  8.  * calling a method.
  9.  * @version 2.0
  10. **/
  11.  
  12. class iContactApi {
  13.  
  14.     //////////////////////////////////////////////////////////////////////////////
  15.     /// Properties //////////////////////////////////////////////////////////////
  16.     ////////////////////////////////////////////////////////////////////////////
  17.  
  18.     protected static $oInstance  = null;    // This holds the instance of this class
  19.     protected $iAccountId        = null;    // This holds the account ID
  20.     protected $iClientFolderId   = null;    // This holds the client folder ID
  21.     protected $aConfig           = array(); // This is our array for pragmatically overriding configuration constants
  22.     protected $aErrors           = array(); // This holds the errors encountered with the iContact API
  23.     protected $sLastRequest      = null;    // This holds the last request JSON
  24.     protected $sLastResponse     = null;    // This holds the last response JSON
  25.     protected $sRequestUri       = null;    // This stores the last used URL
  26.     protected $bSandbox          = false;   // This tells the system whether or not to use the iContact Sandbox or not
  27.     protected $aSearchParameters = array(); // This is our container for search params
  28.     protected $iTotal            = 0;       // If the results return a total, it will be stored here
  29.     protected $aWarnings         = array(); // This holds the warnings encountered with the iContact API
  30.  
  31.     //////////////////////////////////////////////////////////////////////////////
  32.     /// Singleton ///////////////////////////////////////////////////////////////
  33.     ////////////////////////////////////////////////////////////////////////////
  34.  
  35.     /**
  36.      * This sets the singleton pattern instance
  37.      * @static
  38.      * @access public
  39.      * @param iContactApi $oInstance Instance to set to
  40.      * @return iContactApi $this
  41.     **/
  42.     public static function setInstance($oInstance) {
  43.  
  44.         self::$oInstance = $oInstance;
  45.         // Return instance of class
  46.         return self::$oInstance;
  47.     }
  48.  
  49.     /**
  50.      * This gets the singleton instance
  51.      * @static
  52.      * @access public
  53.      * @return iContactApi $this
  54.     **/
  55.     public static function getInstance() {
  56.         // Check to see if an instance has already
  57.         // been created
  58.         if (is_null(self::$oInstance)) {
  59.             // If not, return a new instance
  60.             self::$oInstance = new self();
  61.             return self::$oInstance;
  62.         } else {
  63.             // If so, return the previously created
  64.             // instance
  65.             return self::$oInstance;
  66.         }
  67.     }
  68.  
  69.     /**
  70.      * This resets the singleton instance to null
  71.      * @static
  72.      * @access public
  73.      * @return void
  74.     **/
  75.     public static function resetInstance() {
  76.         // Reset the instance
  77.         self::$oInstance = null;
  78.     }
  79.  
  80.     //////////////////////////////////////////////////////////////////////////////
  81.     /// Constructor /////////////////////////////////////////////////////////////
  82.     ////////////////////////////////////////////////////////////////////////////
  83.  
  84.     /**
  85.      * This is our constuctor and simply checks for
  86.      * defined constants and configuration values and
  87.      * then builds the configuration from that
  88.      * @access protected
  89.      * @return iContactApi $this
  90.     **/
  91.     protected function __construct() {
  92.         // Check for constants
  93.         $aConstantMap = array(
  94.             // 'ICONTACT_APIVERSION',
  95.             // 'ICONTACT_APISANDBOXURL',
  96.             'ICONTACT_APPID'       => 'appId',
  97.             // 'ICONTACT_APIURL',
  98.             'ICONTACT_APIUSERNAME' => 'apiUsername',
  99.             'ICONTACT_APIPASSWORD' => 'apiPassword'
  100.         );
  101.         // Loop through the map
  102.         foreach ($aConstantMap as $sConstant => $sConfigKey) {
  103.             // Check for the defined constant
  104.             if (defined($sConstant)) {
  105.                 // Set the configuration key to the contant's value
  106.                 $this->aConfig[$sConfigKey] = constant($sConstant);
  107.             }
  108.         }
  109.         // Return instance
  110.         return $this;
  111.     }
  112.  
  113.     //////////////////////////////////////////////////////////////////////////////
  114.     /// Public //////////////////////////////////////////////////////////////////
  115.     ////////////////////////////////////////////////////////////////////////////
  116.  
  117.     /**
  118.      * This method adds a contact to your iContact account
  119.      * @access public
  120.      * @param string $sEmail
  121.      * @param string [$sStatus]
  122.      * @param string [$sPrefix]
  123.      * @param string [$sFirstName]
  124.      * @param string [$sLastName]
  125.      * @param string [$sSuffix]
  126.      * @param string [$sStreet]
  127.      * @param string [$sStreet2]
  128.      * @param string [$sCity]
  129.      * @param string [$sState]
  130.      * @param string [$sPostalCode]
  131.      * @param string [$sPhone]
  132.      * @param string [$sFax]
  133.      * @param string [$sBusiness]
  134.      *
  135.      * @return object
  136.     **/
  137.     public function addContact($sEmail, $sStatus = 'normal', $sPrefix = null, $sFirstName = null, $sLastName = null, $sSuffix = null, $sStreet = null, $sStreet2 = null, $sCity = null, $sState = null, $sPostalCode = null, $sPhone = null, $sFax = null, $sBusiness = null) {
  138.         // Valid statuses
  139.         $aValidStatuses = array('normal', 'bounced', 'donotcontact', 'pending', 'invitable', 'deleted');
  140.         // Contact placeholder
  141.         $aContact       = array(
  142.             'email' => $sEmail
  143.         );
  144.         // Check for a prefix
  145.         if (!empty($sPrefix)) {
  146.             // Add the new prefix
  147.             $aContact['prefix'] = (string) $sPrefix;
  148.         }
  149.         // Check for a first name
  150.         if (!empty($sFirstName)) {
  151.             // Add the new first name
  152.             $aContact['firstName'] = (string) $sFirstName;
  153.         }
  154.         // Check for a last name
  155.         if (!empty($sLastName)) {
  156.             // Add the new last name
  157.             $aContact['lastName'] = (string) $sLastName;
  158.         }
  159.         // Check for a suffix
  160.         if (!empty($sSuffix)) {
  161.             // Add the new suffix
  162.             $aContact['suffix'] = (string) $sSuffix;
  163.         }
  164.         // Check for a street
  165.         if (!empty($sStreet)) {
  166.             // Add the new street
  167.             $aContact['street'] = (string) $sStreet;
  168.         }
  169.         // Check for a street2
  170.         if (!empty($sStreet2)) {
  171.             // Add the new street 2
  172.             $aContact['street2'] = (string) $sStreet2;
  173.         }
  174.         // Check for a city
  175.         if (!empty($sCity)) {
  176.             // Add the new city
  177.             $aContact['city'] = (string) $sCity;
  178.         }
  179.         // Check for a state
  180.         if (!empty($sState)) {
  181.             // Add the new state
  182.             $aContact['state'] = (string) $sState;
  183.         }
  184.         // Check for a postal code
  185.         if (!empty($sPostalCode)) {
  186.             // Add the new postal code
  187.             $aContact['postalCode'] = (string) $sPostalCode;
  188.         }
  189.         // Check for a phone number
  190.         if (!empty($sPhone)) {
  191.             // Add the new phone number
  192.             $aContact['phone'] = (string) $sPhone;
  193.         }
  194.         // Check for a fax number
  195.         if (!empty($sFax)) {
  196.             // Add the new fax number
  197.             $aContact['fax'] = (string) $sFax;
  198.         }
  199.         // Check for a business name
  200.         if (!empty($sBusiness)) {
  201.             // Add the new business
  202.             $aContact['business'] = (string) $sBusiness;
  203.         }
  204.         // Check for a valid status
  205.         if (!empty($sStatus) && in_array($sStatus, $aValidStatuses)) {
  206.             // Add the new status
  207.             $aContact['status'] = $sStatus;
  208.         } else {
  209.             $aContact['status'] = 'normal';
  210.         }
  211.  
  212.         // Make the call
  213.         $aContacts = $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/contacts", 'POST', array($aContact), 'contacts');
  214.         // Return the contact
  215.         return $aContacts[0];
  216.     }
  217.  
  218.     /**
  219.      * This method adds a custom field or "term"
  220.      * to the array of search parameters
  221.      * @access public
  222.      * @param string $sName
  223.      * @param string $sValue
  224.      * @return iContactApi $this
  225.     **/
  226.     public function addCustomQueryField($sName, $sValue) {
  227.         // Add the field
  228.         $this->aSearchParameters[$sName] = (string) $sValue;
  229.         // Return instance
  230.         return $this;
  231.     }
  232.  
  233.     /**
  234.      * This message adds a list to your iContact account
  235.      * @access public
  236.      * @param string $sName
  237.      * @param integer $iWelcomeMessageId
  238.      * @param bool [$bEmailOwnerOnChange]
  239.      * @param bool [$bWelcomeOnManualAdd]
  240.      * @param bool [$bWelcomeOnSignupAdd]
  241.      * @param string [$sDescription]
  242.      * @param string [$sPublicName]
  243.      * @return object
  244.     **/
  245.     public function addList($sName, $iWelcomeMessageId, $bEmailOwnerOnChange = true, $bWelcomeOnManualAdd = false, $bWelcomeOnSignupAdd = false, $sDescription = null, $sPublicName = null) {
  246.         // Setup the list
  247.         $aList = array(
  248.             'name'               => $sName,
  249.             'welcomeMessageId'   => $iWelcomeMessageId,
  250.             'emailOwnerOnChange' => intval($bEmailOwnerOnChange),
  251.             'welcomeOnManualAdd' => intval($bWelcomeOnManualAdd),
  252.             'welcomeOnSignupAdd' => intval($bWelcomeOnSignupAdd),
  253.             'description'        => $sDescription,
  254.             'publicname'         => $sPublicName
  255.         );
  256.         // Make the call
  257.         $aLists = $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/lists", 'POST', array($aList), 'lists');
  258.         // Return the list
  259.         return $aLists[0];
  260.     }
  261.  
  262.     /**
  263.      * This method adds a message to
  264.      * your iContact API account
  265.      * @access public
  266.      * @param string $sSubject
  267.      * @param integer $iCampaignId
  268.      * @param string [$sHtmlBody]
  269.      * @param string [$sTextBody]
  270.      * @param string [$sMessageName]
  271.      * @param integer [$iListId]
  272.      * @param string [$sMessageType]
  273.      * @return object
  274.     **/
  275.     public function addMessage($sSubject, $iCampaignId, $sHtmlBody = null, $sTextBody = null, $sMessageName = null, $iListId = null, $sMessageType = 'normal') {
  276.         // Valid message types
  277.         $aValidMessageTypes = array('normal', 'autoresponder', 'welcome', 'confirmation');
  278.         // Setup the message data
  279.         $aMessage           = array(
  280.             'campaignId'  => $iCampaignId,
  281.             'htmlBody'    => $sHtmlBody,
  282.             'messageName' => $sMessageName,
  283.             'messageType' => (in_array($sMessageType, $aValidMessageTypes) ? $sMessageType : 'normal'),
  284.             'subject'     => $sSubject,
  285.             'textBody'    => $sTextBody
  286.         );
  287.         // Add the message
  288.         $aNewMessage = $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/messages", 'POST', array($aMessage), 'messages');
  289.         // Return the message data
  290.         return $aNewMessage[0];
  291.     }
  292.  
  293.     /**
  294.      * This method adds a field to the order by
  295.      * key in the search parameters array
  296.      * @access public
  297.      * @param string $sField
  298.      * @param string [$sDirection]
  299.      * @return iContactApi $this
  300.     **/
  301.     public function addOrderBy($sField, $sDirection = null) {
  302.         // Check for existing order by parameters
  303.         if (empty($this->aSearchParameters['orderby'])) {
  304.             // Check for a direction
  305.             if (empty($sDirection)) {
  306.                 // Add just the field
  307.                 $this->aSearchParameters['orderby'] = (string) $sField;
  308.             } else {
  309.                 // Add the field and direction
  310.                 $this->aSearchParameters['orderby'] = (string) "{$sField}:{$sDirection}";
  311.             }
  312.         } else {
  313.             // Check for a direction
  314.             if (empty($sDirection)) {
  315.                 // Append just the field
  316.                 $this->aSearchParameters['orderby'] .= (string) ",{$sField}";
  317.             } else {
  318.                 // Append the field and direction
  319.                 $this->aSearchParameters['orderby'] .= (string) ",{$sField}:{$sDirection}";
  320.             }
  321.         }
  322.         // Return failure
  323.         return false;
  324.     }
  325.  
  326.     /**
  327.      * This method handles the deleting of a single list
  328.      * @access public
  329.      * @param integer $iListId
  330.      * @return bool
  331.     **/
  332.     public function deleteList($iListId) {
  333.         // Delete the list
  334.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/lists/{$iListId}", 'delete');
  335.     }
  336.  
  337.     /**
  338.      * This method handles the handshaking between this app and the iContact API
  339.      * @access public
  340.      * @param string $sResource
  341.      * @param string $sMethod
  342.      * @param string $sReturnKey
  343.      * @param mixed  $mPostData Array, object, or string
  344.      * @return array|object
  345.     **/
  346.     public function makeCall($sResource, $sMethod = 'GET', $mPostData = null, $sReturnKey = null) {
  347.         // List of needed constants
  348.         $aRequiredConfigs = array('apiPassword', 'apiUsername', 'appId');
  349.         // First off check for definitions
  350.         foreach ($aRequiredConfigs as $sKey) {
  351.             // Is it defined
  352.             if (empty($this->aConfig[$sKey])) {
  353.                 // Set an error
  354.                 $this->addError("{$sKey} is undefined.");
  355.             }
  356.         }
  357.         // Set the URI that we will be calling
  358.         $sApiUrl    = (string) "{$this->getUrl()}{$sResource}";
  359.         // Initialize the cURL handle
  360.         $rHandle     = curl_init();
  361.         // Give our handle headers
  362.         curl_setopt($rHandle, CURLOPT_HTTPHEADER, $this->getHeaders());
  363.         // Tell our handle that we
  364.         // want the data returned
  365.         curl_setopt($rHandle, CURLOPT_RETURNTRANSFER, true);
  366.         // Turn SSL verifcation off, so scripts do not get broken
  367.         curl_setopt($rHandle, CURLOPT_SSL_VERIFYPEER, false);
  368.         // Determine the request
  369.         // method we are using
  370.         switch (strtoupper($sMethod)) {
  371.             // Deleting data
  372.             case 'DELETE' :
  373.                 // Set the cURL custom header
  374.                 curl_setopt($rHandle, CURLOPT_CUSTOMREQUEST, 'DELETE');
  375.             break;
  376.             // Recieving data
  377.             case 'GET'    :
  378.                 // Check for a query string
  379.                 if (!empty($this->aSearchParameters)) {
  380.                     // Add the query string
  381.                     $sApiUrl .= (string) '?'.http_build_query($this->aSearchParameters);
  382.                 }
  383.             break;
  384.             // Sending data
  385.             case 'POST'   :
  386.                 // Check for POST data
  387.                 if (empty($mPostData)) {
  388.                     // Add an error, for there is no
  389.                     // POST data to send to the API
  390.                     $this->addError('No POST data was provided.');
  391.                 } else {
  392.                     // Tell our handle that
  393.                     // we want to send data
  394.                     curl_setopt($rHandle, CURLOPT_POST, true);
  395.                     // Give our handle the data
  396.                     curl_setopt($rHandle, CURLOPT_POSTFIELDS, json_encode($mPostData));
  397.                     // Set the request JSON
  398.                     $this->sLastRequest = (string) json_encode($mPostData);
  399.                 }
  400.             break;
  401.             // Uploading data
  402.             case 'PUT'    :
  403.                 if (empty($mPostData)) {
  404.                     // Is there data?
  405.                     $this->addError('No file or data specified for PUT request');
  406.                 } elseif (!is_string($mPostData) || !file_exists($mPostData)) {
  407.                     // Not a file, so we assume this is just data
  408.                     curl_setopt($rHandle, CURLOPT_CUSTOMREQUEST, "PUT");
  409.                     curl_setopt($rHandle, CURLOPT_POSTFIELDS, $mPostData);
  410.                 } else {
  411.                     $rFileContentHandle = fopen($mPostData, 'r');
  412.                     if ($rFileContentHandle === false) {
  413.                         $this->addError('A non-existant file was specified for POST data, or the file could not be opened.');
  414.                     } else {
  415.                         // Found a file, so upload its contents
  416.                         curl_setopt($rHandle, CURLOPT_PUT, true);
  417.                         curl_setopt($rHandle, CURLOPT_INFILE, $rFileContentHandle);
  418.                     }
  419.                 }
  420.             break;
  421.         }
  422.         // Store the URL into the instance
  423.         $this->sRequestUri = (string) $sApiUrl;
  424.         // Give our handle a URL
  425.         curl_setopt($rHandle, CURLOPT_URL, $sApiUrl);
  426.         // Try to execute the handle
  427.         if (!$sResponse = curl_exec($rHandle)) {
  428.             // Add an error, for we could
  429.             // not even execute the handle
  430.             $this->addError('We were unable to execute the cURL handle.');
  431.         }
  432.         // Set the response JSON
  433.         $this->sLastResponse = (string) $sResponse;
  434.         // Try to decode the response
  435.         if ((!$aResponse = json_decode($sResponse)) && (strtoupper($sMethod) != 'DELETE')) {
  436.             // Add an error, for the API
  437.             // did not return valid JSON
  438.             $this->addError('The iContact API did not return valid JSON.');
  439.         }
  440.         // Close the cURL handle
  441.         curl_close($rHandle);
  442.         // Check for errors from the API
  443.         if (!empty($aResponse->errors)) {
  444.             // Loop through the errors
  445.             foreach ($aResponse->errors as $sError) {
  446.                 // Add the error
  447.                 $this->addError($sError, 1);
  448.             }
  449.         }
  450.         // Check for warnings from the API
  451.         if (!empty($aResponse->warnings)) {
  452.             // Loop through the warnings
  453.             foreach ($aResponse->warnings as $sWarning) {
  454.                 // Add the warning
  455.                 $this->addWarning($sWarning);
  456.             }
  457.         }
  458.         // Check for set errors
  459.         if (!empty($this->aErrors)) {
  460.             // Throw a new exception
  461.             throw new Exception('Errors have occurred and the system cannot continue.  Use getErrors() for details.');
  462.         }
  463.         // Check for a total
  464.         if (!empty($aResponse->total)) {
  465.             // Store the total records
  466.             // into the current instsnce
  467.             $this->iTotal = (integer) $aResponse->total;
  468.         }
  469.         // Return the response
  470.         if (strtoupper($sMethod) == 'DELETE') {
  471.             // Return success
  472.             return true;
  473.         } elseif (empty($sReturnKey)) {
  474.             // Return the entire
  475.             // base response
  476.             return $aResponse;
  477.         } else {
  478.             // Return the narrowed resposne
  479.             return $aResponse->$sReturnKey;
  480.         }
  481.     }
  482.  
  483.     /**
  484.      * This method sends a message
  485.      * @access public
  486.      * @param string $sIncludeListId
  487.      * @param integer $iMessageId
  488.      * @param string [$sExcludeListIds]
  489.      * @param string [$sExcludeSegmentIds]
  490.      * @param string [$sIncludeSegmentIds]
  491.      * @param string [$sScheduledTime]
  492.      * @return object
  493.     **/
  494.     public function sendMessage($sIncludeListIds, $iMessageId, $sExcludeListIds = null, $sExcludeSegmentIds = null, $sIncludeSegmentIds = null, $sScheduledTime = null) {
  495.         // Send the message
  496.         $aSends = $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/sends", 'POST', array(
  497.             array(
  498.                 'excludeListIds'    => $sExcludeListIds,
  499.                 'excludeSegmentIds' => $sExcludeSegmentIds,
  500.                 'includeListIds'    => $sIncludeListIds,
  501.                 'includeSegmentIds' => $sIncludeSegmentIds,
  502.                 'scheduledTime'     => (empty($sScheduledTime) ? null : date('c', strtotime($sScheduledTime)))
  503.             )
  504.         ), 'sends');
  505.         // Return the send
  506.         return $aSends;
  507.     }
  508.  
  509.     /**
  510.      * This method subscribes a contact to a list
  511.      * @access public
  512.      * @param integer $iContactId
  513.      * @param integer $iListId
  514.      * @param string  $sStatus
  515.      * @return object
  516.      **/
  517.     public function subscribeContactToList($iContactId, $iListId, $sStatus = 'normal') {
  518.         // Valid statuses
  519.         $aValidStatuses = array('normal', 'pending', 'unsubscribed');
  520.         // Setup the subscription and make the call
  521.         $aSubscriptions = $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/subscriptions", 'POST', array(
  522.             array(
  523.                 'contactId' => $iContactId,
  524.                 'listId'    => $iListId,
  525.                 'status'    => $sStatus
  526.             )
  527.         ), 'subscriptions');
  528.         // Return the subscription
  529.         return $aSubscriptions;
  530.     }
  531.  
  532.     /**
  533.      * This method updates a contact in your iContact account
  534.      * @access public
  535.      * @param integer $iContactId
  536.      * @param string  $sEmail
  537.      * @param string  $sPrefix
  538.      * @param string  $sFirstName
  539.      * @param string  $sLastName
  540.      * @param string  $sSuffix
  541.      * @param string  $sStreet
  542.      * @param string  $sStreet2
  543.      * @param string  $sCity
  544.      * @param string  $sState
  545.      * @param string  $sPostalCode
  546.      * @param string  $sPhone
  547.      * @param string  $sFax
  548.      * @param string  $sBusiness
  549.      * @param string  $sStatus
  550.      * @return bool|object
  551.      **/
  552.     public function updateContact($iContactId, $sEmail = null, $sPrefix = null, $sFirstName = null, $sLastName = null, $sSuffix = null, $sStreet = null, $sStreet2 = null, $sCity = null, $sState = null, $sPostalCode = null, $sPhone = null, $sFax = null, $sBusiness = null, $sStatus = null) {
  553.         // Valid statuses
  554.         $aValidStatuses = array('normal', 'bounced', 'donotcontact', 'pending', 'invitable', 'deleted');
  555.         // Contact placeholder
  556.         $aContact       = array();
  557.         // Check for an email address
  558.         if (!empty($sEmail)) {
  559.             // Add the new email
  560.             $aContact['email'] = (string) $sEmail;
  561.         }
  562.         // Check for a prefix
  563.         if (!empty($sPrefix)) {
  564.             // Add the new prefix
  565.             $aContact['prefix'] = (string) $sPrefix;
  566.         }
  567.         // Check for a first name
  568.         if (!empty($sFirstName)) {
  569.             // Add the new first name
  570.             $aContact['firstName'] = (string) $sFirstName;
  571.         }
  572.         // Check for a last name
  573.         if (!empty($sLastName)) {
  574.             // Add the new last name
  575.             $aContact['lastName'] = (string) $sLastName;
  576.         }
  577.         // Check for a suffix
  578.         if (!empty($sSuffix)) {
  579.             // Add the new suffix
  580.             $aContact['suffix'] = (string) $sSuffix;
  581.         }
  582.         // Check for a street
  583.         if (!empty($sStreet)) {
  584.             // Add the new street
  585.             $aContact['street'] = (string) $sStreet;
  586.         }
  587.         // Check for a street2
  588.         if (!empty($sStreet2)) {
  589.             // Add the new street 2
  590.             $aContact['street2'] = (string) $sStreet2;
  591.         }
  592.         // Check for a city
  593.         if (!empty($sCity)) {
  594.             // Add the new city
  595.             $aContact['city'] = (string) $sCity;
  596.         }
  597.         // Check for a state
  598.         if (!empty($sState)) {
  599.             // Add the new state
  600.             $aContact['state'] = (string) $sState;
  601.         }
  602.         // Check for a postal code
  603.         if (!empty($sPostalCode)) {
  604.             // Add the new postal code
  605.             $aContact['postalCode'] = (string) $sPostalCode;
  606.         }
  607.         // Check for a phone number
  608.         if (!empty($sPhone)) {
  609.             // Add the new phone number
  610.             $aContact['phone'] = (string) $sPhone;
  611.         }
  612.         // Check for a fax number
  613.         if (!empty($sFax)) {
  614.             // Add the new fax number
  615.             $aContact['fax'] = (string) $sFax;
  616.         }
  617.         // Check for a business name
  618.         if (!empty($sBusiness)) {
  619.             // Add the new business
  620.             $aContact['business'] = (string) $sBusiness;
  621.         }
  622.         // Check for a valid status
  623.         if (!empty($sStatus) && in_array($sStatus, $aValidStatuses)) {
  624.             // Add the new status
  625.             $aContact['status'] = $sStatus;
  626.         }
  627.         // Make sure the contact isn't empty
  628.         if (!empty($aContact)) {
  629.             // Make the call
  630.             $oContact = $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/contacts/{$iContactId}", 'POST', array($aContact), 'contact');
  631.             // Return the contact
  632.             return $oContact;
  633.         }
  634.         // Inevitably return failure
  635.         return false;
  636.     }
  637.  
  638.     /**
  639.      * This method uploads a CSV file to the iContact API
  640.      * @access public
  641.      * @param string $sFile
  642.      * @param integer [$iListId]
  643.      * @param integer [$iUploadId]
  644.      * @return string|bool
  645.     **/
  646.     public function uploadData($sFile, $iListId = null, $iUploadId = null) {
  647.         // Check for an upload ID
  648.         if (empty($iUploadId)) {
  649.             // Make the call
  650.             $aUploads = $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/uploads", 'POST', array(
  651.                 array(
  652.                     'action' => 'add',
  653.                     'listIds' => $iListId
  654.                 )
  655.             ), 'uploads');
  656.             // Store the uploadID
  657.             $iUploadId = $aUploads[0]->uploadId;
  658.         }
  659.         // Upload the data
  660.         if ($this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/uploads/{$iUploadId}/data", 'PUT', $sFile, 'uploadId')) {
  661.             // Loop until the upload is complete
  662.             while (true) {
  663.                 // Grab the upload
  664.                 $aUpload = $this->getUpload($iUploadId);
  665.                 // Check to see if the upload
  666.                 // has finished uploading
  667.                 if ($aUpload->status != 'receiving') {
  668.                     // Return the upload
  669.                     return $this->makeCall("/a/{$this->setAccountId()}/c{$this->setClientFolderId()}/uploads/{$iUploadId}/data", 'GET');
  670.                 }
  671.             }
  672.         }
  673.         // Return failure
  674.         return false;
  675.     }
  676.  
  677.     /**
  678.      * This message updates a list on your iContact account
  679.      * @access public
  680.      * @param string $sName
  681.      * @param integer $iListId
  682.      * @param string $sName
  683.      * @param integer $iWelcomeMessageId
  684.      * @param bool [$bEmailOwnerOnChange]
  685.      * @param bool [$bWelcomeOnManualAdd]
  686.      * @param bool [$bWelcomeOnSignupAdd]
  687.      * @param string [$sDescription]
  688.      * @param string [$sPublicName]
  689.      * @return object
  690.     **/
  691.     public function updateList($iListId, $sName, $iWelcomeMessageId, $bEmailOwnerOnChange = true, $bWelcomeOnManualAdd = false, $bWelcomeOnSignupAdd = false, $sDescription = null, $sPublicName = null) {
  692.         // Setup the list
  693.         $aList = array(
  694.             'name'               => $sName,
  695.             'welcomeMessageId'   => $iWelcomeMessageId,
  696.             'emailOwnerOnChange' => intval($bEmailOwnerOnChange),
  697.             'welcomeOnManualAdd' => intval($bWelcomeOnManualAdd),
  698.             'welcomeOnSignupAdd' => intval($bWelcomeOnSignupAdd),
  699.             'description'        => $sDescription,
  700.             'publicname'         => $sPublicName
  701.         );
  702.         // Return the list
  703.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/lists/{$iListId}", 'POST', $aList, 'list');;
  704.     }
  705.  
  706.     /**
  707.      * This method tells the system whether
  708.      * or not to use the sandbox or not, the
  709.      * sandbox is turned off by defualt and
  710.      * by default this method turns it on
  711.      * @access public
  712.      * @param bool [$bUse]
  713.      * @return iContactApi $this
  714.     **/
  715.     public function useSandbox($bUse = true) {
  716.         // Set the sandbox status
  717.         $this->bSandbox = (bool) $bUse;
  718.         // Return instance
  719.         return $this;
  720.     }
  721.  
  722.     //////////////////////////////////////////////////////////////////////////////
  723.     /// PROTECTED ///////////////////////////////////////////////////////////////
  724.     ////////////////////////////////////////////////////////////////////////////
  725.  
  726.     /**
  727.      * This method appends an error to the list
  728.      * of errors encountered with the iContact API
  729.      * @access protected
  730.      * @param string $sText
  731.      * @param integer [$iCode]
  732.      * @return iContactApi $this
  733.     **/
  734.     protected function addError($sText) {
  735.         // Append the error
  736.         array_push($this->aErrors, $sText);
  737.         // Return instance
  738.         return $this;
  739.     }
  740.  
  741.     /**
  742.      * This method appends a warning to the list
  743.      * of warnings encountered with the iContact API
  744.      * @access protected
  745.      * @param string $sText
  746.      * @return iContactApi $this
  747.     **/
  748.     public function addWarning($sText) {
  749.         // Append the warning
  750.         array_push($this->aWarnings, $sText);
  751.         // Return instance
  752.         return $this;
  753.     }
  754.  
  755.     //////////////////////////////////////////////////////////////////////////////
  756.     /// Getters /////////////////////////////////////////////////////////////////
  757.     ////////////////////////////////////////////////////////////////////////////
  758.  
  759.     /**
  760.      * This method grabs the campaigns associated
  761.      * your iContact account
  762.      * @access public
  763.      * @return object
  764.     **/
  765.     public function getCampaigns() {
  766.         // Make the call and return the data
  767.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/campaigns", 'GET');
  768.     }
  769.  
  770.     /**
  771.      * This method grabs a single contact
  772.      * from your iContact Account
  773.      * @access public
  774.      * @param integer $iContactId
  775.      * @return object
  776.     **/
  777.     public function getContact($iContactId) {
  778.         // Make the call and return the data
  779.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/contacts/{$iContactId}", 'GET', null, 'contact');
  780.     }
  781.  
  782.     /**
  783.      * This method grabs the contacts associated
  784.      * with you iContact API account
  785.      * @access public
  786.      * @return array
  787.     **/
  788.  
  789.     public function getContacts() {
  790.         // Make the call and return the data
  791.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/contacts?listId=49626&status=total&createDate=2015-01-12&createDateSearchType=gt", 'GET');
  792.     }
  793.  
  794.     /**
  795.      * This method returns any set
  796.      * errors in the current instance
  797.      * @access public
  798.      * @return array|bool
  799.     **/
  800.     public function getErrors() {
  801.         // Check for errors
  802.         if (empty($this->aErrors)) {
  803.             // Return false, for
  804.             // there are no errors
  805.             return false;
  806.         } else {
  807.             // Return the errors
  808.             return $this->aErrors;
  809.         }
  810.     }
  811.  
  812.     /**
  813.      * This method builds the header array
  814.      * for making calls to the API
  815.      * @access public
  816.      * @return array
  817.     **/
  818.     public function getHeaders() {
  819.         // Return the headers
  820.         return array(
  821.             'Except:',
  822.             'Accept:  application/json',
  823.             'Content-type:  application/json',
  824.             'Api-Version:  ' . (defined('ICONTACT_APIVERSION')        ? constant('ICONTACT_APIVERSION') : '2.2'),
  825.             'Api-AppId:  '   . (!empty($this->aConfig['appId'])       ? $this->aConfig['appId']         : constant('ICONTACT_APPID')),
  826.             'Api-Username:  '. (!empty($this->aConfig['apiUsername']) ? $this->aConfig['apiUsername']   : constant('ICONTACT_APIUSERNAME')),
  827.             'Api-Password:  '. (!empty($this->aConfig['apiPassword']) ? $this->aConfig['apiPassword']   : constant('ICONTACT_APIPASSWORD'))
  828.         );
  829.     }
  830.  
  831.     /**
  832.      * This method returns the last
  833.      * API POST request JSON
  834.      * @access public
  835.      * @param bool [$bDecode]
  836.      * @return string|object
  837.     **/
  838.     public function getLastRequest($bDecode = false) {
  839.         // Check to see if we need
  840.         // to decode the raw JSON
  841.         if ($bDecode === true) {
  842.             // Return the decoded JSON
  843.             return json_decode($this->sLastRequest);
  844.         }
  845.         // Return the raw JSON
  846.         return $this->sLastRequest;
  847.     }
  848.  
  849.     /**
  850.      * This method returns the last
  851.      * API response JSON
  852.      * @access public
  853.      * @param bool [$bDecode]
  854.      * @return string|object
  855.     **/
  856.     public function getLastResponse($bDecode = false) {
  857.         // Check to see if we need
  858.         // to decode the raw JSON
  859.         if ($bDecode === true) {
  860.             // Return the decoded JSON
  861.             return json_decode($this->sLastResponse);
  862.         }
  863.         // Return the raw JSON
  864.         return $this->sLastResponse;
  865.     }
  866.  
  867.     /**
  868.      * This method grabs a list of lists
  869.      * that are associated with you iContact
  870.      * API account
  871.      * @access public
  872.      * @return array
  873.     **/
  874.     public function getLists() {
  875.         // Make the call and return the lists
  876.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/lists", 'GET', null, 'lists');
  877.     }
  878.  
  879.     /**
  880.      * This method lists the opens of a
  881.      * single message based on the messageID
  882.      * @access public
  883.      * @param integer iMessageId
  884.      * @return integer
  885.     **/
  886.     public function getMessageOpens($iMessageId) {
  887.         // Make the call and return the data
  888.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/messages/{$iMessageId}/opens", 'GET', null, 'total');
  889.     }
  890.  
  891.     public function getMessages($sType = null) {
  892.         // Check for a message type
  893.         if (!empty($sType)) {
  894.             $this->addCustomQueryField('messageType', $sType);
  895.         }
  896.         // Return the messages
  897.         return $this->makeCall("/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}/messages", 'GET', null, 'messages');
  898.     }
  899.  
  900.     /**
  901.      * This method returns the URL
  902.      * that the last API request
  903.      * called
  904.      * @access public
  905.      * @return string
  906.     **/
  907.     public function getRequestUri() {
  908.         // Return the URL
  909.         return $this->sRequestUri;
  910.     }
  911.  
  912.     /**
  913.      * This method returns the count of the
  914.      * total number of records from the most
  915.      * recent API call, if there is one
  916.      * @access public
  917.      * @return integer
  918.     **/
  919.     public function getTotal() {
  920.         // Return the total records
  921.         return $this->iTotal;
  922.     }
  923.  
  924.     /**
  925.      * This method simply returns the base URL for
  926.      * your API/Sandbox account
  927.      * @access public
  928.      * @param bool [$bFull]
  929.      * @return string
  930.     **/
  931.     public function getUrl($bFull = false) {
  932.         // Set the sandbox URL
  933.         $sSandboxUrl = defined('ICONTACT_APISANDBOXURL') ? constant('ICONTACT_APISANDBOXURL') : 'https://app.sandbox.icontact.com/icp';
  934.         // Set the production URL
  935.         $sApiUrl     = defined('ICONTACT_APIURL')        ? constant('ICONTACT_APIURL')        : 'https://app.icontact.com/icp';
  936.         // Determine which one needs to be returned with the URL
  937.         $sBaseUrl    = ($this->bSandbox === true) ? $sSandboxUrl : $sApiUrl;
  938.         // Do we need to return the entire url or just
  939.         // the base url of the API service
  940.         if ($bFull === false) {
  941.             // Return the base url
  942.             return $sBaseUrl;
  943.         } else {
  944.             // Return the base url and account details
  945.             return $sBaseUrl . "/a/{$this->setAccountId()}/c/{$this->setClientFolderId()}";
  946.         }
  947.     }
  948.  
  949.     /**
  950.      * This method grabs a specific upload
  951.      * @access public
  952.      * @param integer $iUploadId
  953.      * @return object
  954.     **/
  955.     public function getUpload($iUploadId) {
  956.         // Return the upload data
  957.         return $this->makeCall("/a/{$this->setAccountId()}/c{$this->setClientFolderId()}/uploads/{$iUploadId}/data");
  958.     }
  959.  
  960.     /**
  961.      * This method grabs the uploads associated
  962.      * with your iContact Account
  963.      * @access public
  964.      * @return array
  965.     **/
  966.     public function getUploads() {
  967.         // Return the uploads
  968.         return $this->makeCall("/a/{$this->setAccountId()}/c{$this->setClientFolderId()}/uploads");
  969.     }
  970.  
  971.     /**
  972.      * This method returns the warnings encountered
  973.      * while communicating with the iContact API
  974.      * @access public
  975.      * @return array
  976.     **/
  977.     public function getWarnings() {
  978.         // Return the current system warnings
  979.         return $this->aWarnings;
  980.     }
  981.  
  982.     //////////////////////////////////////////////////////////////////////////////
  983.     /// Setters /////////////////////////////////////////////////////////////////
  984.     ////////////////////////////////////////////////////////////////////////////
  985.  
  986.     /**
  987.      * This method fetches the Account ID
  988.      * from the iContact API if it has not
  989.      * already been stored in the instance
  990.      * @access public
  991.      * @param integer [$iAccountId]
  992.      * @return integer
  993.     **/
  994.     public function setAccountId($iAccountId = null) {
  995.         // Check for an overriding
  996.         // Account ID
  997.         if (!empty($iAccountId)) {
  998.             // Override the Account ID
  999.             $this->iAccountId = (integer) $iAccountId;
  1000.         } else {
  1001.             // Check to see if the
  1002.             // Account ID has already
  1003.             // been stored in the
  1004.             // instance
  1005.             if (empty($this->iAccountId)) {
  1006.                 // Load the Account ID
  1007.                 if ($aAccounts = $this->makeCall('/a/', 'get', null, 'accounts')) {
  1008.                     // Set the account
  1009.                     $aAccount = $aAccounts[0];
  1010.                     // Make sure the account is active
  1011.                     if (intval($aAccount->enabled) === 1) {
  1012.                         // The account is active
  1013.                         // set the Account ID
  1014.                         $this->iAccountId = (integer) $aAccount->accountId;
  1015.                     } else {
  1016.                         // Set an error, for this account
  1017.                         // has been disabled
  1018.                         $this->addError('Your account has been disabled.');
  1019.                     }
  1020.                 }
  1021.             }
  1022.         }
  1023.         // Inevitably return instance
  1024.         return $this->iAccountId;
  1025.     }
  1026.  
  1027.     /**
  1028.      * This method fetches the Client
  1029.      * Folder ID from the iContact API
  1030.      * if it has not already been stored
  1031.      * in the instance and the Account ID
  1032.      * has also been stored in the instance
  1033.      * @access public
  1034.      * @param integer [$iClientFolderId]
  1035.      * @return integer
  1036.     **/
  1037.     public function setClientFolderId($iClientFolderId = null) {
  1038.         // Check for an overriding
  1039.         // Client Folder ID
  1040.         if (!empty($iClientFolderId)) {
  1041.             // Set the Client Folder ID
  1042.             $this->iClientFolderId = (integer) $iClientFolderId;
  1043.         } elseif (empty($this->iClientFolderId)) {
  1044.             // Check for an Account ID
  1045.             if (empty($this->iAccountId)) {
  1046.                 // Set the Account ID
  1047.                 $this->setAccountId();
  1048.             }
  1049.             // Set the resource
  1050.             $sResource = (string) "/a/{$this->iAccountId}/c/";
  1051.             // Find the Client Folder ID
  1052.             if ($aClients = $this->makeCall($sResource, 'get', null, 'clientfolders')) {
  1053.                 if (empty($aClients)) {
  1054.                     // Add an error, for there
  1055.                     // are no client folders
  1056.                     $this->addError('No client folders were found for this account.');
  1057.                 } else {
  1058.                     // Grab the default client folder
  1059.                     $aClient = $aClients[0];
  1060.                     // Set the Client Folder ID
  1061.                     $this->iClientFolderId = (integer) $aClient->clientFolderId;
  1062.                 }
  1063.             }
  1064.         }
  1065.         // Inevitably return instance
  1066.         return $this->iClientFolderId;
  1067.     }
  1068.  
  1069.     /**
  1070.      * This method sets configuration into the
  1071.      * plugin to pragmatically override constants
  1072.      * @access public
  1073.      * @param array $aConfig
  1074.      * @return iContactApi $this
  1075.     **/
  1076.     public function setConfig($aConfig) {
  1077.         // Combine the arrays
  1078.         $this->aConfig = (array) array_merge($this->aConfig, $aConfig);
  1079.         // Return instance
  1080.         return $this;
  1081.     }
  1082.  
  1083.     /**
  1084.      * This method sets the result limit
  1085.      * for GET requests to the iContact API
  1086.      * @access public
  1087.      * @param integer $iLimit
  1088.      * @return iContactApi $this
  1089.     **/
  1090.     public function setLimit($iLimit) {
  1091.         // Set the limit in the search parameters
  1092.         $this->aSearchParameters['limit'] = (integer) $iLimit;
  1093.         // Return instance
  1094.         return $this;
  1095.     }
  1096.  
  1097.     /**
  1098.      * This method sets the result index
  1099.      * offset for paginating results from
  1100.      * GET requests to the iContact API
  1101.      * @access public
  1102.      * @param integer $iOffset
  1103.      * @return iContactApi $this
  1104.     **/
  1105.     public function setOffset($iOffset) {
  1106.         // Set the offset in the search parameters
  1107.         $this->aSearchParameters['offset'] = (integer) $iOffset;
  1108.         // Return instance
  1109.         return $this;
  1110.     }
  1111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement