Request a new token

@param array $userData
@return void
@todo Allow different delivery-methods, such as SMS?
6723
public function requestToken(array $userData) {
        if (empty($userData['email'])) {
            $this->_addError(
                sprintf(
                    __('%s is a required field'),
                    __('Email')
                )
            );
            return false;
        }

        $validator = new Zend_Validate_EmailAddress();
        if (!$validator->isValid($userData['email'])) {
            $this->_addError(
                sprintf(
                    __('%s is not a valid email address'),
                    __('Email')
                )
            );
            return false;
        }

        $userId = $this->_createOrFetchUserRecord($userData);
        $token  = $this->createOrUpdateAuthRecord($userId);

        $this->_sendTokenEmail($userData['email'], $userId, $token);
        $this->setRedirect($this->_getRedirectUrl());
    }
275108
protected function verifySecurityContextHash(array $tokenData, HttpRequest $httpRequest)
    {
        if (!isset($tokenData['securityContextHash'])) {
            return;
        }
        /** @var $actionRequest ActionRequest */
        $actionRequest = $this->objectManager->get(ActionRequest::class, $httpRequest);
        $this->securityContext->setRequest($actionRequest);
        if ($tokenData['securityContextHash'] !== $this->securityContext->getContextHash()) {
            $this->emitInvalidSecurityContextHash($tokenData, $httpRequest);
            throw new AccessDeniedException(sprintf('Invalid security hash!%sThis request is signed for a security context hash of "%s", but the current hash is "%s"',
                chr(10), $tokenData['securityContextHash'], $this->securityContext->getContextHash()), 1429705633);
        }
    }
30646
public function call($userData = array(), $verifyData = TRUE)
    {
	    if ($verifyData)
	    {
		    foreach (self::$_KEYS as $k)
		    {
			    if ((!array_key_exists($k, $this->_API)) || (empty($this->_API[$k])))
			    {
				    throw new \Exception($k . ' must be set.');
			    }
		    }
	    }

	    $defaults = array(
		    'CHARSET'       => 'UTF-8',
		    'METHOD'        => 'GET',
		    'URL'           => '/',
			'HEADERS'       => array(),
	        'DATA'          => array(),
	        'FAILONERROR'   => TRUE,
	        'RETURNARRAY'   => FALSE,
	        'ALLDATA'       => FALSE
	    );

	    if ($verifyData)
	    {
		    $request = $this->setupUserData(array_merge($defaults, $userData));
	    }
	    else
	    {
		    $request = array_merge($defaults, $userData);
	    }


	    // Send & accept JSON data
	    $defaultHeaders = array();
	    $defaultHeaders[] = 'Content-Type: application/json; charset=' . $request['CHARSET'];
	    $defaultHeaders[] = 'Accept: application/json';
	    if (array_key_exists('ACCESS_TOKEN', $this->_API))
	    {
		    $defaultHeaders[] = 'X-Shopify-Access-Token: ' . $this->_API['ACCESS_TOKEN'];
	    }

        $headers = array_merge($defaultHeaders, $request['HEADERS']);


	    if ($verifyData)
	    {
		    $url = 'https://' . $this->_API['API_KEY'] . ':' . $this->_API['ACCESS_TOKEN'] . '@' . $this->_API['SHOP_DOMAIN'] . $request['URL'];
	    }
	    else
	    {
		    $url = $request['URL'];
	    }

	    // cURL setup
        $ch = curl_init();
        $options = array(
            CURLOPT_RETURNTRANSFER  => TRUE,
            CURLOPT_URL             => $url,
            CURLOPT_HTTPHEADER      => $headers,
            CURLOPT_CUSTOMREQUEST   => strtoupper($request['METHOD']),
            CURLOPT_ENCODING        => '',
            CURLOPT_USERAGENT       => 'RocketCode Shopify API Wrapper',
            CURLOPT_FAILONERROR     => $request['FAILONERROR'],
            CURLOPT_VERBOSE         => $request['ALLDATA'],
            CURLOPT_HEADER          => 1
        );

	    // Checks if DATA is being sent
	    if (!empty($request['DATA']))
	    {
		    if (is_array($request['DATA']))
		    {
			    $options[CURLOPT_POSTFIELDS] = json_encode($request['DATA']);
		    }
		    else
		    {
			    // Detect if already a JSON object
			    json_decode($request['DATA']);
			    if (json_last_error() == JSON_ERROR_NONE)
			    {
				    $options[CURLOPT_POSTFIELDS] = $request['DATA'];
			    }
			    else
			    {
				    throw new \Exception('DATA malformed.');
			    }
		    }
	    }

        curl_setopt_array($ch, $options);

        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);


        // Data returned
        $result = json_decode(substr($response, $headerSize), $request['RETURNARRAY']);

        // Headers
        $info = array_filter(array_map('trim', explode("\n", substr($response, 0, $headerSize))));

        foreach($info as $k => $header)
        {
	        if (strpos($header, 'HTTP/') > -1)
	        {
                $_INFO['HTTP_CODE'] = $header;
                continue;
            }

            list($key, $val) = explode(':', $header);
            $_INFO[trim($key)] = trim($val);
        }


        // cURL Errors
        $_ERROR = array('NUMBER' => curl_errno($ch), 'MESSAGE' => curl_error($ch));

        curl_close($ch);

	    if ($_ERROR['NUMBER'])
	    {
		    throw new \Exception('ERROR #' . $_ERROR['NUMBER'] . ': ' . $_ERROR['MESSAGE']);
	    }


	    // Send back in format that user requested
	    if ($request['ALLDATA'])
	    {
		    if ($request['RETURNARRAY'])
		    {
			    $result['_ERROR'] = $_ERROR;
			    $result['_INFO'] = $_INFO;
		    }
		    else
		    {
			    $result->_ERROR = $_ERROR;
			    $result->_INFO = $_INFO;
		    }
		    return $result;
	    }
	    else
	    {
		    return $result;
	    }


    }
