/**
  * Unmarshal return value from a specified node
  *
  * @param   xml.Node node
  * @return  webservices.uddi.BusinessList
  * @see     xp://webservices.uddi.UDDICommand#unmarshalFrom
  * @throws  lang.FormatException in case of an unexpected response
  */
 public function unmarshalFrom($node)
 {
     if (0 != strcasecmp($node->name, 'businessList')) {
         throw new \lang\FormatException('Expected "businessList", got "' . $node->name . '"');
     }
     // Create business list object from XML representation
     with($list = new BusinessList(), $children = $node->nodeAt(0)->getChildren());
     $list->setOperator($node->getAttribute('operator'));
     $list->setTruncated(0 == strcasecmp('true', $node->getAttribute('truncated')));
     for ($i = 0, $s = sizeof($children); $i < $s; $i++) {
         $b = new Business($children[$i]->getAttribute('businessKey'));
         for ($j = 0, $t = sizeof($children[$i]->getChildren()); $j < $s; $j++) {
             switch ($children[$i]->nodeAt($j)->name) {
                 case 'name':
                     $b->names[] = $children[$i]->nodeAt($j)->getContent();
                     break;
                 case 'description':
                     $b->description = $children[$i]->nodeAt($j)->getContent();
                     break;
             }
         }
         $list->items[] = $b;
     }
     return $list;
 }
Exemplo n.º 2
1
 public function getAllProjects()
 {
     $key = "{$this->cachePrefix}-all-projects";
     if ($this->cache && ($projects = $this->cache->fetch($key))) {
         return $projects;
     }
     $first = json_decode($this->client->get('projects.json', ['query' => ['limit' => 100]])->getBody(), true);
     $projects = $first['projects'];
     if ($first['total_count'] > 100) {
         $requests = [];
         for ($i = 100; $i < $first['total_count']; $i += 100) {
             $requests[] = $this->client->getAsync('projects.json', ['query' => ['limit' => 100, 'offset' => $i]]);
         }
         /** @var Response[] $responses */
         $responses = Promise\unwrap($requests);
         $responseProjects = array_map(function (Response $response) {
             return json_decode($response->getBody(), true)['projects'];
         }, $responses);
         $responseProjects[] = $projects;
         $projects = call_user_func_array('array_merge', $responseProjects);
     }
     usort($projects, function ($projectA, $projectB) {
         return strcasecmp($projectA['name'], $projectB['name']);
     });
     $this->cache && $this->cache->save($key, $projects);
     return $projects;
 }
Exemplo n.º 3
0
 protected function getTableFieldList($tableName)
 {
     $tableFieldList = array();
     $factory = WebserviceField::fromArray($this->pearDB, array('tablename' => $tableName));
     $dbTableFields = $factory->getTableFields();
     foreach ($dbTableFields as $dbField) {
         if ($dbField->primaryKey) {
             if ($this->idColumn === null) {
                 $this->idColumn = $dbField->name;
             } else {
                 throw new WebServiceException(WebServiceErrorCode::$UNKOWNENTITY, "Entity table with multi column primary key is not supported");
             }
         }
         $field = $this->getFieldArrayFromDBField($dbField, $tableName);
         $webserviceField = WebserviceField::fromArray($this->pearDB, $field);
         $fieldDataType = $this->getFieldType($dbField, $tableName);
         if ($fieldDataType === null) {
             $fieldDataType = $this->getFieldDataTypeFromDBType($dbField->type);
         }
         $webserviceField->setFieldDataType($fieldDataType);
         if (strcasecmp($fieldDataType, 'reference') === 0) {
             $webserviceField->setReferenceList($this->getReferenceList($dbField, $tableName));
         }
         array_push($tableFieldList, $webserviceField);
     }
     return $tableFieldList;
 }
/**
 * Makes an API request to elucidat
 * @param $headers
 * @param $fields
 * @param $url
 * @param $consumer_secret
 * @return mixed
 */
