/**
  * Get config value for some key
  *
  * @author Atul Atri
  *
  * @param string $_key configuration key
  * @param string $_app App name if null is provided current module is used
  *
  * @return String value for given key
  *
  * @throws SWIFT_Config_Exception if $_app could not be located or
  *                             if configuration does not exists or
  *                             if Constant $_key does not exist in configuration file
  */
 public static function Get($_key, $_app = null)
 {
     $_configurationFile = null;
     $_appObject = null;
     $_SWIFT = SWIFT::GetInstance();
     if (!$_app) {
         $_appObject = $_SWIFT->Router->GetApp();
     } else {
         $_appObject = new SWIFT_App($_app);
     }
     if (!$_appObject) {
         throw new SWIFT_Config_Exception($_app . ' not found');
     }
     $_className = "SWIFT_Config_" . $_appObject->GetName();
     if (!class_exists($_className)) {
         $_configurationFile = $_appObject->GetDirectory() . DIRECTORY_SEPARATOR . SWIFT_APP::DIRECTORY_CONFIG . DIRECTORY_SEPARATOR . "class." . $_className . ".php";
         if (!file_exists($_configurationFile)) {
             throw new SWIFT_Config_Exception($_app . ' : configuration file does not exist.');
         }
         require_once $_configurationFile;
         if (!class_exists($_className)) {
             throw new SWIFT_Config_Exception("{$_app} : Could not locate  {$_className}");
         }
     }
     if (!defined("{$_className}::{$_key}")) {
         throw new SWIFT_Config_Exception("No constant {$_key} defined in {$_className}");
     }
     return constant("{$_className}::{$_key}");
 }
 /**
  * Test the API connection and return projects list
  *
  * @author Ashish Kataria
  */
 public function TestConnection()
 {
     $_SWIFT = SWIFT::GetInstance();
     $this->_freshbooksObject = new FreshBooksRequest('system.current');
     $this->_freshbooksObject->request();
     return $this->_freshbooksObject->success();
 }
 /**
  * Get Url to todo on basecmap
  *
  * @author Atul Atri
  *
  * @param Int $_todoProjectId project id where todo is posted
  * @param Int $_todoId todo id
  *
  * @return string basecamp Url to todo on basecmap
  */
 public static function BasecampTodoUrl($_todoProjectId, $_todoId)
 {
     $_SWIFT = SWIFT::GetInstance();
     $_basecampTodoUrl = SWIFT_ConfigManager::Get("BC_BASE_URL", 'basecamp') . SWIFT_ConfigManager::Get("TODO_SUB_URL", 'basecamp');
     $_accountId = $_SWIFT->Settings->Get('bc_base_acc_id');
     $_basecampTodoUrl = sprintf($_basecampTodoUrl, $_accountId, $_todoProjectId, $_todoId);
     return $_basecampTodoUrl;
 }
 /**
  * Insert a todo record
  *
  * @param int $_ticketId ticket id
  * @param int $_todoId   todo id
  * @param int $_pId      basecamp project id
  *
  * @return mixed result of SWIFT_Database::Execute
  */
 public static function insertTodo($_ticketId, $_todoId, $_pId)
 {
     $_Swift = SWIFT::GetInstance();
     $_dataArray = array();
     $_dataArray['ticketid'] = intval($_ticketId);
     $_dataArray['todoid'] = intval($_todoId);
     $_dataArray['projectid'] = intval($_pId);
     return $_Swift->Database->AutoExecute(TABLE_PREFIX . self::TABLE_NAME, $_dataArray);
 }
 /**
  * Intialize wrapper object and calls function send as action in post ajax request
  *
  * @author Ashish Kataria
  */
 public function Index()
 {
     // Create instance of SWIFT class
     $_SWIFT = SWIFT::GetInstance();
     // Create instance of freshbooks wrapper
     $this->_freshbooksWrapperObject = new SWIFT_FreshbooksWrapper();
     // Set freshbooks API Url and authentication token
     $this->_freshbooksWrapperObject->SetApiDetails($_SWIFT->Settings->Get('freshbooks_apiUrl'), $_SWIFT->Settings->Get('freshbooks_authenticationToken'));
     call_user_func(array(__CLASS__, $_POST['action']));
 }
 /**
  * Render the settings
  *
  * @author Abhinav Kumar
  *
  * @throws SWIFT_Exception If class is not loaded
  * @return bool
  */
 public function Index()
 {
     $_SWIFT = SWIFT::GetInstance();
     if (!$this->GetIsClassLoaded()) {
         throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);
     }
     $this->UserInterface->Header($this->Language->Get('jira') . ' > ' . $this->Language->Get('settings'), self::MENU_ID, self::NAVIGATION_ID);
     if ($_SWIFT->Staff->GetPermission('admin_canupdatesettings') == '0') {
         $this->UserInterface->DisplayError($this->Language->Get('titlenoperm'), $this->Language->Get('msgnoperm'));
     } else {
         $this->UserInterface->Start(get_class($this), '/JIRA/SettingsManager/Index', SWIFT_UserInterface::MODE_INSERT, false);
         $this->SettingsManager->Render($this->UserInterface, SWIFT_SettingsManager::FILTER_NAME, array('settings_bj'));
         $this->UserInterface->End();
     }
     $this->UserInterface->Footer();
     return true;
 }
 /**
  * Render the Verify Connection Dialog
  *
  * @author Ashish Kataria
  * @param $_msg The message to display
  * @param $_displayError To show error or not
  * @return bool "true" on Success, "false" otherwise
  */
 public function RenderConnectionButton($_msg, $_displayError = 0)
 {
     $_SWIFT = SWIFT::GetInstance();
     if (!$this->GetIsClassLoaded()) {
         return false;
     }
     // Calculate the URL
     $this->UserInterface->Start(get_class($this) . 'verifycon', '/Base/Settings/View', SWIFT_UserInterface::MODE_EDIT, true);
     $this->UserInterface->SetDialogOptions(false);
     if ($_displayError) {
         $this->UserInterface->Toolbar->AddButton('Ok', 'icon_jqmcompleted.png', 'javascript: UIDestroyAllDialogs(); SWIFT.Freshbooks.AdminObject.ConnectionButtonOk();', '4', '', '');
         $_statusImage = 'icon_check.gif';
         $_customClass = '';
     } else {
         $this->UserInterface->Toolbar->AddButton('Ok', 'icon_jqmcompleted.png', 'javascript: UIDestroyAllDialogs();', '4', '', '');
         $_statusImage = 'icon_block.gif';
         $_customClass = 'errorrow';
     }
     $this->UserInterface->Toolbar->AddButton($this->Language->Get('help'), 'icon_help.gif', SWIFT_Help::RetrieveHelpLink('parseremailqueue'), SWIFT_UserInterfaceToolbar::LINK_NEWWINDOW);
     /*
      * ###############################################
      * BEGIN GENERAL TAB
      * ###############################################
      */
     $_GeneralTabObject = $this->UserInterface->AddTab($this->Language->Get('tabgeneral'), 'icon_form.gif', 'general', true);
     $_columnContainer[0]['value'] = $_msg;
     $_columnContainer[0]['align'] = 'left';
     $_columnContainer[1]['value'] = '<img src="' . SWIFT::Get('themepath') . 'images/' . $_statusImage . '" align="absmiddle" border="0" />';
     $_columnContainer[1]['align'] = 'center';
     $_columnContainer[1]['width'] = '16';
     $_GeneralTabObject->Row($_columnContainer, $_customClass);
     /*
      * ###############################################
      * END GENERAL TAB
      * ###############################################
      */
     $this->UserInterface->End();
     return false;
 }
    /**
     * Renders the Issue History Tab
     *
     * @param mixed $_issuesContainer array of issues associated with current ticket
     *
     * @author Abhinav Kumar
     * @return boolean 'true' on success and 'false' otherwise
     * @throws SWIFT_Exception if class is not loaded
     */
    public function RenderHistoryTab($_issuesContainer)
    {
        $_SWIFT = SWIFT::GetInstance();
        $_JIRABridge = SWIFT_JIRABridge::GetInstance();
        if (!$this->GetIsClassLoaded()) {
            throw new SWIFT_Exception(__CLASS__ . ' ' . SWIFT_CLASSNOTLOADED);
        } else {
            if (!is_array($_issuesContainer)) {
                throw new SWIFT_Exception(SWIFT_INVALIDDATA);
            }
        }
        $this->UserInterface->Start(get_class($this), '', SWIFT_UserInterface::MODE_INSERT, false);
        $_IssueHistoryTabObject = new SWIFT_UserInterfaceTab($this->UserInterface, 'history', '', 1, 'history', false, false, 4, '');
        $_columnContainer = array();
        // Issue ID
        $_columnContainer[0]['value'] = $this->Language->Get('jira_issueid');
        $_columnContainer[0]['align'] = 'left';
        $_columnContainer[0]['width'] = '10';
        // Summary
        $_columnContainer[1]['value'] = $this->Language->Get('jira_summary');
        $_columnContainer[1]['align'] = 'left';
        $_columnContainer[1]['width'] = '100';
        // Updated
        $_columnContainer[3]['value'] = $this->Language->Get('jira_updated');
        $_columnContainer[3]['align'] = 'left';
        $_columnContainer[3]['width'] = '10';
        // Priority
        $_columnContainer[4]['value'] = $this->Language->Get('jira_priority');
        $_columnContainer[4]['align'] = 'left';
        $_columnContainer[4]['width'] = '10';
        // Status
        $_columnContainer[5]['value'] = $this->Language->Get('jira_status');
        $_columnContainer[5]['align'] = 'left';
        $_columnContainer[5]['width'] = '10';
        // Assigned To
        $_columnContainer[6]['value'] = $this->Language->Get('jira_assignedto');
        $_columnContainer[6]['align'] = 'left';
        $_columnContainer[6]['width'] = '10';
        // Action
        $_columnContainer[7]['value'] = $this->Language->Get('jira_action');
        $_columnContainer[7]['align'] = 'left';
        $_columnContainer[7]['width'] = '10';
        $_IssueHistoryTabObject->Row($_columnContainer, 'gridtabletitlerow');
        if (empty($_issuesContainer)) {
            $_columnContainer = array();
            $_columnContainer[0]['value'] = $this->Language->Get('jira_noissuefound');
            $_columnContainer[0]['align'] = 'left';
            $_columnContainer[0]['width'] = '100%';
            $_IssueHistoryTabObject->Row($_columnContainer);
            $_renderHTML = $_IssueHistoryTabObject->GetDisplayHTML(true);
            $_renderHTML .= '<script language="Javascript" type="text/javascript">';
            $_renderHTML .= 'ClearFunctionQueue();';
            $_renderHTML .= '</script>';
            echo $_renderHTML;
            return true;
        }
        foreach ($_issuesContainer as $_Issue) {
            $_columnContainer = array();
            $_issueURL = $_SWIFT->Settings->Get('bj_jiraurl') . 'browse/' . $_Issue->GetKey();
            // Key
            $_columnContainer[0]['value'] = '<a href="' . $_issueURL . '" target="_blank">' . htmlspecialchars($_Issue->GetKey()) . '</a>';
            $_columnContainer[0]['align'] = 'left';
            $_columnContainer[0]['width'] = '10';
            // Summary
            $_columnContainer[1]['value'] = '<a href="' . $_issueURL . '" target="_blank">' . IIF(strlen($_Issue->GetSummary()) > 100, htmlspecialchars(substr($_Issue->GetSummary(), 0, 100)) . '...', htmlspecialchars($_Issue->GetSummary())) . '</a>';
            $_columnContainer[1]['align'] = 'left';
            $_columnContainer[1]['width'] = '100';
            // Updated
            $_columnContainer[3]['value'] = htmlspecialchars(SWIFT_Date::EasyDate($_Issue->GetUpdated()) . IIF(SWIFT_Date::EasyDate($_Issue->GetUpdated()) == $this->Language->Get('edjustnow'), '', ' ago'));
            $_columnContainer[3]['align'] = 'left';
            $_columnContainer[3]['width'] = '10';
            // Priority
            $_columnContainer[4]['value'] = htmlspecialchars($_Issue->GetPriority());
            $_columnContainer[4]['align'] = 'left';
            $_columnContainer[4]['width'] = '10';
            // Status
            $_columnContainer[5]['value'] = htmlspecialchars($_Issue->GetStatus());
            $_columnContainer[5]['align'] = 'left';
            $_columnContainer[5]['width'] = '10';
            // Comments
            $_columnContainer[6]['value'] = htmlspecialchars($_Issue->GetAssignee());
            $_columnContainer[6]['align'] = 'left';
            $_columnContainer[6]['width'] = '10';
            // Unlink
            $_columnContainer[7]['value'] = '<a title="' . $this->Language->Get('postJIRAComment') . '" href="#" onclick="postJIRAComment(\'' . $_Issue->GetKey() . '\')">
										<img src="' . SWIFT::Get('swiftpath') . SWIFT_APPSDIRECTORY . '/jira/resources/icon-comment.gif' . '"/>
									  </a>' . ' | ' . '<a title="' . $this->Language->Get('jira_unlinkissue') . '" href="#" onclick="unlinkJIRAIssue(\'' . $_Issue->GetKey() . '\')">
										<img src="' . SWIFT::Get('swiftpath') . SWIFT_APPSDIRECTORY . '/jira/resources/edit_delete.png' . '"/>
									   </a>';
            $_columnContainer[7]['align'] = 'left';
            $_columnContainer[7]['width'] = '10';
            $_IssueHistoryTabObject->Row($_columnContainer, '', $_Issue->GetKey());
            //Fetch the issue comments now
            if ($_JIRABridge) {
                $_commentsContainer = $_JIRABridge->FetchAllCommentsBy('issuekey', $_Issue->GetKey());
                if (isset($_columnContainer) && _is_array($_commentsContainer)) {
                    $_renderedNotes = array();
                    foreach ($_commentsContainer as $_JIRAComment) {
                        $_renderedNotes[] = '<div class="notebackground">
											<div class="notecontainer">
												<div class="note">' . nl2br($_JIRAComment->GetRawBody(), true) . '</div>
											</div>
											<cite class="tip">
											<strong>
												<img border="0" align="absmiddle" src="' . SWIFT::Get('themepath') . 'images/icon_user2.png"/> ' . $_JIRAComment->GetAuthor() . ' ' . htmlspecialchars(SWIFT_Date::EasyDate($_JIRAComment->GetUpdated())) . ' ago
												</strong><div style="float: right; padding-right: 4px;"></div>
											</cite>
										</div>';
                    }
                    $_renderedNotes = implode('', $_renderedNotes);
                    $_commentContainer[0]['value'] = '<div class="allnotes">' . $_renderedNotes . '</div>';
                    $_commentContainer[0]['width'] = '100';
                    $_commentContainer[0]['align'] = 'left';
                    $_commentContainer[0]['colspan'] = '7';
                    $_commentContainer[0]['style'] = 'background: none repeat scroll 0pt 0pt #F6F1E7; padding: 0px;';
                    $_IssueHistoryTabObject->Row($_commentContainer, '', $_Issue->GetKey());
                }
            }
        }
        $_renderHTML = $_IssueHistoryTabObject->GetDisplayHTML(true);
        echo $_renderHTML;
        return true;
    }
 /**
  * Set settings values
  *
  * @author Ashish Kataria
  */
 public function SetSamlSsoSettings()
 {
     $_SWIFT = SWIFT::GetInstance();
     $this->_samlSsoSettings = new OneLogin_Saml_Settings();
     /**
      * When using Service Provider Initiated SSO, this URL asks the IdP to authenticate the user
      */
     $this->_samlSsoSettings->idpSingleSignOnUrl = rtrim($_SWIFT->Settings->Get('sso_url'), '\\/');
     /**
      * The certificate for the users account in the IdP
      */
     $this->_samlSsoSettings->idpPublicCertificate = file_get_contents($_SWIFT->Settings->Get('sso_cer'));
     /**
      * The URL where to the SAML Response/SAML Assertion will be posted
      */
     $this->_samlSsoSettings->spReturnUrl = SWIFT::Get('basepath') . '/Samlsso/Sso/Idp/Login';
     /**
      * Name of this application
      */
     $this->_samlSsoSettings->spIssuer = $_SWIFT->Settings->Get('sso_entityid');
     /**
      *  Tells the IdP to return the email address of the current user
      */
     $this->_samlSsoSettings->requestedNameIdFormat = OneLogin_Saml_Settings::NAMEID_EMAIL_ADDRESS;
 }
 /**
  * For setting values in cookie
  *
  * @author Ashish Kataria
  */
 private function SetCookies()
 {
     $_SWIFT = SWIFT::GetInstance();
     $this->Cookie->Set('sso_cookie', true);
     if ($_SWIFT->Settings->Get('sso_twitter_key') != '') {
         $this->Cookie->Set('sso_tw_key', $_SWIFT->Settings->Get('sso_twitter_key'));
     } else {
         $this->Cookie->Set('sso_tw_key', 0);
     }
     if ($_SWIFT->Settings->Get('sso_twitter_secret') != '') {
         $this->Cookie->Set('sso_tw_secret', $_SWIFT->Settings->Get('sso_twitter_secret'));
     } else {
         $this->Cookie->Set('sso_tw_secret', 0);
     }
     if ($_SWIFT->Settings->Get('sso_facebook_key') != '') {
         $this->Cookie->Set('sso_fb_key', $_SWIFT->Settings->Get('sso_facebook_key'));
     } else {
         $this->Cookie->Set('sso_fb_key', 0);
     }
     if ($_SWIFT->Settings->Get('sso_facebook_secret') != '') {
         $this->Cookie->Set('sso_fb_secret', $_SWIFT->Settings->Get('sso_facebook_secret'));
     } else {
         $this->Cookie->Set('sso_fb_secret', 0);
     }
 }
