/** * 上传媒体文件. * * @param string $path * * @return string */ public function upload($path) { if (!file_exists($path) || !is_readable($path)) { throw new Exception("文件不存在或不可读 '{$path}'"); } $options = array('files' => array('media' => $path)); $contents = $this->http->post(self::API_UPLOAD, array(), $options); return $contents['url']; }
/** * * @param string $settlement_date * @param string $groupByCustomField * @return SettlementBatchSummary|Result\Error */ public function generate($settlement_date, $groupByCustomField = NULL) { $criteria = ['settlement_date' => $settlement_date]; if (isset($groupByCustomField)) { $criteria['group_by_custom_field'] = $groupByCustomField; } $params = ['settlement_batch_summary' => $criteria]; $path = $this->_config->merchantPath() . '/settlement_batch_summary'; $response = $this->_http->post($path, $params); if (isset($groupByCustomField)) { $response['settlementBatchSummary']['records'] = $this->_underscoreCustomField($groupByCustomField, $response['settlementBatchSummary']['records']); } return $this->_verifyGatewayResponse($response); }
static function push_to_repository($key, $module_name) { $source_file = new File(ModuleArchiver::MODULES_ARCHIVE_DIR . $module_name); $params = array(); $params["key"] = $key; $params["module_name"] = $module_name; $params["my_file"] = $source_file; Http::post(Config::instance()->MODULE_REPOSITORY_UPLOAD_URL, $params); }
/** * Efetuando a captura de uma transacao * Para efetuar a captura e necessario ja ter setado o tid e o merchid * ATENCAO: A seguinte variavel RECEIVEXML deve estar setada como 1 * no arquivo de configuracao (.ini) do cliente no servidor windows * * @return array('status' => bool, 'msg' => string); */ public function capturarTransacao() { if (!$this->getTid()) { throw new Exception('TID não está definido'); } if (!$this->getMerchid()) { throw new Exception('Merchid não está definido'); } if (!$this->getValorTransacao()) { throw new Exception('O valor da transação não foi definido'); } if (!$this->getWebservice()) { throw new Exception('Endereço do webservice não está definido'); } // parametros a seres passados para o webservice para efetuar a captura $params = array('tid' => $this->getTid(), 'merchid' => $this->getMerchid(), 'price' => $this->getValorTransacao()); $res = Http::post($this->getWebservice() . self::ACAO_CAPTURAR, $params); // caso o retorno nao seja xml, eh uma string com a descricao do erro if (strpos($res, 'xml') === false) { throw new Exception(strip_tags($res)); } $xml = simplexml_load_string($res); if (!is_object($xml)) { throw new Exception('Erro na comunicação com o webservice'); } switch (trim($xml->LR)) { case self::CAPTURA_SUCESSO: $msg = 'Captura realizada com sucesso.'; $status = false; break; case self::CAPTURA_JA_EFETUADA: $msg = 'Captura ja efetuada anteriormente.'; $status = true; break; case self::CAPTURA_NEGADA: $msg = 'Captura negada pelo Visanet.'; $status = false; break; case self::CAPTURA_ERRO: $msg = 'Ocorreu um erro ao efetuar a captura. (Verifique a existência do TID)'; $status = false; break; case self::CAPTURA_EXCEDEU_LIMITE_DIAS: $msg = 'Excedeu o limite de dias da autorizacao'; $status = false; break; default: $msg = isset($xml->ARS) && !empty($xml->ARS) ? $xml->ARS : 'Nao foi possivel identificar o status da captura'; $status = false; break; } return array('status' => $status, 'msg' => $msg); }
/** * 完善daemon处理函数,此函数必备 * * */ function daemonFunc() { require dirname(__FILE__) . '/../../config/testUI/config.php'; $redis = new Predis\Client($_config['redis_server']); $http = new Http(); while ($this->subProcessCheck()) { //处理队列 $case_data = $redis->lpop($_config['queue_name']); if (empty($case_data)) { break; } else { $arr = json_decode($case_data, true); $url = $arr['host'] . $arr['url']; $query = $arr['param']; $method = strtoupper($arr['method']); //拼装表单提交数据 $formdata = array(); $temp_arry = explode('&', $query); foreach ($temp_arry as $item) { list($k, $v) = explode('=', $item); $formdata[$k] = $v; } //判断是否需要token if (isset($arr['token'])) { $formdata['token'] = $arr['token']; } if ($method == 'GET') { $http->get($url, $formdata); } else { $http->post($url, $formdata); } $res = $http->getContent(); //此处增加返回结果的判断 $result = $arr['result']; if ($result == $res) { $res_test = 1; } else { $res_test = 0; } // $req['url'] = $url; // $req['data'] = $formdata; //$result =array(); file_put_contents(realpath(dirname(__FILE__)) . '/../../output/testUI.log', $res_test . '|' . $result . '|' . $res . '|' . $url . '|' . json_encode($formdata) . "\n", FILE_APPEND); } //增加处理数,不增加处理数,就需要子进程本身有退出机制。 //$this->requestCount++; //释放时间片 usleep(5000); } }
/** * 上传媒体文件. * * @param string $type * @param string $path * @param array $params * * @return string */ protected function upload($type, $path, $params = []) { if (!file_exists($path) || !is_readable($path)) { throw new Exception("文件不存在或不可读 '{$path}'"); } if (!in_array($type, $this->allowTypes, true)) { throw new Exception("错误的媒体类型 '{$type}'"); } $queries = ['type' => $type]; $options = ['files' => ['media' => $path]]; $url = $this->getUrl($type, $queries); $response = $this->http->post($url, $params, $options); $this->forever = false; return $response['media_id']; }
public function update() { $group = Http::post("group"); $group_id = Http::post("group_id"); $permissions = Http::post("permission"); $permission_model = DB::loadModel("users/permissions"); $group_model = DB::loadModel("users/groups"); $group_model->updateGroup($group_id, $group); $pids = array(); foreach ($permissions as $id => $val) { $pids[] = $id; } $permission_model->setPermissions($group_id, $pids); Http::redirect("/user_groups"); }
function send($recipients, $headers, $body) { global $wgVersion; $this->_sanitizeHeaders($headers); $headerElements = $this->prepareHeaders($headers); list($from, $textHeaders) = $headerElements; foreach ($recipients as $recipient) { if (version_compare($wgVersion, '1.16', '>=')) { $status = Http::post("http://theschwartz/theschwartz/inject", array("postData" => array("rcpt" => "{$recipient}", "env_from" => $from, "msg" => "{$textHeaders}" . "\n\n" . "{$body}"))); } else { $status = Http::post("http://theschwartz/theschwartz/inject", 'default', array(CURLOPT_POSTFIELDS => array("rcpt" => "{$recipient}", "env_from" => $from, "msg" => "{$textHeaders}" . "\n\n" . "{$body}"))); } wfDebugLog("enotif", __METHOD__ . ": injecting http://theschwartz/theschwartz/inject with params: {$recipient} {$from} {$headers['Subject']}", true); } }
function auth() { $user = is_null($this->registry->get("user")) ? new User() : $this->registry->get("user"); if ($user->logged === false) { $user->login = !is_null(Http::post("login")) ? Http::post("login") : ""; $user->password = !is_null(Http::post("password")) ? Http::post("password") : ""; if ($user->login == "sa" && $user->password == "sa") { $this->registerModule("admin/system/system", "center_side"); $this->display(); exit; } $user->auth(); } Http::redirect("/"); }
public function update() { $user = Http::post("user"); $user_id = Http::post("user_id"); $user["is_admin"] = $user["is_admin"] == "on" ? 1 : 0; $groups = Http::post("groups"); $groups_ids = array(); foreach ($groups as $id => $group) { $groups_ids[] = $id; } $user_model = DB::loadModel("users/user"); $user_groups_model = DB::loadModel("users/groups"); $user_model->update($user_id, $user); $user_groups_model->setGroups($user_id, $groups_ids); Http::redirect("/users"); }
public function execute() { global $wgDevelEnvironment, $wgFlowerUrl; if ($wgDevelEnvironment) { \Wikia\Logger\WikiaLogger::instance()->setDevModeWithES(); } \Wikia\Logger\WikiaLogger::instance()->pushContext(['task_id' => $this->mOptions['task_id']]); $runner = new TaskRunner($this->mOptions['wiki_id'], $this->mOptions['task_id'], $this->mOptions['task_list'], $this->mOptions['call_order'], $this->mOptions['created_by']); ob_start(); $runner->run(); $result = $runner->format(); if ($runner->runTime() > TaskRunner::TASK_NOTIFY_TIMEOUT) { Http::post("{$wgFlowerUrl}/api/task/status/{$this->mOptions['task_id']}", ['noProxy' => true, 'postData' => json_encode(['kwargs' => ['completed' => time(), 'state' => $result->status, 'result' => $result->status == 'success' ? $result->retval : $result->reason]])]); } ob_end_clean(); echo json_encode($result); }
/** * 调用纳客接口. * * @param string $_method 接口方法名 * @param array $data 发送的数据 */ public function callnake($_method, array $data = array()) { //实际请求地址 $url = trim($this->interfaceUrl, '/ \\/') . '/Interface/GeneralInterfaceHandler.ashx'; //请求方法名加入到参数中 $data['do'] = $_method; //如果是商盟旗舰版,则参数中加入店铺ID if ($this->luckVersion === self::LUCK_VERSION_ULTIMATE) { $data['ShopID'] = $this->shopId; } //数据 foreach ($data as $key => $value) { $data[$key] = $this->encryptor->encrypt($value); } //企业代码不加密 $data['CompCode'] = $this->companyCode; $this->result = $this->http->post($url, $data); return $this->result; }
/** * Execute the job * * @return bool */ public function run() { //sleep() could be added here to reduce unnecessary use $ill = $this->params['ill']; foreach ($ill as $lang => $pages) { $iw = Interwiki::fetch($lang); if (!$iw) { continue; } $apiUrl = $iw->getAPI(); if (!$apiUrl) { continue; } $apiUrl .= '?' . wfArrayToCGI(array('action' => 'purge', 'format' => 'json', 'titles' => implode('|', array_keys($pages)))); Http::post($apiUrl); //TODO: error handling } return true; }
function upload($v1, $v2) { $url = "http://sensor.aqicn.org/sensor/"; $time = time(); $data = array(array("t" => $time, "v" => $v1, "id" => 1), array("t" => $time, "v" => $v2, "id" => 2)); $post = array("key" => DylosReaderConf::$sensorKey, "id" => DylosReaderConf::$sensorId, "clientVersion" => 2, "ip" => exec("/sbin/ifconfig wlan0 | grep 'inet addr:' | cut -d: -f2"), "mem" => memory_get_usage(), "data" => $data); $res = Http::post($url, json_encode($post)); $json = json_decode($res); $path = realpath(dirname(__FILE__)) . "/logs/"; mkdir($path); $filename = $path . "upload.dylos.pending.json"; if (!isset($json->result) || $json->result != "ok") { $this->log("Postponning '" . json_encode($post) . "'\nServer says '{$res}'\n"); $list = file_exists($filename) ? json_decode(file_get_contents($filename)) : array(); file_put_contents($filename, json_encode(array_merge($list, $data))); } else { $this->log("Posted '" . json_encode($post) . "'.\nServer said '{$res}'\n"); if (file_exists($filename)) { $data = json_decode(file_get_contents($filename)); $post = array("key" => DylosReaderConf::$sensorKey, "id" => DylosReaderConf::$sensorId, "clientVersion" => 2, "mem" => memory_get_usage(), "data" => $data); $res = Http::post($url, json_encode($post)); $this->log("Reposting ... Server says '{$res}'\n"); $json = json_decode($res); if (!isset($json->result) || $json->result != "ok") { /* In case the upload does not work, try 3 times before failing */ $this->retryUpload++; if ($this->retryUpload < 3) { return; } $time = time(); $tmpfile = $path . "errlog.dylos.failed." . $time; file_put_contents($tmpfile, $res); $tmpfile = $path . "upload.dylos.failed." . $time; file_put_contents($tmpfile, json_encode($data)); } unlink($filename); $this->retryUpload = 0; } } }
function save() { $database = Http::post("database"); $database_external = Http::post("database_external"); $auth = Http::post("auth"); $ad_server = Http::post("ad_server"); if (!is_null($database) && !is_null($database_external) && !is_null($auth) && !is_null($ad_server)) { $config = new Config(); $config->set("/settings/database/host", $database["host"]); $config->set("/settings/database/name", $database["name"]); $config->set("/settings/database/user", $database["user"]); $config->set("/settings/database/pass", $database["pass"]); $config->set("/settings/database_external/host", $database_external["host"]); $config->set("/settings/database_external/name", $database_external["name"]); $config->set("/settings/database_external/user", $database_external["user"]); $config->set("/settings/database_external/pass", $database_external["pass"]); $config->set("/settings/auth/mode", $auth["mode"]); $config->set("/settings/ad_server/address", $ad_server["address"]); $config->set("/settings/ad_server/account_sufix", $ad_server["account_sufix"]); $config->set("/settings/ad_server/base_dn", $ad_server["base_dn"]); } Http::redirect("/system"); }
public function execute() { $apiURL = 'http://en.wikipedia.org/w/api.php'; $revisions = explode(',', $this->getArg(0)); // Retrieve original revisions and their predecessors $requestData = array('format' => 'php', 'action' => 'query', 'prop' => 'revisions', 'revids' => implode('|', $revisions)); $originalData = Http::post($apiURL, array('postData' => $requestData)); $data = unserialize($originalData); $pages = $data['query']['pages']; foreach ($pages as $page) { if (count($page['revisions']) != 1) { continue; } $revid = $page['revisions'][0]['revid']; $newRequest = array('format' => 'php', 'action' => 'query', 'prop' => 'revisions', 'titles' => $page['title'], 'rvstartid' => $revid, 'rvlimit' => 2, 'rvprop' => 'ids|content|user'); $newData = Http::post($apiURL, array('postData' => $newRequest)); $newData = unserialize($newData); $oldText = ''; $newText = ''; $allData = $newData['query']['pages']; $pageData = array_shift($allData); if (count($pageData['revisions']) == 2) { $revision1 = $pageData['revisions'][0]; $revision2 = $pageData['revisions'][1]; $oldText = trim($revision2['*']) . "\n"; $newText = trim($revision1['*']) . "\n"; } elseif (count($pageData['revisions']) == 1) { $revision1 = $pageData['revisions'][0]; $newText = trim($revision1['*']) . "\n"; $oldText = ''; } $user = $pageData['revisions'][0]['user']; print "http://en.wikipedia.org/w/index.php?diff=prev&oldid={$revid}\n"; EchoDiscussionParser::getInterestedUsers($oldText, $newText, $user); // FIXME: getInterestedUsers() is undefined } }
public function act_accountInforIntegation() { $dpId = $_REQUEST['dpId']; $developerMod = M('Developer'); if (!$dpId) { self::$errMsg['12000'] = "未获取到该用户的ID,无法同步信息至开放系统!"; return false; } $basInfoSta = $developerMod->getDeveloper("*", "id = " . $dpId); if (!empty($basInfoSta)) { $sendInfor = array("username" => $basInfoSta[0]['app_key'], "password" => $basInfoSta[0]['login_pwd'], "token" => $basInfoSta[0]['token'], "groupid" => 10, "email" => $basInfoSta[0]['email'], "mobile" => $basInfoSta[0]['phone'], "qq" => '', "address" => $basInfoSta[0]['address2'] . " " . $basInfoSta[0]['address'], "company" => $basInfoSta[0]['company'], "status" => $basInfoSta[0]['status'], "regtime" => $basInfoSta[0]['create_time'], "regip" => '', "logintime" => '', "loginip" => ''); } else { self::$errMsg[10131] = get_promptmsg(10131, '分销商'); return false; } $synStatus = array(); //开始同步到开放系统 外网 include_once WEB_PATH . 'lib/service/http.php'; $http = new Http('http://idc.open.valsun.cn/admin_open/openInterface.php'); $http->addPostParam(array('distributionBasicInfor' => json_encode($sendInfor))); $http->addHeader("Author:zoujunrong"); if (!$http->post()) { //如果是javascript请求,输出是给javascript的,可能就需要对输出转码 self::$errMsg[10145] = get_promptmsg(10145, $http->err_str); return false; } else { // echo $http->getResponse('header')."---header<br/>"; $synStatus["outOpenSystem"] = $http->getContent(); } //开始同步到开放系统 外网 $http->setURL('http://open.valsun.cn:88/admin_open/openInterface.php'); $http->addPostParam(array('distributionBasicInfor' => json_encode($sendInfor))); $http->addHeader("Author:zoujunrong"); if (!$http->post()) { //如果是javascript请求,输出是给javascript的,可能就需要对输出转码 self::$errMsg[10146] = get_promptmsg(10146, $http->err_str); return false; } else { // echo $http->getResponse('header')."---header<br/>"; $synStatus["innerOpenSystem"] = $http->getContent(); } return $synStatus; }
/** * 上传封面图片 * * @param string $id * @param string $image * @return boolean|string */ public function image($id, $image) { $data = ['activityId' => $id, 'method' => 'letv.cloudlive.activity.modifyCoverImg']; $data = $this->makeParams($data); $data['file'] = '@' . $image; $http = new Http(); $result = $http->post($this->url, $data); $result = json_decode($result, true); if (isset($result['errCode'])) { $this->e = $result; return false; } return $result['coverImgUrl']; }
private function refreshToken() { $parameter = array("client_id" => $this->client_id, "client_secret" => $this->client_secret, "grant_type" => 'refresh_token', "refresh_token" => $this->refresh_token); try { $result = json_decode(Http::post(self::ACCESS_TOKEN_URL, $parameter)); if (isset($result->error)) { $error = $result->error; throw new UploadException($error->description, $error->code); } } catch (UploadException $e) { echo $e->getError(); exit; } return $result; }
/** * @return string * @throws GWTAuthenticationException */ private function getAuthToken() { $cacheKey = $this->mEmail; return WikiaDataAccess::cache($cacheKey, 60 * 60, function () { $content = Http::post('https://www.google.com/accounts/ClientLogin', array('postData' => array("Email" => $this->mEmail, "Passwd" => $this->mPass, "accountType" => $this->mType, "source" => $this->mSource, "service" => $this->mService))); if (preg_match('/Auth=(\\S+)/', $content, $matches)) { return $matches[1]; } else { throw new GWTAuthenticationException(); } }); }
/** * Show the special page * * @param $par Mixed: parameter passed to the page or null */ public function execute($par) { global $wgOut, $wgRequest, $wgDevelEnvironment; // Set page title and other stuff $this->setHeaders(); $wgOut->setPageTitle('Special:Healthcheck'); // for faster response $wgOut->setArticleBodyOnly(true); $statusCode = 200; $statusMsg = self::STATUS_MESSAGE_OK; if ($wgRequest->wasPosted() && $wgRequest->getVal(self::POST_PARAM_GET)) { $testValue = $wgRequest->getVal(self::POST_PARAM_GET); if (empty($testValue) || $testValue != $wgRequest->getVal(self::POST_PARAM_POST)) { $statusCode = 503; $statusMsg = "Server status is: NOT OK - POST data incorrect"; } $wgOut->setStatusCode($statusCode); $wgOut->addHTML($statusMsg); return; } $maxLoad = $wgRequest->getVal('maxload'); $cpuCount = $this->getCpuCount(); $load = sys_getloadavg(); if ($cpuRatio = $wgRequest->getVal('cpuratio')) { $maxLoad = $cpuCount * $cpuRatio; } $wgRequest->response()->header("Cpu-Count: {$cpuCount}"); $wgRequest->response()->header("Load: " . implode(", ", $load)); $wgRequest->response()->header("Max-Load: {$maxLoad}"); if ($maxLoad) { if ($load[0] > $maxLoad || $load[1] > $maxLoad || $load[2] > $maxLoad) { $statusCode = 503; $statusMsg = "Server status is: NOT OK - load ({$load['0']} {$load['1']} {$load['2']}) > {$maxLoad} (cpu = {$cpuCount})"; } } if (file_exists("/usr/wikia/conf/current/host_disabled") || file_exists("/etc/disabled/apache")) { # failure! $statusCode = 503; $statusMsg = 'Server status is: NOT OK - Disabled'; } // Varnish should respond with a 200 for any request to any host with this path // The Http class takes care of the proxying through varnish for us. if (empty($wgDevelEnvironment)) { $content = Http::get("http://x/__varnish_nagios_check"); if (!$content) { $statusCode = 503; $statusMsg = 'Server status is: NOT OK - Varnish not responding'; } } // don't check POST on Iowa (i.e. when ready only mode is on) if (wfReadOnly()) { $statusMsg = 'Server status is: POST check disabled'; } else { $content = Http::post('http://' . $_SERVER['SERVER_NAME'] . '/index.php?title=Special:HealthCheck&' . self::POST_PARAM_GET . '=1234', array('proxy' => '127.0.0.1:80', 'postData' => array(self::POST_PARAM_POST => '1234'))); if (substr((string) $content, 0, strlen(self::STATUS_MESSAGE_OK)) != self::STATUS_MESSAGE_OK) { $statusCode = 503; $statusMsg = 'Server status is: NOT OK - POST request failed'; } } $wgOut->setStatusCode($statusCode); $wgOut->addHTML($statusMsg . "\n"); }
/** * 上传头像 * * @param string $email * @param string $path * * @return bool */ public function avatar($email, $path) { $options = array('files' => array('media' => $path)); $url = self::API_AVATAR_UPLOAD . "?kf_account={$email}"; return $this->http->post($url, array(), $options); }
function runHTTPPosts($proxy = null) { $opt = array(); if ($proxy) { $opt['proxy'] = $proxy; } elseif ($proxy === false) { $opt['noProxy'] = true; } foreach ($this->test_posturl as $u => $postData) { $opt['postData'] = $postData; $r = Http::post($u, $opt); $this->assertEquals(self::$content["POST {$u} => {$postData}"], "{$r}", "POST {$u} (postData={$postData}) with " . Http::$httpEngine); } }
protected function requisicao($url, $dados) { return Http::post($url, $dados); }
protected function getApertiumSuggestion($serviceName, $config) { global $wgMemc; self::checkTranslationServiceFailure($serviceName); $page = $this->handle->getKey(); $code = $this->handle->getCode(); $ns = $this->handle->getTitle()->getNamespace(); $memckey = wfMemckey('translate-tmsug-pairs-' . $serviceName); $pairs = $wgMemc->get($memckey); if (!$pairs) { $pairs = array(); $json = Http::get($config['pairs'], 5); $response = FormatJson::decode($json); if ($json === false) { self::reportTranslationServiceFailure($serviceName); } elseif (!is_object($response)) { error_log(__METHOD__ . ': Unable to parse reply: ' . strval($json)); return null; } foreach ($response->responseData as $pair) { $source = $pair->sourceLanguage; $target = $pair->targetLanguage; if (!isset($pairs[$target])) { $pairs[$target] = array(); } $pairs[$target][$source] = true; } $wgMemc->set($memckey, $pairs, 60 * 60 * 24); } if (isset($config['codemap'][$code])) { $code = $config['codemap'][$code]; } $code = str_replace('-', '_', wfBCP47($code)); if (!isset($pairs[$code])) { return null; } $suggestions = array(); $codemap = array_flip($config['codemap']); foreach ($pairs[$code] as $candidate => $unused) { $mwcode = str_replace('_', '-', strtolower($candidate)); if (isset($codemap[$mwcode])) { $mwcode = $codemap[$mwcode]; } $text = TranslateUtils::getMessageContent($page, $mwcode, $ns); if ($text === null || TranslateEditAddons::hasFuzzyString($text)) { continue; } $title = Title::makeTitleSafe($ns, "{$page}/{$mwcode}"); if ($title && TranslateEditAddons::isFuzzy($title)) { continue; } $options = self::makeGoogleQueryParams($text, "{$candidate}|{$code}", $config); $options['postData']['format'] = 'html'; $json = Http::post($config['url'], $options); $response = FormatJson::decode($json); if ($json === false || !is_object($response)) { self::reportTranslationServiceFailure($serviceName); } elseif ($response->responseStatus !== 200) { error_log(__METHOD__ . " (HTTP {$response->responseStatus}) with ({$serviceName} ({$candidate}|{$code})): " . $response->responseDetails); } else { $sug = Sanitizer::decodeCharReferences($response->responseData->translatedText); $sug = trim($sug); $sug = $this->suggestionField($sug); $suggestions[] = Html::rawElement('div', array('title' => $text), self::legend("{$serviceName} ({$candidate})") . $sug . self::clear()); } } if (!count($suggestions)) { return null; } $divider = Html::element('div', array('style' => 'margin-bottom: 0.5ex')); return implode("{$divider}\n", $suggestions); }
/** * Serialize pingback data and send it to MediaWiki.org via a POST * to its event beacon endpoint. * * The data encoding conforms to the expectations of EventLogging, * a software suite used by the Wikimedia Foundation for logging and * processing analytic data. * * Compare: * <https://github.com/wikimedia/mediawiki-extensions-EventLogging/ * blob/7e5fe4f1ef/includes/EventLogging.php#L32-L74> * * @param array $data Pingback data as an associative array * @return bool true on success, false on failure */ private function postPingback(array $data) { $json = FormatJson::encode($data); $queryString = rawurlencode(str_replace(' ', '\\u0020', $json)) . ';'; $url = 'https://www.mediawiki.org/beacon/event?' . $queryString; return Http::post($url) !== false; }
public static function createDept($accessToken, $dept) { $response = Http::post("/department/create", array("access_token" => $accessToken), json_encode($dept)); return $response->id; }
public static function activeSuite($suiteAccessToken, $authCorpId, $permanentCode) { $response = Http::post("/service/activate_suite", array("suite_access_token" => $suiteAccessToken), json_encode(array("suite_key" => SUITE_KEY, "auth_corpid" => $authCorpId, "permanent_code" => $permanentCode))); return $response; }
function testApiLoginGoodPass() { if (!isset($wgServername) || !isset($wgServer)) { $this->markTestIncomplete('This test needs $wgServerName and $wgServer to ' . 'be set in LocalSettings.php'); } $resp = Http::post(self::$apiUrl . "?action=login&format=xml", array("postData" => array("lgname" => self::$userName, "lgpassword" => self::$passWord))); libxml_use_internal_errors(true); $sxe = simplexml_load_string($resp); $this->assertNotType("bool", $sxe); $this->assertThat($sxe, $this->isInstanceOf("SimpleXMLElement")); $a = $sxe->login[0]->attributes()->result; $this->assertEquals(' result="Success"', $a->asXML()); }
/** * Send prepared request request to phalanx daemon * * @author Krzysztof Krzyżaniak (eloy) <*****@*****.**> * @access private * * @param $action String type of action * @param $parameters Array additional parameters as hash table */ private function sendToPhalanxDaemon($action, $parameters) { wfProfileIn(__METHOD__); $baseurl = F::app()->wg->PhalanxServiceUrl; $options = F::app()->wg->PhalanxServiceOptions; $url = sprintf("%s/%s", $baseurl, $action != "status" ? $action : ""); /** * for status we're sending GET */ if ($action == "status") { wfDebug(__METHOD__ . ": calling {$url}\n"); $response = Http::get($url, 'default', $options); } else { if (($action == "match" || $action == "check") && !is_null($this->user)) { $parameters['wiki'] = F::app()->wg->CityId; $parameters['user'][] = $this->user->getName(); } if ($action == "match" && $this->limit != 1) { $parameters['limit'] = $this->limit; } $postData = array(); if (!empty($parameters)) { foreach ($parameters as $key => $values) { if (is_array($values)) { foreach ($values as $val) { $postData[] = urlencode($key) . '=' . urlencode($val); } } else { $postData[] = urlencode($key) . '=' . urlencode($values); } } } $options["postData"] = implode("&", $postData); wfDebug(__METHOD__ . ": calling {$url} with POST data " . $options["postData"] . "\n"); wfDebug(__METHOD__ . ": " . json_encode($parameters) . "\n"); $response = Http::post($url, $options); } if ($response === false) { /* service doesn't work */ $res = false; } else { wfDebug(__METHOD__ . "::response - {$response}\n"); switch ($action) { case "stats": $res = is_null($response) ? false : $response; break; case "status": $res = stripos($response, self::RES_STATUS) !== false ? true : false; break; case "match": $ret = json_decode($response); if (!is_array($ret)) { $res = false; } else { if (count($ret) > 0 && $this->limit != 0) { if ($this->limit == 1) { $res = $ret[0]; } else { $res = array_slice($ret, 0, $this->limit); } } else { $res = 0; } } break; default: if (stripos($response, self::RES_OK) !== false) { $res = 1; } elseif (stripos($response, self::RES_FAILURE) !== false) { $res = 0; } else { /* invalid response */ $res = false; } break; } } wfProfileOut(__METHOD__); return $res; }