function call_elucidat($headers, $fields, $method, $url, $consumer_secret)
{
    //Build a signature
    $headers['oauth_signature'] = build_signature($consumer_secret, array_merge($headers, $fields), $method, $url);
    //Build OAuth headers
    $auth_headers = 'Authorization:';
    $auth_headers .= build_base_string($headers, ',');
    //Build the request string
    $fields_string = build_base_string($fields, '&');
    //Set the headers
    $header = array($auth_headers, 'Expect:');
    // Create curl options
    if (strcasecmp($method, "GET") == 0) {
        $url .= '?' . $fields_string;
        $options = array(CURLOPT_HTTPHEADER => $header, CURLOPT_HEADER => false, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false);
    } else {
        $options = array(CURLOPT_HTTPHEADER => $header, CURLOPT_HEADER => false, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_POST => count($fields), CURLOPT_POSTFIELDS => $fields_string);
    }
    //Init the request and set its params
    $request = curl_init();
    curl_setopt_array($request, $options);
    //Make the request
    $response = curl_exec($request);
    $status = curl_getinfo($request, CURLINFO_HTTP_CODE);
    curl_close($request);
    return array('status' => $status, 'response' => json_decode($response, true));
}
Exemplo n.º 5
0
function get_profile_url($html)
{
    $profiles = array();
    $keys = array();
    $doc = new \DOMDocument();
    $html = "<html><head> <title> test </title> </head> <body> " . $html . "</body> </html>";
    @$doc->loadHTML($html);
    $links = $doc->getElementsByTagName("a");
    $length = $links->length;
    if ($length <= 0) {
        return $profiles;
    }
    for ($i = 0; $i < $length; $i++) {
        //individual link node
        $link = $links->item($i);
        $href = $link->getAttribute("href");
        //does the link href end in profile?
        $pos = strrpos($href, "/");
        if ($pos !== false) {
            $token = substr($href, $pos + 1);
            if (strcasecmp($token, "profile") == 0) {
                $key = md5($href);
                //avoid duplicates!
                if (!in_array($key, $keys)) {
                    array_push($profiles, $href);
                    array_push($keys, $key);
                }
            }
        }
    }
    return $profiles;
}
Exemplo n.º 6
0
 function &getTransport($url, $encoding = SOAP_DEFAULT_ENCODING)
 {
     $urlparts = @parse_url($url);
     if (!$urlparts['scheme']) {
         return SOAP_Base_Object::_raiseSoapFault("Invalid transport URI: {$url}");
     }
     if (strcasecmp($urlparts['scheme'], 'mailto') == 0) {
         $transport_type = 'SMTP';
     } else {
         if (strcasecmp($urlparts['scheme'], 'https') == 0) {
             $transport_type = 'HTTP';
         } else {
             /* handle other transport types */
             $transport_type = strtoupper($urlparts['scheme']);
         }
     }
     $transport_include = 'SOAP/Transport/' . $transport_type . '.php';
     $res = @(include_once $transport_include);
     if (!$res && !in_array($transport_include, get_included_files())) {
         return SOAP_Base_Object::_raiseSoapFault("No Transport for {$urlparts['scheme']}");
     }
     $transport_class = "SOAP_Transport_{$transport_type}";
     if (!class_exists($transport_class)) {
         return SOAP_Base_Object::_raiseSoapFault("No Transport class {$transport_class}");
     }
     return new $transport_class($url, $encoding);
 }
Exemplo n.º 7
0
 public function requestForgotPassword($request)
 {
     $request = new Vtiger_Request($request);
     $adb = PearDatabase::getInstance();
     $username = vtlib_purify($request->get('user_name'));
     $result = $adb->pquery('select id,email1 from vtiger_users where user_name = ? ', array($username));
     if ($adb->num_rows($result) > 0) {
         $email = $adb->query_result($result, 0, 'email1');
     }
     if (strcasecmp($request->get('emailId'), $email) === 0) {
         $userId = $adb->query_result($result, 0, 'id');
         $time = time();
         $options = array('handler_path' => 'modules/Users/handlers/ForgotPassword.php', 'handler_class' => 'Users_ForgotPassword_Handler', 'handler_function' => 'changePassword', 'handler_data' => array('username' => $username, 'email' => $email, 'time' => $time, 'hash' => md5($username . $time)));
         $trackURL = Vtiger_ShortURL_Helper::generateURL($options);
         $data = ['sysname' => 'UsersForgotPassword', 'to_email' => $email, 'module' => 'Users', 'record' => $userId, 'trackURL' => $trackURL];
         $recordModel = Vtiger_Record_Model::getCleanInstance('OSSMailTemplates');
         $status = $recordModel->sendMailFromTemplate($data);
         $site_URL = vglobal('site_URL') . 'index.php?modules=Users&view=Login';
         if ($status === 1) {
             header('Location:  ' . $site_URL . '&status=1');
         } else {
             header('Location:  ' . $site_URL . '&statusError=1');
         }
     } else {
         $site_URL = vglobal('site_URL') . 'index.php?modules=Users&view=Login';
         header('Location:  ' . $site_URL . '&fpError=1');
     }
 }