189538
protected function sendRequest(array $requestData): TransferInterface
    {
        $response = $this->adapter->sendRequest($requestData);

        return $this->converter->toTransactionResponseTransfer($response);
    }
214469
public static function createFromResponse($responseData)
    {
        $sendCode = new self(null, null);
        $sendCode->setRawResponseData($responseData)
            ->processResponse();

        if ($sendCode['status'] !== 0 && $sendCode['status'] !== '0') {
            throw new Exception($sendCode['err_msg']);
        }

        return $sendCode;
    }
1318487
public function requestRequestToken($data = array())
    {
        $config = new AnConfig(array('data' => $data));
        
        $config->append(array(
            'url' => $this->request_token_url,
            'data' => array('oauth_callback' => $this->getConsumer()->callback_url),
        ));
        
        $request = $this->getRequest($config);
        $response = $request->send();

        if ($response->successful()) {
            $result = $response->parseQuery();
            $_SESSION['oauth_token_secret'] = $result->oauth_token_secret;
        } else {
            $result = '';
        }

        return $result;
    }
1278424
public function updateCustomer(Update\RequestData $requestData)
    {
        $request = new Update\Request($requestData);

        return $this->sendRequest($request, Update\ApiResponse::class);
    }
1096046
public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
        global $DB, $PAGE;

        $request = new \stdClass();
        $request->userid = $userid;
        $request->requesteduserid = $requesteduserid;
        $request->timecreated = time();

        $request->id = $DB->insert_record('message_contact_requests', $request);

        // Send a notification.
        $userfrom = \core_user::get_user($userid);
        $userfromfullname = fullname($userfrom);
        $userto = \core_user::get_user($requesteduserid);
        $url = new \moodle_url('/message/pendingcontactrequests.php');

        $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
        $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);

        $message = new \core\message\message();
        $message->courseid = SITEID;
        $message->component = 'moodle';
        $message->name = 'messagecontactrequests';
        $message->notification = 1;
        $message->userfrom = $userfrom;
        $message->userto = $userto;
        $message->subject = $subject;
        $message->fullmessage = text_to_html($fullmessage);
        $message->fullmessageformat = FORMAT_HTML;
        $message->fullmessagehtml = $fullmessage;
        $message->smallmessage = '';
        $message->contexturl = $url->out(false);
        $userpicture = new \user_picture($userfrom);
        $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
        $message->customdata = [
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
            'actionbuttons' => [
                'accept' => get_string_manager()->get_string('accept', 'moodle', null, $userto->lang),
                'reject' => get_string_manager()->get_string('reject', 'moodle', null, $userto->lang),
            ],
        ];

        message_send($message);

        return $request;
    }
666931
public static function setUserAuthData(EntityAuthData $entityAuthData)
	{
		if(self::$_instance === NULL)
			throw new SonicRuntimeException('Sonic instance not initialized');
		
		self::$_instance->userAuthData = $entityAuthData;
		
		self::$_instance->setContext(Sonic::CONTEXT_USER);
		
		return self::$_instance;
	}
216256
public static function createFromResponse($responseData)
    {
        $messageStatus = new self(null);
        $messageStatus->setRawResponseData($responseData)
            ->processResponse();

        if ($messageStatus['status'] !== 0 && $messageStatus['status'] !== '0') {
            throw new Exception($messageStatus['err_msg']);
        }

        //show message status instead of integer status code
        $messageStatus['message_status'] = self::$messageStatusType[$messageStatus['message_status']];

        return $messageStatus;
    }