<?php

if (!isset($_COOKIE['SWIFT_sso_cookie'])) {
    $_SWIFT = SWIFT::GetInstance();
    $_COOKIE['SWIFT_sso_fb_key'] = $_SWIFT->Settings->Get('sso_facebook_key');
    $_COOKIE['SWIFT_sso_fb_secret'] = $_SWIFT->Settings->Get('sso_facebook_secret');
    $_COOKIE['SWIFT_sso_tw_key'] = $_SWIFT->Settings->Get('sso_twitter_key');
    $_COOKIE['SWIFT_sso_tw_secret'] = $_SWIFT->Settings->Get('sso_twitter_secret');
    $_COOKIE['SWIFT_sso_cookie'] = true;
}
$config = array('example-userpass' => array('exampleauth:UserPass', 'ashish:somepwd' => array('uid' => array('ashish'), 'fullname' => array('Ashish Kataria'), 'email' => array('*****@*****.**'), 'designation' => array('Sr. Software Engineer')), 'mahesh:somepwd' => array('uid' => array('mahesh'), 'fullname' => array('Mahesh Salaria'), 'email' => array('*****@*****.**'), 'designation' => array('Team Lead')), 'customer:somepwd' => array('uid' => array('customer'), 'eduPersonAffilation' => array('customer'))), 'twitter' => array('authtwitter:Twitter', 'key' => $_COOKIE['SWIFT_sso_tw_key'], 'secret' => $_COOKIE['SWIFT_sso_tw_secret']), 'facebook' => array('authfacebook:Facebook', 'api_key' => $_COOKIE['SWIFT_sso_fb_key'], 'secret' => $_COOKIE['SWIFT_sso_fb_secret']));
 /**
  * Modifies Authentication header in queued requests
  *
  * @author Atul Atri
  * @return void
  */
 private function ModifyAuthHeader()
 {
     $_SWIFT = SWIFT::GetInstance();
     $_authHeaderName = SWIFT_ConfigManager::Get('AUTH_HEADER_NAME');
     $_authHeaderValue = $_SWIFT->Settings->Get('bc_auth_token');
     foreach ($this->_reqQueue as &$_nextReq) {
         if (isset($_nextReq['headers']) && isset($_nextReq['headers'][$_authHeaderName])) {
             $_nextReq['headers'][$_authHeaderName] = $_authHeaderValue;
         }
     }
 }
 /**
  * Validate an array of input
  *
  * @author Atul Atri
  *
  * @param mixed $_data         data to be validated
  * @param array $_filterArray  array of filters to be applied
  *                             e.g.
  *                             $_filterArray = array(
  *                             array('float' , FILTER_FLAG_ALLOW_OCTAL | FILTER_FLAG_ALLOW_HEX, array(min_range => 1, max_range => 10), 'lang_key_invalid_float')
  *                             )
  * @param bool  $_breakOnError break on first error
  *                             '
  *
  * @return true if $_data passed all validations, false or array of errors if error strings are given
  * @throws SWIFT_Exception
  */
 public function IsValid($_data, array $_filterArray, $_breakOnError = true)
 {
     $_errorArray = array();
     $_ValidationFailed = false;
     foreach ($_filterArray as $_nextFilterConfig) {
         $_validatorId = null;
         $_flag = 0;
         $_options = array();
         $_errrorKey = null;
         if (is_string($_nextFilterConfig)) {
             $this->IsValidatorRegistered($_nextFilterConfig);
             $_validatorId = $_nextFilterConfig;
         } else {
             if (is_array($_nextFilterConfig)) {
                 if (isset($_nextFilterConfig[0])) {
                     $_validatorId = $_nextFilterConfig[0];
                     $this->IsValidatorRegistered($_validatorId);
                 }
                 if (isset($_nextFilterConfig[1])) {
                     $_flag = $_nextFilterConfig[1];
                     $this->IsFlagTypeValid($_flag, $_validatorId);
                 }
                 if (isset($_nextFilterConfig[2])) {
                     $_options = $_nextFilterConfig[2];
                     $this->IsOptionsTypeValid($_options, $_validatorId);
                 }
                 if (isset($_nextFilterConfig[3])) {
                     $_errrorKey = $_nextFilterConfig[3];
                 }
                 if (isset($_nextFilterConfig['error'])) {
                     $_errrorKey = $_nextFilterConfig['error'];
                 }
             }
         }
         if ($_validatorId) {
             $_validatorClass = $this->_validators[$_validatorId];
             /* @var $_validatorClass SWIFT_Filter_Interface */
             $_isValid = $_validatorClass::Filter($_data, $_validatorId, $_flag, $_options, self::FILTER_TYPE_VALIDATE);
             if (!$_isValid) {
                 $_ValidationFailed = true;
                 if ($_errrorKey) {
                     $_errorArray[] = SWIFT::GetInstance()->Language->Get($_errrorKey);
                 }
                 if ($_breakOnError) {
                     break;
                 }
             }
         } else {
             throw new SWIFT_Filter_Exception("Could not find valid validator name");
         }
     }
     if ($_ValidationFailed) {
         if (count($_errorArray) > 0) {
             return $_errorArray;
         }
         return false;
     }
     return true;
 }
 /**
  * Posts a remote link to JIRA
  *
  * @author Abhinav Kumar
  *
  * @param string $_issueKey  The JIRA issue key to the send to the request to
  * @param string $_ticketURL Kayako ticket URL for backlinking
  * @param string $_title     Remote link title
  * @param string $_summary   Remote link summary
  * @param int    $_status    Kayako ticket status
  *
  * @return bool "true" on Success, "false" otherwise
  * @throws SWIFT_Exception If the Class is not Loaded
  */
 public function PostRemoteLink($_issueKey, $_ticketURL, $_title = '', $_summary = '', $_status = 1)
 {
     if (!$this->GetIsClassLoaded()) {
         throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);
     }
     if (empty($_issueKey) || empty($_ticketURL)) {
         throw new SWIFT_Exception(SWIFT_INVALIDDATA);
     }
     if (!$this->IsIssueValid($_issueKey)) {
         throw new SWIFT_Exception('Invalid Issue');
     }
     $_SWIFT = SWIFT::GetInstance();
     $_apiURL = $this->_url . 'rest/api/latest/issue/' . $_issueKey . '/remotelink';
     $this->Client->SetURI($_apiURL);
     $_globalID = 'system=' . $_ticketURL;
     $objectPayload = ['url' => $_ticketURL, 'title' => $_title, 'icon' => ['url16x16' => SWIFT::Get('swiftpath') . '/favicon.ico', 'title' => SWIFT_PRODUCT]];
     if ($_SWIFT->Settings->Get('bj_includesubjectinlink')) {
         $objectPayload['summary'] = $_summary;
     }
     $_ticketStatusClosed = false;
     $_ticketStatusCache = $_SWIFT->Cache->Get('statuscache');
     if (_is_array($_ticketStatusCache)) {
         foreach ($_SWIFT->Cache->Get('statuscache') as $_ticketStatus) {
             if ($_ticketStatus['markasresolved']) {
                 $_ticketStatusClosed = $_ticketStatus['ticketstatusid'];
             }
         }
     }
     if ($_ticketStatusClosed && $_status == $_ticketStatusClosed) {
         $objectPayload['status'] = ['resolved' => true, 'icon' => ['url16x16' => SWIFT::Get('swiftpath') . '__modules/jira/resources/resolved.png', 'title' => $this->Language->Get('jira_ticketclosed'), 'link' => $_ticketURL]];
     }
     $this->Client->SetParameterPost('globalId', $_globalID);
     $this->Client->SetParameterPost('object', $objectPayload);
     $_Response = $this->Client->Request(SWIFT_HTTPBase::POST, $this->_connectionTimeout);
     if ($_Response && $_Response->isSuccessful()) {
         return true;
     } else {
         $_ResponseDecoded = json_decode($_Response->getBody());
         $_responseContainer = get_object_vars($_ResponseDecoded);
         return $_responseContainer['errorMessages'][0];
     }
 }
 /**
  * Checks todo export form data
  *
  * @author Atul Atri
  * @return bool "true" on Success, "false" otherwise
  */
 private function CheckTodoExportForm()
 {
     $_SWIFT = SWIFT::GetInstance();
     if (!SWIFT_Session::CheckCSRFHash($_POST['csrfhash'])) {
         SWIFT::Error($_SWIFT->Language->Get('titlecsrfhash'), $_SWIFT->Language->Get('msgcsrfhash'));
         return false;
     }
     $_pId = $_POST['todoproject'];
     $_todolistId = $_POST['todolist'];
     $_todo = trim($_POST['todoitem']);
     $_date = trim($_POST['duedate']);
     if (empty($_pId)) {
         $this->UserInterface->CheckFields('todoproject');
         $this->UserInterface->Error($this->Language->Get('basecamp_error_title'), $this->Language->Get('basecamp_empty_todoproject'));
         return false;
     }
     if (empty($_todolistId)) {
         $this->UserInterface->CheckFields('todlist');
         $this->UserInterface->Error($this->Language->Get('basecamp_error_title'), $this->Language->Get('basecamp_empty_todolist'));
         return false;
     }
     if (empty($_todo)) {
         $this->UserInterface->CheckFields('todoitem');
         $this->UserInterface->Error($this->Language->Get('basecamp_error_title'), $this->Language->Get('basecamp_empty_todo'));
         return false;
     }
     if (!empty($_date) && date('m/d/Y', strtotime($_date)) != $_date) {
         $this->UserInterface->CheckFields('duedate');
         $this->UserInterface->Error($this->Language->Get('basecamp_error_title'), $this->Language->Get('basecamp_empty_duedate'));
         return false;
     }
     return true;
 }
 /**
  * Does the actual initialization
  * Checks if $_Data is an array & $_key is a key then reads and sets the value
  * to the corresponding class attribute
  *
  * @author Abhinav Kumar
  *
  * @param string $_key        The key to read - This also relate to the class attribute
  * @param array  $_data       The associative array containing all the keys
  * @param bool   $_isRequired whether mandatory or not. If set to 'true' will throw an \SWIFT_Exception if no value is passed
  *
  * @return boolean 'TRUE' on success & 'FALSE' otherwise
  * @throws SWIFT_Exception
  */
 protected function SetFromArray($_key, $_data, $_isRequired)
 {
     if (!_is_array($_data)) {
         throw new SWIFT_Exception(SWIFT_INVALIDDATA);
     }
     if (array_key_exists($_key, $_data)) {
         // && $_data[$_key] != '')
         $_Var = '_' . $_key;
         $this->{$_Var} = $_data[$_key];
         return true;
     }
     if ($_isRequired) {
         $_SWIFT = SWIFT::GetInstance();
         $_SWIFT->Language->LoadApp('jira', 'jira');
         throw new SWIFT_Exception(__CLASS__ . '::' . $_key . $_SWIFT->Language->Get('jira_noempty'));
     }
     return false;
 }
 /**
  * Get Authentication token
  *
  * @param string $_refreshToken Refresh Token
  *
  * @return string json response return by user
  */
 public static function RefreshToken()
 {
     $_grantClassObject = new SWIFT_OAuth2RefreshTokenGrant();
     $_grantClassObject->SetParameterNames(array('grant_type' => 'type'));
     $_OAuth2Client = self::GetOAuthClient($_grantClassObject);
     $_extraParams = array('grant_type' => 'refresh');
     try {
         $_SWIFT = SWIFT::GetInstance();
         $_refreshToken = $_SWIFT->Settings->Get("bc_refresh_token");
         $_responseArr = $_OAuth2Client->GetRefreshToken($_refreshToken, $_extraParams, SWIFT_OAuth2GrantType_Interface::AUTH_TYPE_AUTHORIZATION_FORM);
         if ($_responseArr[SWIFT_APIHttp::SRV_CODE] == 200) {
             $_responseJson = $_responseArr[SWIFT_APIHttp::SRV_RESPONSE];
             $_responseJsonArr = json_decode($_responseJson, true);
             if (isset($_responseJsonArr['access_token'])) {
                 $_token = trim($_responseJsonArr['access_token']);
                 //save token in settings
                 $_isset = $_SWIFT->Settings->UpdateKey('settings', 'bc_auth_token', "Bearer {$_token}");
                 return $_isset;
             }
         }
     } catch (Exception $_e) {
         //do nothing
     }
     return false;
 }
 /**
  * Import the MailChimp Integration Settings
  *
  * @author Ruchi Kothari
  * @return bool "true" on Success, "false" otherwise
  */
 private function ImportSettings()
 {
     $_SWIFT = SWIFT::GetInstance();
     $this->Load->Library('Language:LanguageManager');
     $_languageIDList = SWIFT_Language::GetMasterLanguageIDList();
     try {
         $this->SettingsManager->Import('./' . SWIFT_APPSDIRECTORY . '/mailchimp/config/settings.xml');
     } catch (SWIFT_Exception $_SWIFT_ExceptionObject) {
     }
     // Adding merge language to first found master language
     if (_is_array($_languageIDList)) {
         $this->LanguageManager->Merge($_languageIDList[0], './' . SWIFT_APPSDIRECTORY . '/mailchimp/config/mailchimp.language.xml');
     }
     return true;
 }
 /**
  * Unlinks a JIRA issue with a Kayako ticket
  *
  * @author Abhinav Kumar
  *
  * @param string $_issueKey The issue key to be unlinked
  * @param int    $_ticketID
  *
  * @throws SWIFT_Exception
  * @return bool
  */
 public function Unlink($_issueKey, $_ticketID)
 {
     $_SWIFT = SWIFT::GetInstance();
     $_JIRABridge = SWIFT_JIRABridge::GetInstance();
     $_response = array();
     if (!$this->GetIsClassLoaded()) {
         throw new SWIFT_Exception(__CLASS__ . ' - ' . SWIFT_CLASSNOTLOADED);
     }
     if (!empty($_issueKey)) {
         $this->Load->Library('JIRA:JIRABridge', false, false, 'jira');
         $this->Language->LoadApp('jira', 'jira');
         if ($_JIRABridge) {
             $_JIRAIssue = $_JIRABridge->GetIssueBy('issuekey', $_issueKey);
             if ($_JIRAIssue && $_JIRAIssue instanceof SWIFT_JIRAIssueManager && $_JIRAIssue->GetIsClassLoaded()) {
                 $_unlinked = $_JIRABridge->UnlinkIssue($_issueKey, $_ticketID);
                 if ($_unlinked) {
                     $_SWIFT_TicketObject = SWIFT_Ticket::GetObjectOnID((int) $_ticketID);
                     if ($_SWIFT_TicketObject && $_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
                         SWIFT_TicketAuditLog::Create($_SWIFT_TicketObject, null, SWIFT_TicketAuditLog::CREATOR_STAFF, $_SWIFT->Staff->GetStaffID(), $_SWIFT->Staff->GetProperty('fullname'), SWIFT_TicketAuditLog::ACTION_UPDATESTATUS, $this->Language->Get('unlinkedFromJIRA') . ' - ' . $_JIRAIssue->GetKey(), SWIFT_TicketAuditLog::VALUE_STATUS);
                     }
                     $_response['code'] = 200;
                     $_response['message'] = 'success';
                 } else {
                     $_response['code'] = 500;
                     $_response['message'] = $_JIRABridge->GetErrorMessage();
                 }
             } else {
                 $_response['code'] = 500;
                 $_response['message'] = 'noissuekey';
             }
         } else {
             $_response['code'] = 500;
             $_response['message'] = $this->Language->Get('jira_error');
         }
     } else {
         $_response['code'] = 500;
         $_response['message'] = 'noissuekey';
     }
     echo json_encode($_response);
     return true;
 }
    /**
     * Renders Link Issue Form
     *
     * @param int $_ticketID The current ticket id
     *
     * @return boolean 'TRUE' on success and 'FALSE' otherwise
     * @throws SWIFT_Exception if class is not loaded or $_ticketID is not provided
     */
    public function RenderLinkIssueForm($_ticketID)
    {
        $_SWIFT = SWIFT::GetInstance();
        if (!$this->GetIsClassLoaded()) {
            throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);
        }
        if (empty($_ticketID)) {
            throw new SWIFT_Exception('Ticket ID' . $this->Language->Get('jira_noempty'));
        }
        $_ticketID = (int) $_ticketID;
        $this->Load->Library('Ticket:Ticket', false, false, APP_TICKETS);
        $_SWIFT_TicketObject = SWIFT_Ticket::GetObjectOnID($_ticketID);
        $_ticketPostContainer = $_SWIFT_TicketObject->GetTicketPosts();
        $_ticketPosts = array();
        foreach ($_ticketPostContainer as $_TicketPost) {
            $_creater = $_TicketPost->GetProperty('fullname');
            if ($_TicketPost->GetProperty('creator') == SWIFT_Ticket::CREATOR_STAFF) {
                $_staffDataStore = $_SWIFT->Staff->GetDataStore();
                $_creater = $_staffDataStore['grouptitle'];
            } else {
                if ($_TicketPost->GetProperty('creator') == SWIFT_Ticket::CREATOR_USER) {
                    $_creater .= ' (' . $this->Language->Get('jira_user') . ')';
                }
            }
            $_postedOn = SWIFT_Date::Get(SWIFT_Date::TYPE_DATETIME, $_TicketPost->GetProperty('dateline'));
            $_ticketPosts[] = $_creater . ' - ' . $_postedOn . PHP_EOL . strip_tags(trim($_TicketPost->GetDisplayContents())) . PHP_EOL;
        }
        $_ticketPosts = implode(PHP_EOL, $_ticketPosts);
        $_ticketPosts = '[' . $_SWIFT_TicketObject->GetProperty('ticketmaskid') . ']: ' . $_SWIFT_TicketObject->GetProperty('subject') . PHP_EOL . '==================================================' . PHP_EOL . PHP_EOL . $_ticketPosts;
        $this->UserInterface->Start(get_class($this), '/JIRA/Bug/ProcessLinkIssueForm', SWIFT_UserInterface::MODE_INSERT, true);
        $_buttonText = '<input type="button" name="submitbutton" id="%formid%_submit" class="rebuttonblue" onclick="processIssueLinking(\'%formid%\');PreventDoubleClicking(this);" value="' . $this->Language->Get('jira_save') . '" />
					<input type="button" name="submitbutton" id="%formid%_cancel" class="rebuttonred" onclick="javascript: $(\'.ui-icon-closethick\').click();" value="' . $this->Language->Get('jira_cancel') . '"/>';
        $this->UserInterface->OverrideButtonText($_buttonText);
        $_GeneralTabObject = $this->UserInterface->AddTab($this->Language->Get('tabgeneral'), SWIFT::Get('swiftpath') . '__modules/jira/resources/postbugtojira_b.gif', 'general', true, false);
        $this->Load->Library('JIRA:JIRABridge', false, false, 'jira');
        $_JIRABridge = SWIFT_JIRABridge::GetInstance();
        if (!$_JIRABridge) {
            echo $this->Language->Get('jira_error');
        }
        //Add form fields
        $_GeneralTabObject->Hidden('ticketId', $_ticketID);
        $_GeneralTabObject->Hidden('ticketkey', $_SWIFT_TicketObject->GetTicketDisplayID());
        $_GeneralTabObject->Text('jira_issue_id', $this->Language->Get('jira_issue_id'), $this->Language->Get('jira_issue_id_desc'), '', 'text', 60);
        $_GeneralTabObject->Title('<label for="description">' . $this->Language->Get('jira_description') . '</label><br/><span class="tabledescription">' . $this->Language->Get('jira_sensitive') . '</span>');
        $_GeneralTabObject->TextArea('description', '', $this->Language->Get('jira_description_desc'), $_ticketPosts, 3, 14);
        //Add Hidden fields - proves handy for Loading the view after update
        $this->UserInterface->Hidden('jira_ticketid', $_SWIFT_TicketObject->GetTicketID());
        $this->UserInterface->Hidden('jira_listtype', 'inbox');
        $this->UserInterface->Hidden('jira_departmentid', $_SWIFT_TicketObject->GetProperty('departmentid'));
        $this->UserInterface->Hidden('jira_ticketstatusid', $_SWIFT_TicketObject->GetProperty('ticketstatusid'));
        $this->UserInterface->Hidden('jira_tickettypeid', $_SWIFT_TicketObject->GetProperty('tickettypeid'));
        $this->UserInterface->End();
        return true;
    }
 /**
  * Render manage form
  *
  * @author Atul Atri
  *
  * @return bool "true" on Success, "false" otherwise
  */
 public function ManageForm()
 {
     //check if already autherised
     $_SWIFT = SWIFT::GetInstance();
     $_authHeader = $_SWIFT->Settings->Get('bc_auth_token');
     if ($_authHeader) {
         $this->Template->Assign('_alreadyAuthorised', true);
     } else {
         $this->Template->Assign('_alreadyAuthorised', false);
     }
     $this->Template->Assign('_settingsObj', $_SWIFT->Settings);
     $this->Template->Assign('_swiftpath', SWIFT::Get('swiftpath'));
     $this->Template->Assign('_Language', $this->Language);
     $this->Template->Assign('_UserInterface', $this->UserInterface);
     $_formTxt = '';
     $_redirectUrl = SWIFT::Get('basename') . '/basecamp/Manager/CodeRedirect';
     $this->Template->Assign('_redirectUrl', $_redirectUrl);
     //show only if user registered this application
     $_appName = $this->Settings->Get('bc_app_name');
     $_appEmail = $this->Settings->Get('bc_email');
     $_appId = $this->Settings->Get('bc_app_id');
     $_appSecret = $this->Settings->Get('bc_app_secret');
     if ($_appName || $_appEmail || $_appId || $_appSecret) {
         $_formTxt = $this->Language->Get('basecamp_update_app_txt');
         $_formTxt = sprintf($_formTxt, '<b>' . $_redirectUrl . '</b>');
         $_buttonTxt = 'basecamp_update_button';
     } else {
         $_formTxt = $this->Language->Get('basecamp_new_app_txt');
         $_bcCreatAppUrl = SWIFT_ConfigManager::Get('CREATE_APP_LNK');
         $_clickHere = $this->Language->Get('basecamp_click_here_lnk');
         $_bcCreateAppHref = "<b><a href='{$_bcCreatAppUrl}' target='_blank'>{$_clickHere}</a></b>";
         $_formTxt = sprintf($_formTxt, $_bcCreateAppHref, '<b>' . $_redirectUrl . '</b>');
         $_buttonTxt = 'basecamp_save_button';
     }
     $_authLink = false;
     if ($_appName && $_appEmail && $_appId && $_appSecret) {
         $_authLink = SWIFT_APIOauth2::GetAuthReqURL();
     }
     $this->Template->Assign('_authLink', $_authLink);
     $this->Template->Assign('_formTxt', $_formTxt);
     $this->Template->Assign('_buttonTxt', $_buttonTxt);
     $this->View->Assign('_buttonTxt', $_buttonTxt);
     $this->View->Assign('_appName', $_appName);
     $this->View->Assign('_appEmail', $_appEmail);
     $this->View->Assign('_appId', $_appId);
     $this->View->Assign('_appSecret', $_appSecret);
     $this->View->ManageForm(self::MENU_ID, self::NAV_ID);
     return true;
 }