Exemplo n.º 8
0
 /**
  * Factory
  *
  * @param string $backend backend name
  * @param array $backendOptions associative array of options for the corresponding backend constructor
  * @return Zend_Memory_Manager
  * @throws Zend_Memory_Exception
  */
 public static function factory($backend, $backendOptions = array())
 {
     if (strcasecmp($backend, 'none') == 0) {
         return new Zend_Memory_Manager();
     }
     // Look through available backendsand
     // (that allows to specify it in any case)
     $backendIsFound = false;
     foreach (Zend_Cache::$standardBackends as $zendCacheBackend) {
         if (strcasecmp($backend, $zendCacheBackend) == 0) {
             $backend = $zendCacheBackend;
             $backendIsFound = true;
             break;
         }
     }
     if (!$backendIsFound) {
         // require_once 'Zend/Memory/Exception.php';
         throw new Zend_Memory_Exception("Incorrect backend ({$backend})");
     }
     $backendClass = 'Zend_Cache_Backend_' . $backend;
     // For perfs reasons, we do not use the Zend_Loader::loadClass() method
     // (security controls are explicit)
     // require_once str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php';
     $backendObject = new $backendClass($backendOptions);
     return new Zend_Memory_Manager($backendObject);
 }
Exemplo n.º 9
0
 /**
  *  最大値のチェックを行う
  *
  *  @access public
  *  @param  string  $name       フォームの名前
  *  @param  mixed   $var        フォームの値
  *  @param  array   $params     プラグインのパラメータ
  *  @return true: 成功  Ethna_Error: エラー
  */
 public function validate($name, $var, $params)
 {
     $true = true;
     $type = $this->getFormType($name);
     if (isset($params['strmaxcompat']) == false || $this->isEmpty($var, $type)) {
         return $true;
     }
     $ctl = $this->backend->getController();
     $client_enc = $ctl->getClientEncoding();
     if (mb_enabled() && (strcasecmp('EUC-JP', $client_enc) != 0 && strcasecmp('eucJP-win', $client_enc) != 0)) {
         $var = mb_convert_encoding($var, 'EUC-JP', $client_enc);
     }
     if ($type == VAR_TYPE_STRING) {
         $max_param = $params['strmaxcompat'];
         if (strlen($var) > $max_param) {
             if (isset($params['error'])) {
                 $msg = $params['error'];
             } else {
                 $msg = _et('Please input less than %d full-size (%d half-size) characters to {form}.');
             }
             return Ethna::raiseNotice($msg, E_FORM_MAX_STRING, array(intval($max_param / 2), $max_param));
         }
     }
     return $true;
 }
Exemplo n.º 10
0
 function simple_fields_uasort($a, $b)
 {
     if ($a["name"] == $b["name"]) {
         return 0;
     }
     return strcasecmp($a["name"], $b["name"]);
 }
Exemplo n.º 11
0
 public function curl($server = NULL, $parameters = array())
 {
     $response = false;
     $start = microtime(true);
     if ($server) {
         $this->CI->curl->create($server);
         $this->CI->curl->option('buffersize', 10);
         $this->CI->curl->option('useragent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 (.NET CLR 3.5.30729)');
         $this->CI->curl->option('returntransfer', true);
         $this->CI->curl->option('followlocation', true);
         $this->CI->curl->option('connecttimeout', true);
         $this->CI->curl->post($parameters);
         $data = $this->CI->curl->execute();
         $this->CI->response_time = round(microtime(true) - $start, 3) . " seconds";
         if ($data !== false) {
             if (strcasecmp(element('format', $parameters), 'json') == 0) {
                 $response = json_decode($data, true);
             } else {
                 $response = $data;
             }
             $this->CI->notification->set_message('idol_server_response_success');
         } else {
             $this->CI->notification->set_error('idol_server_response_error');
         }
         $this->CI->curl->close();
     } else {
         $this->CI->notification->set_error('idol_server_response_noserverdefined');
     }
     return $response;
 }