166079
private function set(array $postData)
    {
        return $this->putJson(sprintf(self::COMMUNITY_ENDPOINT . 'communities/%s', $this->id()), $postData);
    }
546675
protected function createWallet(array $shopData)
    {
        $userAccount = new UserAccount($shopData);

        $event = new CreateWallet(
            $userAccount
        );

        $this->dispatcher->dispatch(
            'before.wallet.create',
            $event
        );

        $walletInfo = $this->hipay->createFullUseraccountV2(
            $event->getUserAccount()
        );

        $this->dispatcher->dispatch(
            'after.wallet.create',
            $event
        );

        return $walletInfo;
    }
1214194
public function insertSuperUser(array $userData){

		if (empty($userData['login']) || empty($userData['password'])){
			throw new tao_install_utils_Exception("To create a super user you must provide at least a login and a password");
		}

		$superUserOntology = dirname(__FILE__) . "/../ontology/superuser.rdf";

		if (!@is_readable($superUserOntology)){
			throw new tao_install_utils_Exception("Unable to load ontology : ${superUserOntology}");
		}

		$doc = new DOMDocument();
		$doc->load($superUserOntology);

		foreach ($userData as $key => $value){
			$tags = $doc->getElementsByTagNameNS('http://www.tao.lu/Ontologies/generis.rdf#', $key);
			foreach ($tags as $tag){
				$tag->appendChild($doc->createCDATASection($value));
			}
		}
		return $this->insertLocalModel($doc->saveXML());
	}
420189
public static function mock(array $userData = []): self
    {
        $data = \array_merge([
            'SERVER_PROTOCOL'      => 'HTTP/1.1',
            'REQUEST_METHOD'       => 'GET',
            'SCRIPT_NAME'          => '',
            'REQUEST_URI'          => '',
            'QUERY_STRING'         => '',
            'SERVER_NAME'          => 'localhost',
            'SERVER_PORT'          => 80,
            'HTTP_HOST'            => 'localhost',
            'HTTP_ACCEPT'          => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
            'HTTP_ACCEPT_CHARSET'  => 'utf-8;q=0.7,*;q=0.3',
            'HTTP_USER_AGENT'      => 'MY Framework',
            'REMOTE_ADDR'          => '127.0.0.1',
            'REQUEST_TIME'         => \time(),
            'REQUEST_TIME_FLOAT'   => \microtime(true),
        ], $userData);

        return new static($data);
    }
542033
public function register(array $userData)
    {
        $alreadyCreatedUser = $this->findByEmail($userData['email']);

        if ($alreadyCreatedUser) {
            throw new OutOfBoundsException(
                'A user was already created with this email address.',
                self::EMAIL_NOT_UNIQUE
            );
        }

        $userEntity = new UserEntity;
        $userEntity->setEmail($userData['email'])
            ->setPassword($this->hashPassword($userData['password']))
            ->setCreated(time())
            ->setEnabled(true)
            ->setVerified(false);

        $user = $this->userMapper->persist($userEntity);

        $userToken = $this->createUserToken([
            'token_type_id' => TokenEntity::TYPE_VERIFY_REGISTRATION,
            'user_id'       => $user->getId(),
        ]);

        // Create the verify registration email
        $this->verifyRegistrationView->setToken($userToken);

        $email = $this->emailService->createFromArray([
            'recipient_email' => $user->getEmail(),
            'subject'         => 'Verify Your Account',
            'message'         => (string) $this->verifyRegistrationView,
        ]);

        $this->emailService->enqueueSendEmailJob($email);

        return $user;
    }
1042512
public function getRequest( array $requestPostData )
    {
        $requestProperties = array(
            'username'    => $requestPostData[1],
            'password'    => $requestPostData[2],
            'title'       => $requestPostData[3]['title'],
            'description' => $requestPostData[3]['description'],
            'keywords'    => $requestPostData[3]['mt_keywords'],
            'status'      => $requestPostData[3]['post_status'],
        );

        return new Request( $requestProperties );
    }
705742
public function UserQuery($SafeData = FALSE) {
      if ($SafeData) {
         $this->SQL->Select('u.UserID, u.Name, u.Photo, u.About, u.Gender, u.CountVisits, u.InviteUserID, u.DateFirstVisit, u.DateLastActive, u.DateInserted, u.DateUpdated, u.Score, u.Admin, u.Deleted, u.CountDiscussions, u.CountComments');
      } else {
         $this->SQL->Select('u.*');
      }
      $this->SQL->From('User u');
//      $this->SQL->Select('i.Name', '', 'InviteName')
//         ->From('User u')
//         ->Join('User as i', 'u.InviteUserID = i.UserID', 'left');
   }