/** * @param $id * @return array */ public function find($id) { $url = $this->getResource() . "/{$id}"; $requestManager = new RequestManager($url, [], 'GET', $this->getHeader()); $requestManager->send(); return json_decode($requestManager->getHttpResponse(), true); }
/** * Gera uma URL para o site. * @param array $caminho Caminho cada item corresponde a um diretório. Ex: array('caminho','parametro') = http://seuprojeto.com/caminho/parametro/ * @param mixed $urlBase A BaseUrl para gerar a url. Por padrão é utilizado o baseUrl do contexto atual. * @return string A Url Gerada */ public function generateUrl($caminho = '', $urlBase = '') { //Caminho em branco para retornar por padrão a "home" $url = (empty($urlBase) ? $this->request->getBaseUrl() : $urlBase) . '/'; if (is_array($caminho)) { return $this->hydrateArrayToUrl($caminho, $url); } return $url . $caminho; }
private function fetchToken() { $requestManager = new RequestManager($this->loginUrl, ['client_id' => $this->keys['client_id'], 'client_secret' => $this->keys['client_secret'], 'grant_type' => $this->keys['grant_type'], 'resource' => $this->keys['resource']], 'POST', []); $requestManager->send(); $response = json_decode($requestManager->getHttpResponse()); if (isset($response->error)) { return null; } return $response; }
/** * Routes the request to appropriate controller and returns resource params * * @return Resource $resource */ public static function getResource() { $resource = new Resource(); $firstParam = RequestManager::getParam(RequestManager::FIRST_PARAM); $secondParam = RequestManager::getParam(RequestManager::SECOND_PARAM); $thirdParam = RequestManager::getParam(RequestManager::THIRD_PARAM); if (AuthController::isLoggedIn()) { if (empty($firstParam) && empty($secondParam) && empty($thirdParam)) { $resource->setKey(Constants::INDEX_URI_KEY); } else { $className = ucfirst($firstParam) . 'Controller'; if (class_exists($className) && is_subclass_of(new $className(), 'AbstractController')) { $resource->setKey($className::MODULE_KEY); } else { if (!empty($firstParam) && !empty($secondParam) && !empty($thirdParam)) { $resource->setKey(Constants::EXPLORER_URI_KEY); } else { $resource->setKey(Constants::INDEX_URI_KEY); } } } } else { $resource->setKey(Constants::AUTH_URI_KEY); if ($firstParam !== Constants::AUTH_URI_KEY) { RequestManager::setPendingRequestURI(); } } $resource = self::setCorrectParams($resource, array($firstParam, $secondParam, $thirdParam)); return $resource; }
/** * @see AbstractController::run() */ public function run(Resource $resource) { $uriParams = $resource->getParams(); $formParams = RequestManager::getAllParams(); $uc = new UserPreferencesController(); $uc->getUserPreference(Utils::getLoggedInUserId()); $this->populateProgramData($uriParams, $formParams); $this->getView()->setViewName(self::MODULE_KEY)->display(); }
/** * Display login form */ private function displayLoginForm() { if (!AuthController::isLoggedIn()) { $this->smarty->assign('LOGIN_ACTION_VALUE', AuthController::LOGIN_ACTION_VALUE); $this->render(AuthController::AUTH_LOGIN_KEY); } else { RequestManager::redirect(); } }
/** * @see AbstractController::run() */ public function run(Resource $resource) { $searchQuery = RequestManager::getParam(self::SEARCH_QUERY_PARAM); if (!empty($searchQuery)) { $results = $this->search($searchQuery); $this->setBean(array('query' => $searchQuery, 'resultSet' => $results)); $this->getView()->setViewName(self::MODULE_KEY)->display(); } else { RequestManager::redirect(); } }
public function run(Resource $resource) { $uriParams = $resource->getParams(); $formParams = RequestManager::getAllParams(); if (strtolower($uriParams[Constants::INPUT_PARAM_ACTION]) === 'save') { if ($this->saveUserPreference($formParams)) { Response::sendResponse(Constants::SUCCESS_RESPONSE, Messages::SUCCESS_UPDATE); } else { Response::sendResponse(Constants::SUCCESS_RESPONSE, Messages::ERROR_OPERATION_FAILED); } } }
/** * Loads an html document into a word document and downloads it to the client * @param string $path The path to the html document */ public static function HtmlToWord($path) { ob_start(); require_once $path; $document_script = ob_get_contents(); ob_end_clean(); if (RequestManager::IsAjaxRequest()) { RequestManager::ScriptResponseHeader(); echo 'jQuery("' . addslashes(str_replace(array("\r", "\n"), '', trim($document_script))) . '").wordExport()'; } else { echo '<script>jQuery("' . addslashes(str_replace(array("\r", "\n"), '', trim($document_script))) . '").wordExport()</script>'; } }
public function qrpay($out_trade_no, $total_amount, $subject) { $biz_content = "{\"out_trade_no\":\"" . $out_trade_no . "\","; $biz_content .= "\"total_amount\":\"" . $total_amount . "\",\"discountable_amount\":\"0.00\","; $biz_content .= "\"subject\":\"" . $subject . "\",\"body\":\"test\","; $biz_content .= "\"goods_detail\":[{\"goods_id\":\"apple-01\",\"goods_name\":\"ipad\",\"goods_category\":\"7788230\",\"price\":\"88.00\",\"quantity\":\"1\"},{\"goods_id\":\"apple-02\",\"goods_name\":\"iphone\",\"goods_category\":\"7788231\",\"price\":\"88.00\",\"quantity\":\"1\"}],"; $biz_content .= "\"operator_id\":\"op001\",\"store_id\":\"pudong001\",\"terminal_id\":\"t_001\","; $biz_content .= "\"timeout_express\":\"5m\"}"; echo $biz_content; $request = RequestManager::newInstance(Requests::AlipayTradePayRequest); $request->setBizContent($biz_content); $response = aopclient_request_execute($request); return $response; }
/** * Builds the email message and uses RequestManager to send a POST request * to the sendmail endpoint in the unified API. * * @param string $recipient The recipient of the email. * * @function sendWelcomeMail * @return Nothing, passes RuntimeException from RequestManager on error */ public static function sendWelcomeMail($recipient) { $emailBody = file_get_contents('MailTemplate.html'); // Use the given name if it exists, otherwise, use the alias $greetingName = isset($_SESSION['given_name']) ? $_SESSION['given_name'] : explode('@', $_SESSION['unique_name'])[0]; $emailBody = str_replace('{given_name}', $greetingName, $emailBody); // Build the HTTP request payload (the Message object). $email = "{\n Message: {\n Subject: 'Welcome to Office 365 development with PHP',\n Body: {\n ContentType: 'HTML',\n Content: '{$emailBody}'\n },\n ToRecipients: [\n {\n EmailAddress: {\n Address: '{$recipient}'\n }\n }\n ]\n },\n SaveToSentItems: true\n }"; // Send the email request to the sendmail endpoint, // which is in the following URI: // https://graph.microsoft.com/beta/me/sendMail // Note that the access token is attached in the Authorization header RequestManager::sendPostRequest(Constants::RESOURCE_ID . Constants::SENDMAIL_ENDPOINT, array('Authorization: Bearer ' . $_SESSION['access_token'], 'Content-Type: application/json;' . 'odata.metadata=minimal;' . 'odata.streaming=true'), $email); }
/** * Method for executing all the pre-display activities */ private function prepareDisplay() { $searchSuggestions = Session::get(Session::SESS_SEARCH_SUGGESTIONS); if (empty($searchSuggestions)) { $search = new SearchController(); $searchSuggestions = $search->getSearchSuggestions(); Session::set(Session::SESS_SEARCH_SUGGESTIONS, $searchSuggestions); } $this->smarty->assign('APP_NAME', Constants::APP_NAME); $this->smarty->assign('APP_LOGO', Constants::APP_LOGO); $this->smarty->assign('APP_VERSION', Constants::APP_VERSION); $this->smarty->assign('CSRF_TOKEN_NAME', Constants::CSRF_TOKEN_NAME); $this->smarty->assign('CSRF_TOKEN_VALUE', RequestManager::getCsrfToken()); $this->smarty->assign('SEARCH_SUGGESTIONS', $searchSuggestions); $this->smarty->assign('CHPWD_ACTION_VALUE', AuthController::CHPWD_ACTION_VALUE); }
/** * @see AbstractController::run() */ public function run(Resource $resource) { $uriParams = $resource->getParams(); $formParams = RequestManager::getAllParams(); if ($this->isDeleteRequest($uriParams, $formParams)) { $pid = $uriParams[Constants::INPUT_PARAM_PID]; if (!empty($pid) && is_numeric($pid)) { $this->deleteSource($pid); } } else { $pid = $uriParams[Constants::INPUT_PARAM_PID]; $language = $uriParams[Constants::INPUT_PARAM_LANG]; $category = $uriParams[Constants::INPUT_PARAM_CATE]; $this->exploreCode($language, $category, $pid); } }
/** * Contacts the token endpoint to get OAuth tokens including an access token * that can be used to send an authenticated request to the * Microsoft Graph. * It also stores user information, like given name, in session variables. * * @function acquireToken * @return Nothing, stores tokens in session variables. */ public static function acquireToken() { $tokenEndpoint = Constants::AUTHORITY_URL . Constants::TOKEN_ENDPOINT; // Send a POST request to the token endpoint to retrieve tokens. // Token endpoint is: // https://login.microsoftonline.com/common/oauth2/token $response = RequestManager::sendPostRequest($tokenEndpoint, array(), array('client_id' => Constants::CLIENT_ID, 'client_secret' => Constants::CLIENT_SECRET, 'code' => $_SESSION['code'], 'grant_type' => 'authorization_code', 'redirect_uri' => Constants::REDIRECT_URI, 'resource' => Constants::RESOURCE_ID)); // Store the raw response in JSON format. $jsonResponse = json_decode($response, true); // The access token response has the following parameters: // access_token - The requested access token. // expires_in - How long the access token is valid. // expires_on - The time when the access token expires. // id_token - An unsigned JSON Web Token (JWT). // refresh_token - An OAuth 2.0 refresh token. // resource - The App ID URI of the web API (secured resource). // scope - Impersonation permissions granted to the client application. // token_type - Indicates the token type value. foreach ($jsonResponse as $key => $value) { $_SESSION[$key] = $value; } // The id token is a JWT token that contains information about the user // It's a base64 coded string that has a header and payload $decodedAccessTokenPayload = base64_decode(explode('.', $_SESSION['id_token'])[1]); $jsonAccessTokenPayload = json_decode($decodedAccessTokenPayload, true); // The id token payload has the following parameters: // aud - Audience of the token. // exp - Expiration time. // family_name - User’s last name or surname. // given_name - User’s first name. // iat - Issued at time. // iss - Identifies the token issuer. // nbf - Not before time. The time when the token becomes effective. // oid - Object identifier (ID) of the user object // in Azure Active Directory (AD). // sub - Token subject identifier. // tid - Tenant identifier of the Azure AD tenant that issued the token. // unique_name - A unique identifier that can be displayed to the user. // upn - User principal name. // ver - Version. foreach ($jsonAccessTokenPayload as $key => $value) { $_SESSION[$key] = $value; } }
/** * @see AbstractController::run() */ public function run(Resource $resource) { $uriParams = $resource->getParams(); $formParams = RequestManager::getAllParams(); if (!$this->isEditRequest($formParams)) { if (is_numeric($uriParams[Constants::INPUT_PARAM_ACTION])) { $this->setBean(array('pid' => $uriParams[Constants::INPUT_PARAM_ACTION])); } else { $this->setBean(array('pid' => null)); } $this->getView()->setViewName(self::MODULE_KEY)->display(); } else { if (!$this->isUpdateRequest($formParams)) { $this->getModel()->submitCode($formParams); } else { $this->getModel()->updateCode($formParams); } } }
/** * @see AbstractController::run() */ public function run(Resource $resource) { $pid = RequestManager::getParam('id'); $this->execute($pid); }
/** * Downloads a file from the folder uploads * @param string $file * @return void */ public static function DownloadFile($file) { //This condition restricts downloads only for the uploads folder if (strpos($file, "/uploads/") !== false) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $file); finfo_close($finfo); header("Content-Type: " . $mime); header('Content-Disposition: attachment; filename="' . basename($file) . '"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: no-cache'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); } else { Logger::Error("Error downloading a file. The file url is " . $file); RequestManager::RequestError(); //Error on download, posible hacker attack... } }
// Dejo algunas variables globales utiles: /* * Directorio base de la aplicacion, donde se encuentra EntryPoint, * desde el cual se pueden calcular URLs relativas y absolutisarlas * concatenandoles el base_dir. Necesario para el helper de links. */ $_base_dir = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/')); $lg = Logger::getInstance(); $lg->setFile('log.log'); $lg->on(); // TODO: considerar el language de la app $ctx = YuppContext::getInstance(); $locale = $ctx->setLocale('en'); // Hace el request y catchea por posibles errores. try { RequestManager::doRequest(); } catch (Exception $e) { // FIXME: mostrar la vista de error 500 // FIXME: en modo PROD NUNCA deberia mostrar paths ni el stacktrace. // http://code.google.com/p/yupp/issues/detail?id=147 if (YuppConfig::getInstance()->getCurrentMode() === YuppConfig::MODE_PROD) { echo 'Disculpe las molestias, verificaremos el error en breve.'; // FIXME: i18n // Redirect a pagina de error por defecto? if (file_exists('ylogs/500')) { FileSystem::write('ylogs/500/err_' . date("Ymd.his") . '.log', print_r($ctx, true)); } } else { echo '<html><body>'; echo '<h1>Ha ocurrido un error!</h1>'; // TODO: i18n
require_once "framework/request.php"; $Request = new Request(); if (isset($Request->Get->file_download_url) && !empty($Request->Get->file_download_url)) { require_once "framework/filemanager.php"; FileManager::DownloadFile($Request->Get->file_download_url); } else { if (isset($Request->Get->print_document_type) && !empty($Request->Get->print_document_type)) { if ($Request->Get->print_document_type == "canvas" && isset($Request->Get->canvasID) && !empty($Request->Get->canvasID)) { require_once "framework/documentprint.php"; DocumentPrint::Canvas($Request->Get->canvasID); } else { if ($Request->Get->print_document_type == "canvas_to_pdf" && isset($Request->Get->canvasID) && !empty($Request->Get->canvasID)) { require_once "framework/documentprint.php"; DocumentPrint::CanvasToPDF($Request->Get->canvasID); } else { if ($Request->Get->print_document_type == "html" && isset($Request->Get->document_body) && !empty($Request->Get->document_body)) { require_once "framework/documentprint.php"; DocumentPrint::HtmlDocument($Request->Get->document_body); } else { if ($Request->Get->print_document_type == "html_bootstrap" && isset($Request->Get->document_body) && !empty($Request->Get->document_body)) { require_once "framework/documentprint.php"; DocumentPrint::HtmlDocumentBootstrapBased($Request->Get->document_body); } } } } } else { require_once "framework/requestmanager.php"; RequestManager::RequestHandler($Request); } }
function __construct(PDO $db, RequestManager $cpr, $debug = false) { $this->db = $db; $this->baseUrl = $cpr->getBaseUrl(); $this->debug = $debug; }
if (!RequestManager::IsAjaxRequest()) { ?> <script> <?php } ?> var dataUrl = document.getElementById('<?php echo $canvasID; ?> ').toDataURL(); var documentCanvas = '<!DOCTYPE html>'; documentCanvas += '<html>'; documentCanvas += '<head><title>Print Document Canvas</title></head>'; documentCanvas += '<body>'; documentCanvas += '<img style="display:block;margin-left:auto;margin-right:auto;" width="88%" src="' + dataUrl + '">'; documentCanvas += '</body>'; documentCanvas += '</html>'; var printWindow = window.open('','','width=800,height=600'); printWindow.document.open(); printWindow.document.write(documentCanvas); printWindow.document.close(); printWindow.focus(); printWindow.print(); printWindow.close(); <?php if (!RequestManager::IsAjaxRequest()) { ?> </script> <?php }
/** * Danger Notify Bootstrap * @param string $msg */ public static function Danger($msg) { if (RequestManager::IsAjaxRequest()) { RequestManager::ScriptResponseHeader(); ?> jQuery.Notify("<?php echo $msg; ?> ", "error") <?php } else { ?> <script>jQuery.Notify("<?php echo $msg; ?> ", "error")</script> <?php } }
//===================================================================// require_once 'Generics.php'; //===================================================================// // Variables // //===================================================================// /* The instance of the request manager controller that dispatches. */ $rqManager = NULL; /* The input data. */ $inputData = NULL; /* The outbound data stored in the model object. */ $responseObj = NULL; //===================================================================// // Main Routine // //===================================================================// // Construct the request manager. $rqManager = new RequestManager(); // Determine the incoming request type. if ($rqManager != Null) { switch ($_SERVER['REQUEST_METHOD']) { case 'GET': $inputData =& $_GET["request"]; break; case 'POST': $inputData =& $_POST["request"]; break; default: echo '{ "Response" : "InvalidData" }'; exit; break; } $inputData = json_decode($inputData, True);
/** * Log error in main log file and redirect to home page * * @param string $msg * @param string $type */ private function logErrorAndRedirect($msg, $type) { Logger::getLogger()->LogFatal($msg); RequestManager::redirect(); }
/** * Bootstrapping application */ public function init() { RequestManager::initRequest(); $this->requireCoreFiles(); RequestManager::serveRequest(); }
/** * Prompt Triple Bootstrap Dialog * @param string $input_msg1 Dialog message label for input #1 * @param string $input_msg2 Dialog message label for input #2 * @param string $input_msg3 Dialog message label for input #3 * @param string $callback Dialog javascript callback handler on button click * @return void */ public static function PromptTriple($input_msg1, $input_msg2, $input_msg3, $callback = "function(){}") { if (RequestManager::IsAjaxRequest()) { RequestManager::ScriptResponseHeader(); ?> Dialog.PromptTriple("<?php echo $input_msg1; ?> ", "<?php echo $input_msg2; ?> ", "<?php echo $input_msg3; ?> ", <?php echo $callback; ?> ) <?php die; } else { ?> <script>Dialog.PromptTriple("<?php echo $input_msg1; ?> ", "<?php echo $input_msg2; ?> ", "<?php echo $input_msg3; ?> ", <?php echo $callback; ?> )</script> <?php } }
public function updateEntity($id, $entityName, $valuePairs) { $dataToSend = json_encode($valuePairs); $url = "https://{$this->systemId}:{$this->apiKey}@r3.minicrm.hu/Api/R3/{$entityName}/{$id}"; // -d '$dataToSend'"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($valuePairs)); // Make the REST call, returning the result $response = curl_exec($curl); if (!$response) { print_r($response); echo 'NU O MERS<br/>'; //die("Connection Failure.n"); } else { echo 'O MERS<br/>'; print_r($response); } echo '<br/>'; echo '<br/>'; echo '<br/>'; echo 'Calling URL: ' . $url . '<br/>'; } } // https://27336:hqXPJH3sxDrupjEgMdYon6ewbNKGFRti@r3.minicrm.hu/Api/R3/Project/1950 $rm = new RequestManager(27336, 'hqXPJH3sxDrupjEgMdYon6ewbNKGFRti'); $args = array('Name' => 'ROYAL PRESIDENT SRL (Ionut)2'); $rm->updateEntity(1950, 'Project', $args);
$objEvent = $this->aEvents[$sEvent]; $objEvent->addHandler($xUserFunction); return true; } } } } return false; } /** * Generate a hash for the registered browser events * * @return string */
/** * Terminate current request processing, And redirects to home page * * @param string $msg */ public static function exitRequest($msg) { Logger::getLogger()->logError('Exiting Request: ' . $msg); RequestManager::redirect(); }
public static function registerToken($userId, $device = NULL, $CI = NULL) { if (is_null($CI)) { $CI =& get_instance(); } if (!empty($device)) { $deviceData = (array) json_decode($device); $CI->load->model('Device_model'); $existDevice = $CI->Device_model->get_by(array('secure_id' => $deviceData['secureId'])); if (empty($existDevice)) { $insertDevice = $CI->Device_model->create($deviceData); if ($insertDevice) { $existDevice = $CI->Device_model->get($insertDevice); } else { return FALSE; } } } $CI->load->model('User_token_model'); $time = Util::timeNow(); $token = self::generateToken($userId); $data = array('user_id' => $userId, 'device_id' => !empty($existDevice) ? $existDevice['id'] : NULL, 'ip_address' => RequestManager::getIpAddress(), 'login_time' => $time, 'last_activity' => $time, 'token' => $token, 'token_expired_time' => Util::timeAdd('+6 hours'), 'count_request' => 1, 'status' => self::STATUS_LOGIN); $insert = $CI->User_token_model->insert($data); if ($insert) { return $token; } else { return FALSE; } }