Exemplo n.º 12
0
 function is_soap_fault($obj)
 {
     if (!is_object($obj)) {
         return false;
     }
     return strcasecmp(get_class($obj), 'soap_fault') === 0;
 }
Exemplo n.º 13
0
function handle_md5($string)
{
    if (strcasecmp(substr($string, 0, 1), "0") == 0) {
        $string = substr($string, 1);
    }
    return $string;
}
 /**
  * {@inheritdoc}
  */
 public function getOptions($dataLocale, $collectionId = null, $search = '', array $options = [])
 {
     if (null === $collectionId) {
         throw new \InvalidArgumentException('Please supply attribute id as collectionId');
     }
     $qb = $this->createQueryBuilder('o')->select('o.id, o.code, v.value AS label, a.properties')->leftJoin('o.optionValues', 'v', 'WITH', 'v.locale=:locale')->leftJoin('o.attribute', 'a')->where('o.attribute=:attribute')->orderBy('o.sortOrder')->setParameter('locale', $dataLocale)->setParameter('attribute', $collectionId);
     if ($search) {
         $qb->andWhere('v.value like :search OR o.code LIKE :search')->setParameter('search', "{$search}%");
     }
     if (isset($options['ids'])) {
         $qb->andWhere($qb->expr()->in('o.id', ':ids'))->setParameter('ids', $options['ids']);
     }
     if (isset($options['limit'])) {
         $qb->setMaxResults((int) $options['limit']);
         if (isset($options['page'])) {
             $qb->setFirstResult((int) $options['limit'] * ((int) $options['page'] - 1));
         }
     }
     $results = [];
     $autoSorting = null;
     foreach ($qb->getQuery()->getArrayResult() as $row) {
         if (null === $autoSorting && isset($row['properties']['autoOptionSorting'])) {
             $autoSorting = $row['properties']['autoOptionSorting'];
         }
         $results[] = ['id' => isset($options['type']) && 'code' === $options['type'] ? $row['code'] : $row['id'], 'text' => null !== $row['label'] ? $row['label'] : sprintf('[%s]', $row['code'])];
     }
     if ($autoSorting) {
         usort($results, function ($first, $second) {
             return strcasecmp($first['text'], $second['text']);
         });
     }
     return ['results' => $results];
 }
 private function checkUrlMatch($regx, $rule)
 {
     $m1 = explode('/', $regx);
     $m2 = explode('/', $rule);
     $match = true;
     // 是否匹配
     foreach ($m2 as $key => $val) {
         if (':' == substr($val, 0, 1)) {
             // 动态变量
             if (strpos($val, '\\')) {
                 $type = substr($val, -1);
                 if ('d' == $type && !is_numeric($m1[$key])) {
                     $match = false;
                     break;
                 }
             } elseif (strpos($val, '^')) {
                 $array = explode('|', substr(strstr($val, '^'), 1));
                 if (in_array($m1[$key], $array)) {
                     $match = false;
                     break;
                 }
             }
         } elseif (0 !== strcasecmp($val, $m1[$key])) {
             $match = false;
             break;
         }
     }
     return $match;
 }
