/** * Returns all filters on a given txttools account * @global moodle_database $DB Moodle database controller * @param TxttoolsAccount $txttoolsAccount Account to search against * @return TxttoolsAccount Updated account object * @version 2012042301 * @since 2011070401 */ public function getFiltersForAccount(TxttoolsAccount $txttoolsAccount) { global $DB; $filters = $DB->get_records('block_moodletxt_filter', array('account' => $txttoolsAccount->getId())); // Iterate over filters and build beans foreach ($filters as $filter) { $filterObj = new MoodletxtInboundFilter($filter->account, $filter->type, $filter->value, $filter->id); $users = $DB->get_records_sql(self::$FETCH_INBOXES_SQL, array('filterid' => $filterObj->getId())); // Get links between filters and user inboxes foreach ($users as $user) { $filterObj->addDestinationUser(new MoodletxtBiteSizedUser($user->id, $user->username, $user->firstname, $user->lastname)); } $txttoolsAccount->addInboundFilter($filterObj); } return $txttoolsAccount; }
/** * Takes the vanilla object returned as a database row and creates a full-fledged * sent message object from it, complete with dependent beans, methods, the works * @param stdClass $stdObject Raw database-level data object * @return MoodletxtOutboundMessage Constructed message object * @version 2015062901 * @since 2011081101 */ private function convertStandardClassToBean($stdObject) { $defaultUser = new MoodletxtBiteSizedUser($stdObject->defaultuser, $stdObject->defaultusername, $stdObject->defaultfirst, $stdObject->defaultlast); $txttoolsAccount = new TxttoolsAccount($stdObject->txttoolsuser, $stdObject->description, $defaultUser, $stdObject->url, $stdObject->location); if (isset($stdObject->encrypted)) { $txttoolsAccount->setEncryptedPassword($stdObject->encrypted); } $messageOwner = new MoodletxtBiteSizedUser($stdObject->moodleuserid, $stdObject->moodleuser, $stdObject->firstname, $stdObject->lastname); $outboundMessage = new MoodletxtOutboundMessage($txttoolsAccount, $messageOwner, $stdObject->messagetext, $stdObject->timesent, $stdObject->type); if (isset($stdObject->scheduledfor)) { $outboundMessage->setScheduledTime($stdObject->scheduledfor); } if (isset($stdObject->id)) { $outboundMessage->setId($stdObject->id); } $eventCreated = $stdObject->fromevent == '1' ? true : false; $outboundMessage->setEventCreated($eventCreated); return $outboundMessage; }
/** * Method to ensure that all account names within the * module are outputted in the same manner * @param TxttoolsAccount $account * @return string Formatted display string * @version 2015062901 * @since 2011102401 */ public static final function formatAccountForDisplay($account) { $formatted = $account->getUsername(); $description = $account->getDescription(); if (isset($description) && !empty($description)) { $formatted = $formatted . " (" . $description . ")"; } $formatted = $formatted . " - " . $account->getUrl(); return $formatted; }
/** * Converts a basic object returned from the * Moodle DB layer into a full data type * @param object $standardClass DB record object * @return txttoolsAccount Converted acount * @version 2015062901 * @since 2011042601 */ private function convertStandardClassToBean($standardClass) { $defaultUser = new MoodletxtBiteSizedUser($standardClass->defaultuser, $standardClass->defaultusername, $standardClass->firstname, $standardClass->lastname); $txttoolsAccount = new TxttoolsAccount($standardClass->username, $standardClass->description, $defaultUser, $standardClass->url, $standardClass->location, $standardClass->creditsused, $standardClass->creditsremaining, $standardClass->outboundenabled, $standardClass->inboundenabled, $standardClass->accounttype, $standardClass->lastupdate, $standardClass->id); $txttoolsAccount->setEncryptedPassword($standardClass->password); return $txttoolsAccount; }
} else { $acc = $accountDAO->getUrlAndLocation(); $location = $acc->location; $url = $acc->url; } if ($accountDAO->accountNameExists((string) $formData->accountName, $url)) { $formErrors[] = get_string('erroraccountexists', 'block_moodletxt'); } else { if ($formData->accountCtxtInstance !== TxttoolsAccount::$UK_LOCATION && $formData->accountCtxtInstance !== TxttoolsAccount::$US_LOCATION && ($formData->accountCtxtInstance !== 'URL' && $formData->accountUrl)) { $formErrors[] = get_string('errorinvalidlocationorurl', 'block_moodletxt'); } else { $encrypter = new MoodletxtEncryption(); $key = get_config('moodletxt', 'EK'); $xmlController = MoodletxtOutboundControllerFactory::getOutboundController(MoodletxtOutboundControllerFactory::$CONTROLLER_TYPE_XML); $defaultUser = $userDAO->getUserById($formData->accountDefaultInbox); $txttoolsAccount = new TxttoolsAccount((string) $formData->accountName, (string) $formData->accountDescription, $defaultUser, $url, $location); $txttoolsAccount->setEncryptedPassword($encrypter->encrypt($key, $formData->accountPassword1, 20)); if ($location === 'URL') { $location = $xmlController->getServerLocation($txttoolsAccount); $txttoolsAccount->setLocation($location); } $txttoolsAccount = $xmlController->updateAccountInfo($txttoolsAccount); $accountDAO->saveTxttoolsAccount($txttoolsAccount); redirect($CFG->wwwroot . '/blocks/moodletxt/settings_accounts.php', get_string('redirectaccountsfound', 'block_moodletxt')); } } } catch (MoodletxtRemoteProcessingException $ex) { $connErrors['remoteError'] = $ex->getCode(); } catch (Exception $ex) { $connErrors['connectError'] = $ex->getCode(); }
/** * Increment's a user's outbound message stats for a given day * @TODO Expand these stats in 3.1 * @param TxttoolsAccount $txttoolsAccount Account message was sent through * @param object $user Moodle user object * @param int $numberSent Number of messages sent * @version 2012101101 * @since 2012101101 */ public function incrementUserOutboundStats(TxttoolsAccount $txttoolsAccount, object $user, $numberSent) { $this->incrementUserOutboundStatsById($txttoolsAccount->getId(), $user->id, $numberSent); }
/** * Builds authentication block. * Method to build an <Authentication> block for authenticating a request with the API * @param TxttoolsAccount $txttoolsAccount txttools account to authenticate against * @version 2011041501 * @since 2010090101 */ private function buildAuthentication($txttoolsAccount) { $outPass = $this->encrypter->decrypt(get_config('moodletxt', 'EK'), $txttoolsAccount->getEncryptedPassword()); // Set authentication block // Code written this way so the output is all nice and formatted $this->currentAuthentication = ' ' . MoodletxtXMLConstants::$REQUEST_AUTHENTICATION_BLOCK . ' ' . MoodletxtXMLConstants::$REQUEST_AUTHENTICATION_USERNAME . $txttoolsAccount->getUsername() . MoodletxtXMLConstants::$_REQUEST_AUTHENTICATION_USERNAME . ' ' . MoodletxtXMLConstants::$REQUEST_AUTHENTICATION_PASSWORD . $outPass . MoodletxtXMLConstants::$_REQUEST_AUTHENTICATION_PASSWORD . ' ' . MoodletxtXMLConstants::$_REQUEST_AUTHENTICATION_BLOCK; }
/** * Sends requests to txttools. * Takes an array of requests and shoves them to txttools, then grabs the responses and passes them back up to the calling object * @param array $requestArray Requests to send * @param TxttoolsAccount $ctxtAccount txttools account to use * @return array Unparsed response from txttools * @throws Exception * @throws HTTPException * @throws SocketException * @throws dml_exception * @version 2015062901 * @since 2011032901 */ public function sendData($requestArray, $ctxtAccount) { // If the parameter is not formatted as an array, make it one if (!is_array($requestArray)) { $requestArray = array($requestArray); } // Set defaults $pathPrefix = "https://"; $txttoolsHost = $ctxtAccount->getUrl(); $filePath = '/connectors/XML/xml.jsp'; $fullPath = $filePath; $connectionPrefix = 'ssl://'; $connectionHost = $txttoolsHost; $connectionPort = 443; // Get proxy details $proxyHost = get_config('moodletxt', 'Proxy_Host'); $proxyPort = get_config('moodletxt', 'Proxy_Port'); $proxyUsername = get_config('moodletxt', 'Proxy_Username'); $proxyPassword = get_config('moodletxt', 'Proxy_Password'); // Check for protocol if ($this->protocol != MoodletxtOutboundController::$CONNECTION_TYPE_SSL) { $connectionPort = 80; $pathPrefix = "http://"; $connectionPrefix = ''; } // If proxy details are set, override defaults if ($proxyHost != '' && $proxyPort != '') { $connectionHost = $proxyHost; $connectionPort = $proxyPort; $fullPath = "http://" . $txttoolsHost . $filePath; $connectionPrefix = ''; } $responseArray = array(); foreach ($requestArray as $request) { // Build URL-encoded string from XML request $poststring = "XMLPost=" . urlencode($request); // Build connection string $request = "POST " . $fullPath . " HTTP/1.0\r\n"; $request .= "Host: " . $txttoolsHost . "\r\n"; $request .= "User-Agent: " . $this->USER_AGENT . "\r\n"; if ($proxyHost != '' && $proxyPort != '') { $request .= "Proxy-Authorization: Basic " . base64_encode($proxyUsername . ":" . $proxyPassword) . "\r\n"; } $request .= "Content-type: application/x-www-form-urlencoded\r\n"; $request .= "Content-length: " . strlen($poststring) . "\r\n"; $request .= "Connection: close\r\n\r\n"; $request .= $poststring . "\r\n"; // error_log(get_string('logxmlblocksent', 'block_moodletxt') . "\r\n\r\n" . $request); // Open socket $fp = @fsockopen($connectionPrefix . $connectionHost, $connectionPort, $errorNo, $errorStr, $timeout = 30); if (!$fp) { throw new SocketException(); } else { // Send request to server fputs($fp, $request); // Get server response $response = ''; while (!feof($fp)) { $response .= @fgets($fp, 128); // Bug in PHP SSL handling causes problems here - suppress } fclose($fp); // Check that XML has been returned $XMLproc = '<?xml'; $checkForXML = strpos($response, $XMLproc); if ($checkForXML === false) { // If no XML is received, check for HTTP error codes // Uses only the txttools server, so safe to assume Apache,HTTP 1.1, Linux $responseCode = substr($response, 9, 3); throw new HTTPException('HTTP error encountered when sending.', $responseCode); } else { $response = substr($response, $checkForXML); } } // error_log(get_string('logxmlresponse', 'block_moodletxt') . "\r\n\r\n" . $response); // Push response from website onto response array array_push($responseArray, $response); } // Give responses back to parsers return $responseArray; }
/** * Build JSON response structure for an updated account * @param TxttoolsAccount $txttoolsAccount Account to build from * @return string Constructed JSON * @version 2012100801 * @since 2011061301 */ private function buildResponse(TxttoolsAccount $txttoolsAccount) { // Copy template down $response = $this->responseTemplate; $response['accountID'] = $txttoolsAccount->getId(); $response['username'] = $txttoolsAccount->getUsername(); $response['description'] = $txttoolsAccount->getDescription(); $response['creditsUsed'] = $txttoolsAccount->getCreditsUsed(); $response['creditsRemaining'] = $txttoolsAccount->getCreditsRemaining(); $response['updateTimeString'] = $txttoolsAccount->getLastUpdateFormatted(); $response['allowOutbound'] = $txttoolsAccount->isOutboundEnabled() ? 1 : 0; $response['allowInbound'] = $txttoolsAccount->isInboundEnabled() ? 1 : 0; $response['billingType'] = $txttoolsAccount->getBillingType(); // Include account restrictions if specified foreach ($txttoolsAccount->getAllowedUsers() as $allowedUser) { $response['allowedUsers'][$allowedUser->getId()] = array('firstName' => $allowedUser->getFirstName(), 'lastName' => $allowedUser->getLastName(), 'username' => $allowedUser->getUsername()); } // Include inbound filters if specified foreach ($txttoolsAccount->getInboundFilters() as $inboundFilter) { $response['inboundFilters'][$inboundFilter->getId()] = array('type' => $inboundFilter->getFilterType(), 'operand' => (string) $inboundFilter->getOperand(), 'inboxes' => array()); foreach ($inboundFilter->getDestinationUsers() as $biteSizedUser) { // No I'm not kidding. Fortunately these won't be included often $response['inboundFilters'][$inboundFilter->getId()]['users'][$biteSizedUser->getId()] = array('firstName' => $biteSizedUser->getFirstName(), 'lastName' => $biteSizedUser->getLastName(), 'username' => $biteSizedUser->getUsername()); } } return json_encode($response); }
/** * @param array $blacklistedNumbers * @param TxttoolsAccount $account * @version 2015062901 * @since 2015062901 */ private function syncDbWithResponse($blacklistedNumbers, $account) { $blacklistEntries = array(); foreach ($blacklistedNumbers as $number => $status) { $blacklistEntry = new BlacklistEntry(); $blacklistEntry->setPhoneNumber($number); $blacklistEntry->setIsBlacklisted(BlacklistDAO::$BLACKLISTED); $blacklistEntry->setAccountId($account->getId()); $blacklistEntries[] = $blacklistEntry; } $this->blacklistDAO->removeAllBlacklistEntriesForAccount($account->getId()); $this->blacklistDAO->saveBlacklistEntries($blacklistEntries); }