Exemplo n.º 16
0
function getip($format = 0)
{
    global $_iGLOBAL;
    if (empty($_iGLOBAL['ip'])) {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        preg_match("/[\\d\\.]{7,15}/", $onlineip, $onlineipmatches);
        $_iGLOBAL['ip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
    }
    if ($format) {
        $ips = explode('.', $_iGLOBAL['ip']);
        for ($i = 0; $i < 3; $i++) {
            $ips[$i] = intval($ips[$i]);
        }
        return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
    } else {
        return $_iGLOBAL['ip'];
    }
}
Exemplo n.º 17
0
 /**
  * Decodes a JSON string.
  * @param  string
  * @param  int  accepts Json::FORCE_ARRAY
  * @return mixed
  */
 public static function decode($json, $options = 0)
 {
     $json = (string) $json;
     if (!preg_match('##u', $json)) {
         throw new JsonException('Invalid UTF-8 sequence', 5);
         // workaround for PHP < 5.3.3 & PECL JSON-C
     }
     $forceArray = (bool) ($options & self::FORCE_ARRAY);
     if (!$forceArray && preg_match('#(?<=[^\\\\]")\\\\u0000(?:[^"\\\\]|\\\\.)*+"\\s*+:#', $json)) {
         // workaround for json_decode fatal error when object key starts with \u0000
         throw new JsonException(static::$messages[JSON_ERROR_CTRL_CHAR]);
     }
     $args = array($json, $forceArray, 512);
     if (PHP_VERSION_ID >= 50400 && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
         // not implemented in PECL JSON-C 1.3.2 for 64bit systems
         $args[] = JSON_BIGINT_AS_STRING;
     }
     $value = call_user_func_array('json_decode', $args);
     if ($value === NULL && $json !== '' && strcasecmp(trim($json, " \t\n\r"), 'null') !== 0) {
         // '' is not clearing json_last_error
         $error = json_last_error();
         throw new JsonException(isset(static::$messages[$error]) ? static::$messages[$error] : 'Unknown error', $error);
     }
     return $value;
 }
Exemplo n.º 18
0
 public function renderizar($nome, $item = FALSE)
 {
     if (Session::get('autenticado')) {
         $menu[] = array("id" => "", "titulo" => "", "link" => URL . "");
     } else {
         $menu[] = array("id" => "login", "titulo" => "Inciar Sessão", "link" => URL . "login");
     }
     if (strcasecmp(Session::get('nivel'), 'administrador') == 0) {
         $admin = array(array("id" => "matricula", "titulo" => "Matricula", "link" => URL . "matricula"), array("id" => "docente", "titulo" => "Docente", "link" => URL . "docente"), array("id" => "curso", "titulo" => "Curso", "link" => URL . "curso"), array("id" => "nota", "titulo" => "Nota", "link" => URL . "nota"), array("id" => "programa", "titulo" => "Programa", "link" => URL . "programa"), array("id" => "relatorio", "titulo" => "Relatorio", "link" => URL . "relatorio"));
     } else {
         $admin = "";
     }
     $js = array();
     if (count($this->_js)) {
         $js = $this->_js;
     }
     $css = array();
     if (count($this->_css)) {
         $css = $this->_css;
     }
     $_layoutParam = array("caminho_css" => URL . "views/layout" . DS1 . DEFAULT_LAYOUT . "/bootstrap" . DS1 . "css/", "caminho_js" => URL . "views/layout" . DS1 . DEFAULT_LAYOUT . "/bootstrap" . DS1 . "js/", "caminho_images" => URL . "views/layout" . DS1 . DEFAULT_LAYOUT . "/images/", "caminho_vendores" => URL . "views/layout" . DS1 . DEFAULT_LAYOUT . "/vendors/", "caminho_assets" => URL . "views/layout" . DS1 . DEFAULT_LAYOUT . "/assets/", "menu" => $menu, "admin" => $admin, "js" => $js, "css" => $css);
     $caminho = ROOT . "views" . DS1 . $this->_controller . DS1 . $nome . ".phtml";
     //ou phtml
     $header = ROOT . "views" . DS1 . "layout" . DS1 . DEFAULT_LAYOUT . DS1 . "header.php";
     $footer = ROOT . "views" . DS1 . "layout" . DS1 . DEFAULT_LAYOUT . DS1 . "footer.php";
     if (is_readable($caminho)) {
         require $header;
         //$this->assign("conteudo",$caminho);
         require $caminho;
         require $footer;
     } else {
         throw new Exception("Erro ao incluir a view, verifique o arquivo View");
     }
 }
Exemplo n.º 19
0
function post_req($url_str, $username, $password, $headers_arr, $req_str)
{
    fwrite(STDERR, $url_str);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url_str);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req_str);
    // Don't get the headers
    //curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_arr);
    // execute the request
    $output = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    if ($errno !== 0) {
        curl_close($ch);
        return array("success" => FALSE, "message" => "Error sending request to service {$url_str}: {$error}");
    }
    $sc_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($sc_code !== 200) {
        $ct = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        curl_close($ch);
        if (strcasecmp($ct, "application/json") == 0) {
            $err_obj = json_decode($output, true);
            return array("success" => FALSE, "message" => $err_obj['user_message']);
        }
        return array("success" => FALSE, "message" => "Service returned http code: {$sc_code}");
    }
    // close curl resource to free up system resources
    curl_close($ch);
    return array("success" => TRUE, "output" => $output);
}
 /**
  * Processes this test when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The current file being scanned.
  * @param int                  $stackPtr  The position of the current token
  *                                        in the stack passed in $tokens.
  * @param int                  $currScope A pointer to the start of the scope.
  *
  * @return void
  */
 protected function processTokenWithinScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $currScope)
 {
     $className = $phpcsFile->getDeclarationName($currScope);
     $methodName = $phpcsFile->getDeclarationName($stackPtr);
     if (strcasecmp($methodName, $className) === 0) {
         $error = 'PHP4 style constructors are not allowed; use "__construct()" instead';
         $phpcsFile->addError($error, $stackPtr, 'OldStyle');
     } else {
         if (strcasecmp($methodName, '__construct') !== 0) {
             // Not a constructor.
             return;
         }
     }
     $tokens = $phpcsFile->getTokens();
     $parentClassName = $phpcsFile->findExtendedClassName($currScope);
     if ($parentClassName === false) {
         return;
     }
     $endFunctionIndex = $tokens[$stackPtr]['scope_closer'];
     $startIndex = $stackPtr;
     while ($doubleColonIndex = $phpcsFile->findNext(array(T_DOUBLE_COLON), $startIndex, $endFunctionIndex)) {
         if ($tokens[$doubleColonIndex + 1]['code'] === T_STRING && $tokens[$doubleColonIndex + 1]['content'] === $parentClassName) {
             $error = 'PHP4 style calls to parent constructors are not allowed; use "parent::__construct()" instead';
             $phpcsFile->addError($error, $doubleColonIndex + 1, 'OldStyleCall');
         }
         $startIndex = $doubleColonIndex + 1;
     }
 }
Exemplo n.º 21
0
function phabricator_form(PhabricatorUser $user, $attributes, $content)
{
    $body = array();
    $http_method = idx($attributes, 'method');
    $is_post = strcasecmp($http_method, 'POST') === 0;
    $http_action = idx($attributes, 'action');
    $is_absolute_uri = preg_match('#^(https?:|//)#', $http_action);
    if ($is_post) {
        // NOTE: We only include CSRF tokens if a URI is a local URI on the same
        // domain. This is an important security feature and prevents forms which
        // submit to foreign sites from leaking CSRF tokens.
        // In some cases, we may construct a fully-qualified local URI. For example,
        // we can construct these for download links, depending on configuration.
        // These forms do not receive CSRF tokens, even though they safely could.
        // This can be confusing, if you're developing for Phabricator and
        // manage to construct a local form with a fully-qualified URI, since it
        // won't get CSRF tokens and you'll get an exception at the other end of
        // the request which is a bit disconnected from the actual root cause.
        // However, this is rare, and there are reasonable cases where this
        // construction occurs legitimately, and the simplest fix is to omit CSRF
        // tokens for these URIs in all cases. The error message you receive also
        // gives you some hints as to this potential source of error.
        if (!$is_absolute_uri) {
            $body[] = phutil_tag('input', array('type' => 'hidden', 'name' => AphrontRequest::getCSRFTokenName(), 'value' => $user->getCSRFToken()));
            $body[] = phutil_tag('input', array('type' => 'hidden', 'name' => '__form__', 'value' => true));
        }
    }
    if (is_array($content)) {
        $body = array_merge($body, $content);
    } else {
        $body[] = $content;
    }
    return javelin_tag('form', $attributes, $body);
}
Exemplo n.º 22
0
Arquivo: S3.php Projeto: rikaix/zf2
 /**
  * Add the S3 Authorization signature to the request headers
  *
  * @param  string $method
  * @param  string $path
  * @param  array &$headers
  * @return string
  */
 public function generateSignature($method, $path, &$headers)
 {
     if (!is_array($headers)) {
         $headers = array($headers);
     }
     $type = $md5 = $date = '';
     // Search for the Content-type, Content-MD5 and Date headers
     foreach ($headers as $key => $val) {
         if (strcasecmp($key, 'content-type') == 0) {
             $type = $val;
         } else {
             if (strcasecmp($key, 'content-md5') == 0) {
                 $md5 = $val;
             } else {
                 if (strcasecmp($key, 'date') == 0) {
                     $date = $val;
                 }
             }
         }
     }
     // If we have an x-amz-date header, use that instead of the normal Date
     if (isset($headers['x-amz-date']) && isset($date)) {
         $date = '';
     }
     $sig_str = "{$method}\n{$md5}\n{$type}\n{$date}\n";
     // For x-amz- headers, combine like keys, lowercase them, sort them
     // alphabetically and remove excess spaces around values
     $amz_headers = array();
     foreach ($headers as $key => $val) {
         $key = strtolower($key);
         if (substr($key, 0, 6) == 'x-amz-') {
             if (is_array($val)) {
                 $amz_headers[$key] = $val;
             } else {
                 $amz_headers[$key][] = preg_replace('/\\s+/', ' ', $val);
             }
         }
     }
     if (!empty($amz_headers)) {
         ksort($amz_headers);
         foreach ($amz_headers as $key => $val) {
             $sig_str .= $key . ':' . implode(',', $val) . "\n";
         }
     }
     $sig_str .= '/' . parse_url($path, PHP_URL_PATH);
     if (strpos($path, '?location') !== false) {
         $sig_str .= '?location';
     } else {
         if (strpos($path, '?acl') !== false) {
             $sig_str .= '?acl';
         } else {
             if (strpos($path, '?torrent') !== false) {
                 $sig_str .= '?torrent';
             }
         }
     }
     $signature = base64_encode(Crypt\Hmac::compute($this->_secretKey, 'sha1', utf8_encode($sig_str), Crypt\Hmac::BINARY));
     $headers['Authorization'] = 'AWS ' . $this->_accessKey . ':' . $signature;
     return $sig_str;
 }
Exemplo n.º 23
0
 /**
  * Fixes CGI only one Status header allowed bug
  *
  * @link  http://bugs.php.net/bug.php?id=36705
  *
  * @return Mage_Core_Controller_Response_Http
  */
 public function sendHeaders()
 {
     if (!$this->canSendHeaders()) {
         Mage::log('HEADERS ALREADY SENT: ' . mageDebugBacktrace(true, true, true));
         return $this;
     }
     if (substr(php_sapi_name(), 0, 3) == 'cgi') {
         $statusSent = false;
         foreach ($this->_headersRaw as $i => $header) {
             if (stripos($header, 'status:') === 0) {
                 if ($statusSent) {
                     unset($this->_headersRaw[$i]);
                 } else {
                     $statusSent = true;
                 }
             }
         }
         foreach ($this->_headers as $i => $header) {
             if (strcasecmp($header['name'], 'status') === 0) {
                 if ($statusSent) {
                     unset($this->_headers[$i]);
                 } else {
                     $statusSent = true;
                 }
             }
         }
     }
     return parent::sendHeaders();
 }
Exemplo n.º 24
0
 static function sortAlphabetically(X_Page_Item_PItem $item1, X_Page_Item_PItem $item2)
 {
     // prevent warning for array modification
     $label1 = $item1->getLabel();
     $label2 = $item2->getLabel();
     return strcasecmp($label1, $label2);
 }
Exemplo n.º 25
0
function get_replay_type($data, $fileExtension)
{
    if (strcasecmp($fileExtension, "cnc4replay") == 0) {
        return "cnc4replay";
    }
    if (strcasecmp($fileExtension, "ra3replay") == 0) {
        return "ra3replay";
    }
    if (strcasecmp($fileExtension, "kwreplay") == 0) {
        return "kwreplay";
    }
    if (strcasecmp($fileExtension, "cnc3replay") == 0) {
        return "cnc3replay";
    }
    if (strcasecmp($fileExtension, "rep") == 0) {
        return "rep";
    }
    if (strcasecmp($fileExtension, "rec") == 0) {
        $hexdata = bin2hex($data);
        //先判断是否英雄连,第五个字节后为coh
        $cohToken = substr($hexdata, 8, 6);
        $cohToken = hex2bin($cohToken);
        if ($cohToken == "COH") {
            return "rec";
        }
        //是英雄连
        $dowToken = substr($hexdata, 24, 8);
        $dowToken = hex2bin($dowToken);
        if ($dowToken == "DOW2") {
            return "dow2";
        }
    }
}
Exemplo n.º 26
0
function endsWith($haystack, $needle, $case = true)
{
    if ($case) {
        return strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0;
    }
    return strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0;
}
Exemplo n.º 27
0
function name_case($name)
{
    $newname = strtoupper($name[0]);
    for ($i = 1; $i < strlen($name); $i++) {
        $subed = substr($name, $i, 1);
        if (ord($subed) > 64 && ord($subed) < 123 || ord($subed) > 48 && ord($subed) < 58) {
            $word_check = substr($name, $i - 2, 2);
            if (!strcasecmp($word_check, 'Mc') || !strcasecmp($word_check, "O'")) {
                $newname .= strtoupper($subed);
            } else {
                if ($break) {
                    $newname .= strtoupper($subed);
                } else {
                    $newname .= strtolower($subed);
                }
            }
            $break = 0;
        } else {
            // not a letter - a boundary
            $newname .= $subed;
            $break = 1;
        }
    }
    return $newname;
}
Exemplo n.º 28
0
 /**
  * Returns a specific character in UTF-8.
  * @param  int     codepoint
  * @return string
  */
 public static function chr($code)
 {
     if (func_num_args() > 1 && strcasecmp(func_get_arg(1), 'UTF-8')) {
         trigger_error(__METHOD__ . ' supports only UTF-8 encoding.', E_USER_DEPRECATED);
     }
     return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
 }
Exemplo n.º 29
0
function deliver_response($format, $api_response, $isSaveQuery)
{
    // Define HTTP responses
    $http_response_code = array(200 => 'OK', 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found');
    // Set HTTP Response
    header('HTTP/1.1 ' . $api_response['status'] . ' ' . $http_response_code[$api_response['status']]);
    // Process different content types
    if (strcasecmp($format, 'json') == 0) {
        // Set HTTP Response Content Type
        header('Content-Type: application/json; charset=utf-8');
        // Format data into a JSON response
        $json_response = json_encode($api_response);
        // Deliver formatted data
        echo $json_response;
    } elseif (strcasecmp($format, 'xml') == 0) {
        // Set HTTP Response Content Type
        header('Content-Type: application/xml; charset=utf-8');
        // Format data into an XML response (This is only good at handling string data, not arrays)
        $xml_response = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<response>' . "\n" . "\t" . '<code>' . $api_response['code'] . '</code>' . "\n" . "\t" . '<data>' . $api_response['data'] . '</data>' . "\n" . '</response>';
        // Deliver formatted data
        echo $xml_response;
    } else {
        // Set HTTP Response Content Type (This is only good at handling string data, not arrays)
        header('Content-Type: text/html; charset=utf-8');
        // Deliver formatted data
        echo $api_response['data'];
    }
    // End script process
    exit;
}
Exemplo n.º 30
-1
 public static function getHtmlOptions($tag, $asString = true)
 {
     $tag = strtolower($tag);
     $options = [];
     switch ($tag) {
         case 'body':
             if (strcasecmp(Metronic::getComponent()->headerOption, 'fixed') === 0) {
                 Html::addCssClass($options, 'page-header-fixed');
             }
             switch (Metronic::getComponent()->layoutOption) {
                 case Metronic::LAYOUT_FULL_WIDTH:
                     Html::addCssClass($options, Metronic::LAYOUT_FULL_WIDTH);
                     break;
                 case Metronic::LAYOUT_BOXED:
                     Html::addCssClass($options, Metronic::LAYOUT_BOXED);
                     break;
             }
             break;
         case 'header':
             Html::addCssClass($options, 'header navbar');
             if (strcasecmp(Metronic::getComponent()->headerOption, 'fixed') === 0) {
                 Html::addCssClass($options, 'navbar-fixed-top');
             } else {
                 Html::addCssClass($options, 'navbar-static-top');
             }
             break;
     }
     return $asString ? Html::renderTagAttributes($options) : $options;
 }