sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function db_select($database = '') { if ($database === '') { $database = $this->database; } // Note: Escaping is required in the event that the DB name // contains reserved characters. if (mssql_select_db('['.$database.']', $this->conn_id)) { $this->database = $database; return TRUE; } return FALSE; }
Select the database @param string $database @return bool
entailment
public function insert_id() { $query = version_compare($this->version(), '8', '>=') ? 'SELECT SCOPE_IDENTITY() AS last_id' : 'SELECT @@IDENTITY AS last_id'; $query = $this->query($query); $query = $query->row(); return $query->last_id; }
Insert ID Returns the last id created in the Identity column. @return string
entailment
protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT '.$this->escape_identifiers('name') .' FROM '.$this->escape_identifiers('sysobjects') .' WHERE '.$this->escape_identifiers('type')." = 'U'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql.' ORDER BY '.$this->escape_identifiers('name'); }
List table query Generates a platform-specific query string so that the table names can be fetched @param bool $prefix_limit @return string
entailment
public function field_data($table) { $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->COLUMN_NAME; $retval[$i]->type = $query[$i]->DATA_TYPE; $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION; $retval[$i]->default = $query[$i]->COLUMN_DEFAULT; } return $retval; }
Returns an object with field data @param string $table @return array
entailment
public function error() { // We need this because the error info is discarded by the // server the first time you request it, and query() already // calls error() once for logging purposes when a query fails. static $error = array('code' => 0, 'message' => NULL); $message = mssql_get_last_message(); if ( ! empty($message)) { $error['code'] = $this->query('SELECT @@ERROR AS code')->row()->code; $error['message'] = $message; } return $error; }
Error Returns an array containing code and message of the last database error that has occured. @return array
entailment
protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); }
Update statement Generates a platform-specific update string from the supplied data @param string $table @param array $values @return string
entailment
protected function _delete($table) { if ($this->qb_limit) { return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete'; } return parent::_delete($table); }
Delete statement Generates a platform-specific delete string from the supplied data @param string $table @return string
entailment
protected function _limit($sql) { $limit = $this->qb_offset + $this->qb_limit; // As of SQL Server 2005 (9.0.*) ROW_NUMBER() is supported, // however an ORDER BY clause is required for it to work if (version_compare($this->version(), '9', '>=') && $this->qb_offset && ! empty($this->qb_orderby)) { $orderby = $this->_compile_order_by(); // We have to strip the ORDER BY clause $sql = trim(substr($sql, 0, strrpos($sql, $orderby))); // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results if (count($this->qb_select) === 0) { $select = '*'; // Inevitable } else { // Use only field names and their aliases, everything else is out of our scope. $select = array(); $field_regexp = ($this->_quoted_identifier) ? '("[^\"]+")' : '(\[[^\]]+\])'; for ($i = 0, $c = count($this->qb_select); $i < $c; $i++) { $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m) ? $m[1] : $this->qb_select[$i]; } $select = implode(', ', $select); } return 'SELECT '.$select." FROM (\n\n" .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql) ."\n\n) ".$this->escape_identifiers('CI_subquery') ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit; } return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql); }
LIMIT Generates a platform-specific LIMIT clause @param string $sql SQL Query @return string
entailment
protected function _insert_batch($table, $keys, $values) { // Multiple-value inserts are only supported as of SQL Server 2008 if (version_compare($this->version(), '10', '>=')) { return parent::_insert_batch($table, $keys, $values); } return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; }
Insert batch statement Generates a platform-specific insert string from the supplied data. @param string $table Table name @param array $keys INSERT keys @param array $values INSERT values @return string|bool
entailment
public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = cubrid_field_name($this->result_id, $i); $retval[$i]->type = cubrid_field_type($this->result_id, $i); $retval[$i]->max_length = cubrid_field_len($this->result_id, $i); $retval[$i]->primary_key = (int) (strpos(cubrid_field_flags($this->result_id, $i), 'primary_key') !== FALSE); } return $retval; }
Field data Generates an array of objects containing field meta-data @return array
entailment
public function free_result() { if (is_resource($this->result_id) OR (get_resource_type($this->result_id) === 'Unknown' && preg_match('/Resource id #/', strval($this->result_id)))) { cubrid_close_request($this->result_id); $this->result_id = FALSE; } }
Free the result @return void
entailment
public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field_names[] = pg_field_name($this->result_id, $i); } return $field_names; }
Fetch Field Names Generates an array of column names @return array
entailment
public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = pg_field_name($this->result_id, $i); $retval[$i]->type = pg_field_type($this->result_id, $i); $retval[$i]->max_length = pg_field_size($this->result_id, $i); } return $retval; }
Field data Generates an array of objects containing field meta-data @return array
entailment
public function free_result() { if (is_resource($this->result_id)) { pg_free_result($this->result_id); $this->result_id = FALSE; } }
Free the result @return void
entailment
public function uploadVideo($path, $title, $description) { $params = [ 'description' => json_encode( [ 'title' => $title, 'introduction' => $description, ], JSON_UNESCAPED_UNICODE), ]; return $this->uploadMedia('video', $path, $params); }
Upload video. @param string $path @param string $title @param string $description @return mixed @throws \yii\httpclient\Exception
entailment
public function updateArticle($mediaId, $article, $index = 0) { $params = [ 'media_id' => $mediaId, 'index' => $index, 'articles' => isset($article['title']) ? $article : (isset($article[$index]) ? $article[$index] : []), ]; return $this->post(self::API_NEWS_UPDATE, $params); }
Update article. @param string $mediaId @param string $article @param int $index @return array @throws \yii\httpclient\Exception
entailment
public function get1($mediaId) { /** @var \yii\httpclient\Response $response */ $response = $request = $this->getHttpClient()->createRequest() ->setUrl([ self::API_GET, 'media_id' => $mediaId ]) ->setMethod('GET') ->send(); if ($response->isOk) { } // foreach ($response->getHeader('Content-Type') as $mime) { // if (preg_match('/(image|video|audio)/i', $mime)) { // return $response->getBody(); // } // } // // $json = $this->getHttp()->parseJSON($response); // // // XXX: 微信开发这帮混蛋,尼玛文件二进制输出不带header,简直日了!!! // if (!$json) { // return $response->getBody(); // } // // $this->checkAndThrow($json); return $json; }
Fetch material. @param string $mediaId @return mixed
entailment
protected function uploadMedia($type, $path, array $form = []) { if (!file_exists($path) || !is_readable($path)) { throw new InvalidArgumentException("File does not exist, or the file is unreadable: '$path'"); } $form['type'] = $type; return $this->upload($this->getAPIByType($type), ['media' => $path], $form); }
Upload material. @param string $type @param string $path @param array $form @return mixed @throws \yii\httpclient\Exception
entailment
public function getAPIByType($type) { switch ($type) { case 'news_image': $api = self::API_NEWS_IMAGE_UPLOAD; break; default: $api = self::API_UPLOAD; } return $api; }
Get API by type. @param string $type @return string
entailment
public function run() { if (Yii::$app->user->isGuest) { $client = Yii::$app->wechat->oauth; return $this->auth($client); } else { return $this->controller->goHome(); } }
Runs the action. @return \yii\web\Response @throws \yii\base\NotSupportedException
entailment
public function num_rows() { if (is_int($this->num_rows)) { return $this->num_rows; } elseif (count($this->result_array) > 0) { return $this->num_rows = count($this->result_array); } elseif (count($this->result_object) > 0) { return $this->num_rows = count($this->result_object); } elseif (($num_rows = $this->result_id->rowCount()) > 0) { return $this->num_rows = $num_rows; } return $this->num_rows = count($this->result_array()); }
Number of rows in the result set @return int
entailment
public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { // Might trigger an E_WARNING due to not all subdrivers // supporting getColumnMeta() $field_names[$i] = @$this->result_id->getColumnMeta($i); $field_names[$i] = $field_names[$i]['name']; } return $field_names; }
Fetch Field Names Generates an array of column names @return bool
entailment
public function field_data() { try { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field = $this->result_id->getColumnMeta($i); $retval[$i] = new stdClass(); $retval[$i]->name = $field['name']; $retval[$i]->type = $field['native_type']; $retval[$i]->max_length = ($field['len'] > 0) ? $field['len'] : NULL; $retval[$i]->primary_key = (int) ( ! empty($field['flags']) && in_array('primary_key', $field['flags'], TRUE)); } return $retval; } catch (Exception $e) { if ($this->db->db_debug) { return $this->db->display_error('db_unsupported_feature'); } return FALSE; } }
Field data Generates an array of objects containing field meta-data @return array
entailment
public function setIndustry($industryOne, $industryTwo) { $params = [ 'industry_id1' => $industryOne, 'industry_id2' => $industryTwo, ]; return $this->json(static::API_SET_INDUSTRY, $params); }
设置所属行业 @param int $industryOne 公众号模板消息所属行业编号 @param int $industryTwo 公众号模板消息所属行业编号 @return array @throws \yii\httpclient\Exception
entailment
public function send(array $data = []) { $params = array_merge($this->message, $data); foreach ($params as $key => $value) { if (in_array($key, $this->required, true) && empty($value) && empty($this->message[$key])) { throw new InvalidArgumentException("Attribute '$key' can not be empty!"); } $params[$key] = empty($value) ? $this->message[$key] : $value; } $params['data'] = $this->formatData($params['data']); $this->message = $this->messageBackup; return $this->json(static::API_SEND_NOTICE, $params); }
发送模板消息 @param array $data @return array @throws \yii\httpclient\Exception
entailment
protected function formatData($data) { $return = []; foreach ($data as $key => $item) { if (is_scalar($item)) { $value = $item; $color = $this->defaultColor; } elseif (is_array($item) && !empty($item)) { if (isset($item['value'])) { $value = strval($item['value']); $color = empty($item['color']) ? $this->defaultColor : strval($item['color']); } elseif (count($item) < 2) { $value = array_shift($item); $color = $this->defaultColor; } else { list($value, $color) = $item; } } else { $value = 'error data item.'; $color = $this->defaultColor; } $return[$key] = [ 'value' => $value, 'color' => $color, ]; } return $return; }
格式化模板数据 @param array $data @return array
entailment
public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field_names[] = $this->result_id->columnName($i); } return $field_names; }
Fetch Field Names Generates an array of column names @return array
entailment
public function field_data() { static $data_types = array( SQLITE3_INTEGER => 'integer', SQLITE3_FLOAT => 'float', SQLITE3_TEXT => 'text', SQLITE3_BLOB => 'blob', SQLITE3_NULL => 'null' ); $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $this->result_id->columnName($i); $type = $this->result_id->columnType($i); $retval[$i]->type = isset($data_types[$type]) ? $data_types[$type] : $type; $retval[$i]->max_length = NULL; } return $retval; }
Field data Generates an array of objects containing field meta-data @return array
entailment
public function free_result() { if (is_object($this->result_id)) { $this->result_id->finalize(); $this->result_id = NULL; } }
Free the result @return void
entailment
protected function _fetch_object($class_name = 'stdClass') { // No native support for fetching rows as objects if (($row = $this->result_id->fetchArray(SQLITE3_ASSOC)) === FALSE) { return FALSE; } elseif ($class_name === 'stdClass') { return (object) $row; } $class_name = new $class_name(); foreach (array_keys($row) as $key) { $class_name->$key = $row[$key]; } return $class_name; }
Result - object Returns the result set as an object @param string $class_name @return object
entailment
public function registerAssets() { $config = Yii::$app->wechat->js->config($this->apiList); $view = $this->getView(); WechatAsset::register($view); $view->registerJs("wx.config({$config});wx.error(function(res){console.error(res.errMsg);});wx.ready(function (){console.info('wechat jssdk init.');});", View::POS_END); }
Registers the needed assets
entailment
public function list_fields() { $field_names = array(); $this->result_id->field_seek(0); while ($field = $this->result_id->fetch_field()) { $field_names[] = $field->name; } return $field_names; }
Fetch Field Names Generates an array of column names @return array
entailment
public function field_data() { $retval = array(); $field_data = $this->result_id->fetch_fields(); for ($i = 0, $c = count($field_data); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $field_data[$i]->name; $retval[$i]->type = $field_data[$i]->type; $retval[$i]->max_length = $field_data[$i]->max_length; $retval[$i]->primary_key = (int) ($field_data[$i]->flags & 2); $retval[$i]->default = $field_data[$i]->def; } return $retval; }
Field data Generates an array of objects containing field meta-data @return array
entailment
public function free_result() { if (is_object($this->result_id)) { $this->result_id->free(); $this->result_id = FALSE; } }
Free the result @return void
entailment
public function db_connect($persistent = FALSE) { return ($persistent === TRUE) ? odbc_pconnect($this->dsn, $this->username, $this->password) : odbc_connect($this->dsn, $this->username, $this->password); }
Non-persistent database connection @param bool $persistent @return resource
entailment
protected function _trans_commit() { if (odbc_commit($this->conn_id)) { odbc_autocommit($this->conn_id, TRUE); return TRUE; } return FALSE; }
Commit Transaction @return bool
entailment
protected function _trans_rollback() { if (odbc_rollback($this->conn_id)) { odbc_autocommit($this->conn_id, TRUE); return TRUE; } return FALSE; }
Rollback Transaction @return bool
entailment
public function list_databases() { if (isset($this->db->data_cache['db_names'])) { return $this->db->data_cache['db_names']; } return $this->db->data_cache['db_names'] = cubrid_list_dbs($this->db->conn_id); }
List databases @return array
entailment
protected function _backup($filename) { if ($service = ibase_service_attach($this->db->hostname, $this->db->username, $this->db->password)) { $res = ibase_backup($service, $this->db->database, $filename.'.fbk'); // Close the service connection ibase_service_detach($service); return $res; } return FALSE; }
Export @param string $filename @return mixed
entailment
public function db_connect($persistent = FALSE, $conn_id = NULL) { $client_flags = ($this->compress === FALSE) ? 0 : MYSQL_CLIENT_COMPRESS; if ($this->encrypt === TRUE) { $client_flags = $client_flags | MYSQL_CLIENT_SSL; } if( $conn_id && is_resource($conn_id) ){ $this->conn_id = $conn_id; } else { // Error suppression is necessary mostly due to PHP 5.5+ issuing E_DEPRECATED messages $this->conn_id = ($persistent === true) ? mysql_pconnect($this->hostname, $this->username, $this->password, $client_flags) : mysql_connect($this->hostname, $this->username, $this->password, true, $client_flags); } // ---------------------------------------------------------------- // Select the DB... assuming a database name is specified in the config file if ($this->database !== '' && ! $this->db_select()) { return ($this->db_debug === TRUE) ? $this->display_error('db_unable_to_select', $this->database) : FALSE; } if ($this->stricton && is_resource($this->conn_id)) { $this->simple_query('SET SESSION sql_mode="STRICT_ALL_TABLES"'); } return $this->conn_id; }
Non-persistent database connection @param bool $persistent @param ressource $conn_id Allow to use an already opened connection @return resource
entailment
public function db_select($database = '') { if ($database === '') { $database = $this->database; } if (mysql_select_db($database, $this->conn_id)) { $this->database = $database; return TRUE; } return FALSE; }
Select the database @param string $database @return bool
entailment
public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if ( ! $this->conn_id OR ($version = mysql_get_server_info($this->conn_id)) === FALSE) { return FALSE; } return $this->data_cache['version'] = $version; }
Database version number @return string
entailment
protected function _prep_query($sql) { // mysql_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack // modifies the query so that it a proper number of affected rows is returned. if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { return trim($sql).' WHERE 1=1'; } return $sql; }
Prep the query If needed, each database adapter can prep the query string @param string $sql an SQL query @return string
entailment
protected function _list_tables($prefix_limit = FALSE) { $sql = 'SHOW TABLES FROM '.$this->escape_identifiers($this->database); if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'"; } return $sql; }
List table query Generates a platform-specific query string so that the table names can be fetched @param bool $prefix_limit @return string
entailment
public function field_data($table) { if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length ); $retval[$i]->default = $query[$i]->Default; $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); } return $retval; }
Returns an object with field data @param string $table @return array
entailment
protected function _from_tables() { if ( ! empty($this->qb_join) && count($this->qb_from) > 1) { return '('.implode(', ', $this->qb_from).')'; } return implode(', ', $this->qb_from); }
FROM tables Groups tables in FROM clauses if needed, so there is no confusion about operator precedence. @return string
entailment
public function fetchAccessToken($authCode, array $params = []) { $defaultParams = [ 'appid' => $this->clientId, 'secret' => $this->clientSecret, 'js_code' => $authCode, 'grant_type' => 'authorization_code' ]; $request = $this->createRequest() ->setMethod('GET') ->setUrl($this->tokenUrl) ->setData(array_merge($defaultParams, $params)); $response = $this->sendRequest($request); $token = $this->createToken(['params' => $response]); $this->userParams = $response; $this->setAccessToken($token); return $token; }
获取Token @param string $authCode @param array $params @return \yii\authclient\OAuthToken @throws \yii\authclient\InvalidResponseException
entailment
protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('ADD', 'DROP'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' ALTER COLUMN '; $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql.$this->_process_column($field[$i]); } return $sqls; }
ALTER TABLE @param string $alter_type ALTER type @param string $table Table name @param mixed $field Column definition @return string|string[]
entailment
protected function _attr_unique(&$attributes, &$field) { if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE) { $field['unique'] = ' UNIQUE CONSTRAINT '.$this->db->escape_identifiers($field['name']); } }
Field attribute UNIQUE @param array &$attributes @param array &$field @return void
entailment
public function config(array $APIs, $debug = false, $beta = false, $json = true) { $signPackage = $this->signature(); $config = array_merge(['debug' => $debug, 'beta' => $beta], $signPackage, ['jsApiList' => $APIs]); return $json ? Json::encode($config) : $config; }
Get config json for jsapi. @param array $APIs @param bool $debug @param bool $beta @param bool $json @return array|string
entailment
public function getConfigArray(array $APIs, $debug = false, $beta = false) { return $this->config($APIs, $debug, $beta, false); }
Return jsapi config as a PHP array. @param array $APIs @param bool $debug @param bool $beta @return array
entailment
public function ticket($forceRefresh = false) { $cacheKey = [__CLASS__, 'appId' => Yii::$app->wechat->appId]; if ($forceRefresh || ($ticket = Yii::$app->wechat->cache->get($cacheKey)) === false) { $response = $this->post(self::API_TICKET, ['type' => 'jsapi']); Yii::$app->wechat->cache->set($cacheKey, $response['ticket'], $response['expires_in'] - 500); return $response['ticket']; } return $ticket; }
Get jsticket. @param bool $forceRefresh @return string @throws \yii\httpclient\Exception
entailment
public function signature($url = null, $nonce = null, $timestamp = null) { $url = $url ? $url : $this->getUrl(); $nonce = $nonce ? $nonce : uniqid(); $timestamp = $timestamp ? $timestamp : time(); $ticket = $this->ticket(); $sign = [ 'appId' => Yii::$app->wechat->appId, 'nonceStr' => $nonce, 'timestamp' => $timestamp, 'url' => $url, 'signature' => $this->getSignature($ticket, $nonce, $timestamp, $url), ]; return $sign; }
Build signature. @param string $url @param string $nonce @param int $timestamp @return array @throws \yii\httpclient\Exception
entailment
public function getHttpClient() { if (!is_object($this->_httpClient)) { $this->_httpClient = new Client([ 'requestConfig' => [ 'options' => [ 'timeout' => 30, ] ], 'responseConfig' => [ 'format' => Client::FORMAT_JSON ], ]); $this->_httpClient->on(Client::EVENT_BEFORE_SEND, function (RequestEvent $event) { $url = $event->request->getUrl(); if (is_array($url)) { $url = array_merge($url, [Yii::$app->wechat->accessToken->queryName => Yii::$app->wechat->accessToken->getToken()]); } else { $url = [$url, Yii::$app->wechat->accessToken->queryName => Yii::$app->wechat->accessToken->getToken()]; } $event->request->setUrl($url); }); } return $this->_httpClient; }
获取Http Client @return Client
entailment
public function json($url, $params = []) { if (is_array($params)) { $params = Json::encode($params); } return $this->sendRequest('POST', $url, $params, [ 'content-type' => 'application/json' ]); }
JSON request. @param string|array $url use a string to represent a URL (e.g. `http://some-domain.com`, `item/list`), or an array to represent a URL with query parameters (e.g. `['item/list', 'param1' => 'value1']`). @param string|array $params @return array @throws Exception
entailment
protected function sendRequest($method, $url, $params = [], array $headers = [], $files = []) { $request = $this->getHttpClient()->createRequest() ->setUrl($url) ->setMethod($method) ->setHeaders($headers); if (is_array($params)) { $request->setData($params); } else { $request->setContent($params); } foreach ($files as $name => $fileName) { $request->addFile($name, $fileName); } $response = $request->send(); if (!$response->isOk) { throw new Exception('Request fail. response: ' . $response->content, $response->statusCode); } return $response->data; }
Sends HTTP request. @param string $method request type. @param string|array $url use a string to represent a URL (e.g. `http://some-domain.com`, `item/list`), or an array to represent a URL with query parameters (e.g. `['item/list', 'param1' => 'value1']`). @param string|array $params request params. @param array $headers additional request headers. @param array $files @return array response. @throws Exception on failure.
entailment
protected function checkAndThrow(array $contents) { if (isset($contents['errcode']) && 0 !== $contents['errcode']) { if (empty($contents['errmsg'])) { $contents['errmsg'] = 'Unknown'; } throw new HttpException($contents['errmsg'], $contents['errcode']); } }
Check the array data errors, and Throw exception when the contents contains error. @param array $contents @throws HttpException
entailment
protected function _backup($params = array()) { if (count($params) === 0) { return FALSE; } // Extract the prefs for simplicity extract($params); // Build the output $output = ''; // Do we need to include a statement to disable foreign key checks? if ($foreign_key_checks === FALSE) { $output .= 'SET foreign_key_checks = 0;'.$newline; } foreach ( (array) $tables as $table) { // Is the table in the "ignore" list? if (in_array($table, (array) $ignore, TRUE)) { continue; } // Get the table schema $query = $this->db->query('SHOW CREATE TABLE '.$this->db->escape_identifiers($this->db->database.'.'.$table)); // No result means the table name was invalid if ($query === FALSE) { continue; } // Write out the table schema $output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline; if ($add_drop === TRUE) { $output .= 'DROP TABLE IF EXISTS '.$this->db->protect_identifiers($table).';'.$newline.$newline; } $i = 0; $result = $query->result_array(); foreach ($result[0] as $val) { if ($i++ % 2) { $output .= $val.';'.$newline.$newline; } } // If inserts are not needed we're done... if ($add_insert === FALSE) { continue; } // Grab all the data from the current table $query = $this->db->query('SELECT * FROM '.$this->db->protect_identifiers($table)); if ($query->num_rows() === 0) { continue; } // Fetch the field names and determine if the field is an // integer type. We use this info to decide whether to // surround the data with quotes or not $i = 0; $field_str = ''; $is_int = array(); while ($field = mysql_fetch_field($query->result_id)) { // Most versions of MySQL store timestamp as a string $is_int[$i] = in_array(strtolower(mysql_field_type($query->result_id, $i)), array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'), TRUE); // Create a string of field names $field_str .= $this->db->escape_identifiers($field->name).', '; $i++; } // Trim off the end comma $field_str = preg_replace('/, $/' , '', $field_str); // Build the insert string foreach ($query->result_array() as $row) { $val_str = ''; $i = 0; foreach ($row as $v) { // Is the value NULL? if ($v === NULL) { $val_str .= 'NULL'; } else { // Escape the data if it's not an integer $val_str .= ($is_int[$i] === FALSE) ? $this->db->escape($v) : $v; } // Append a comma $val_str .= ', '; $i++; } // Remove the comma at the end of the string $val_str = preg_replace('/, $/' , '', $val_str); // Build the INSERT string $output .= 'INSERT INTO '.$this->db->protect_identifiers($table).' ('.$field_str.') VALUES ('.$val_str.');'.$newline; } $output .= $newline.$newline; } // Do we need to include a statement to re-enable foreign key checks? if ($foreign_key_checks === FALSE) { $output .= 'SET foreign_key_checks = 1;'.$newline; } return $output; }
Export @param array $params Preferences @return mixed
entailment
protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('ADD', 'DROP'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } // No method of modifying columns is supported return FALSE; }
ALTER TABLE @param string $alter_type ALTER type @param string $table Table name @param mixed $field Column definition @return string|string[]
entailment
protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'].$field['length'] .$field['null'] .$field['unique'] .$field['auto_increment']; }
Process column @param array $field @return string
entailment
protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INTEGER': $attributes['TYPE'] = 'INT'; return; case 'BIGINT': $attributes['TYPE'] = 'INT64'; return; default: return; } }
Field attribute TYPE Performs a data type mapping between different databases. @param array &$attributes @return void
entailment
protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) { if (stripos($field['type'], 'int') !== FALSE) { $field['auto_increment'] = ' AUTO_INCREMENT'; } elseif (strcasecmp($field['type'], 'UUID') === 0) { $field['auto_increment'] = ' AUTO_GENERATE'; } } }
Field attribute AUTO_INCREMENT @param array &$attributes @param array &$field @return void
entailment
public function download($mediaId, $directory, $filename = '') { if (!is_dir($directory) || !is_writable($directory)) { throw new InvalidArgumentException("Directory does not exist or is not writable: '$directory'."); } $filename = $filename ?: $mediaId; $stream = $this->getStream($mediaId); $finfo = new finfo(FILEINFO_MIME); $mime = strstr($finfo->buffer($stream), ';', true); $extensions = FileHelper::getExtensionsByMimeType($mime); $filename .= '.' . array_pop($extensions); $filePath = $directory . '/' . $filename; file_put_contents($filePath, $stream); return $filePath; }
Download temporary material. @param string $mediaId @param string $directory @param string $filename @return string @throws InvalidArgumentException
entailment
public function getStream($mediaId) { $response = $request = $this->getHttpClient()->createRequest() ->setUrl([ self::API_GET, 'media_id' => $mediaId ]) ->setMethod('GET') ->send(); if ($response->isOk) { $json = json_decode($response->content, true); if (JSON_ERROR_NONE === json_last_error()) { $this->checkAndThrow($json); } } return $response->content; }
Fetch item from WeChat server. @param string $mediaId @return mixed @throws \EasyWeChat\Core\Exceptions\RuntimeException
entailment
public function db_connect($persistent = FALSE) { return ($persistent === TRUE) ? ibase_pconnect($this->hostname.':'.$this->database, $this->username, $this->password, $this->char_set) : ibase_connect($this->hostname.':'.$this->database, $this->username, $this->password, $this->char_set); }
Non-persistent database connection @param bool $persistent @return resource
entailment
public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if (($service = ibase_service_attach($this->hostname, $this->username, $this->password))) { $this->data_cache['version'] = ibase_server_info($service, IBASE_SVC_SERVER_VERSION); // Don't keep the service open ibase_service_detach($service); return $this->data_cache['version']; } return FALSE; }
Database version number @return string
entailment
protected function _trans_begin() { if (($trans_handle = ibase_trans($this->conn_id)) === FALSE) { return FALSE; } $this->_ibase_trans = $trans_handle; return TRUE; }
Begin Transaction @return bool
entailment
protected function _limit($sql) { // Limit clause depends on if Interbase or Firebird if (stripos($this->version(), 'firebird') !== FALSE) { $select = 'FIRST '.$this->qb_limit .($this->qb_offset ? ' SKIP '.$this->qb_offset : ''); } else { $select = 'ROWS ' .($this->qb_offset ? $this->qb_offset.' TO '.($this->qb_limit + $this->qb_offset) : $this->qb_limit); } return preg_replace('`SELECT`i', 'SELECT '.$select, $sql, 1); }
LIMIT Generates a platform-specific LIMIT clause @param string $sql SQL Query @return string
entailment
protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "tabname" FROM "syscat"."tables" WHERE "type" = \'T\' AND LOWER("tabschema") = '.$this->escape(strtolower($this->database)); if ($prefix_limit === TRUE && $this->dbprefix !== '') { $sql .= ' AND "tabname" LIKE \''.$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; }
Show table query Generates a platform-specific query string so that the table names can be fetched @param bool $prefix_limit @return string
entailment
protected function _list_columns($table = '') { return 'SELECT "colname" FROM "syscat"."columns" WHERE LOWER("tabschema") = '.$this->escape(strtolower($this->database)).' AND LOWER("tabname") = '.$this->escape(strtolower($table)); }
Show column query Generates a platform-specific query string so that the column names can be fetched @param string $table @return array
entailment
public function field_data($table) { $sql = 'SELECT "colname" AS "name", "typename" AS "type", "default" AS "default", "length" AS "max_length", CASE "keyseq" WHEN NULL THEN 0 ELSE 1 END AS "primary_key" FROM "syscat"."columns" WHERE LOWER("tabschema") = '.$this->escape(strtolower($this->database)).' AND LOWER("tabname") = '.$this->escape(strtolower($table)).' ORDER BY "colno"'; return (($query = $this->query($sql)) !== FALSE) ? $query->result_object() : FALSE; }
Returns an object with field data @param string $table @return array
entailment
protected function _limit($sql) { $sql .= ' FETCH FIRST '.($this->qb_limit + $this->qb_offset).' ROWS ONLY'; return ($this->qb_offset) ? 'SELECT * FROM ('.$sql.') WHERE rownum > '.$this->qb_offset : $sql; }
LIMIT Generates a platform-specific LIMIT clause @param string $sql SQL Query @return string
entailment
protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'DROP') { return parent::_alter_table($alter_type, $table, $field); } elseif ($alter_type === 'CHANGE') { $alter_type = 'MODIFY'; } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $field[$i] = "\n\t".$field[$i]['_literal']; } else { $field[$i]['_literal'] = "\n\t".$this->_process_column($field[$i]); if ( ! empty($field[$i]['comment'])) { $sqls[] = 'COMMENT ON COLUMN ' .$this->db->escape_identifiers($table).'.'.$this->db->escape_identifiers($field[$i]['name']) .' IS '.$field[$i]['comment']; } if ($alter_type === 'MODIFY' && ! empty($field[$i]['new_name'])) { $sqls[] = $sql.' RENAME COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' '.$this->db->escape_identifiers($field[$i]['new_name']); } } } $sql .= ' '.$alter_type.' '; $sql .= (count($field) === 1) ? $field[0] : '('.implode(',', $field).')'; // RENAME COLUMN must be executed after MODIFY array_unshift($sqls, $sql); return $sql; }
ALTER TABLE @param string $alter_type ALTER type @param string $table Table name @param mixed $field Column definition @return string|string[]
entailment
public function preInit(&$config) { // merge core components with custom components foreach ($this->coreComponents() as $id => $component) { if (!isset($config['components'][$id])) { $config['components'][$id] = $component; } elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) { $config['components'][$id]['class'] = $component['class']; } } }
预处理组件 @param array $config
entailment
public function init() { parent::init(); if (empty ($this->appId)) { throw new InvalidConfigException ('The "appId" property must be set.'); } if (empty ($this->appSecret)) { throw new InvalidConfigException ('The "appSecret" property must be set.'); } if ($this->cache !== null) { $this->cache = Instance::ensure($this->cache, Cache::class); } }
Initializes the object. This method is invoked at the end of the constructor after the object is initialized with the given configuration. @throws InvalidConfigException
entailment
public function num_rows() { // sqlsrv_num_rows() doesn't work with the FORWARD and DYNAMIC cursors (FALSE is the same as FORWARD) if ( ! in_array($this->scrollable, array(FALSE, SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_DYNAMIC), TRUE)) { return parent::num_rows(); } return is_int($this->num_rows) ? $this->num_rows : $this->num_rows = sqlsrv_num_rows($this->result_id); }
Number of rows in the result set @return int
entailment
public function list_fields() { $field_names = array(); foreach (sqlsrv_field_metadata($this->result_id) as $offset => $field) { $field_names[] = $field['Name']; } return $field_names; }
Fetch Field Names Generates an array of column names @return array
entailment
public function field_data() { $retval = array(); foreach (sqlsrv_field_metadata($this->result_id) as $i => $field) { $retval[$i] = new stdClass(); $retval[$i]->name = $field['Name']; $retval[$i]->type = $field['Type']; $retval[$i]->max_length = $field['Size']; } return $retval; }
Field data Generates an array of objects containing field meta-data @return array
entailment
public function free_result() { if (is_resource($this->result_id)) { sqlsrv_free_stmt($this->result_id); $this->result_id = FALSE; } }
Free the result @return void
entailment
public function check_path($path = '') { if ($path === '') { if ($this->db->cachedir === '') { return $this->db->cache_off(); } $path = $this->db->cachedir; } // Add a trailing slash to the path if needed $path = realpath($path) ? rtrim(realpath($path), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR : rtrim($path, '/').'/'; if ( ! is_dir($path)) { // If the path is wrong we'll turn off caching return $this->db->cache_off(); } if ( ! is_really_writable($path)) { // If the path is not really writable we'll turn off caching return $this->db->cache_off(); } $this->db->cachedir = $path; return TRUE; }
Set Cache Directory Path @param string $path Path to the cache directory @return bool
entailment
public function read($sql) { $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); $filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql); if (FALSE === ($cachedata = @file_get_contents($filepath))) { return FALSE; } return unserialize($cachedata); }
Retrieve a cached query The URI being requested will become the name of the cache sub-folder. An MD5 hash of the SQL statement will become the cache file name. @param string $sql @return string
entailment
public function write($sql, $object) { $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; $filename = md5($sql); if ( ! is_dir($dir_path) && ! @mkdir($dir_path, 0750)) { return FALSE; } if (write_file($dir_path.$filename, serialize($object)) === FALSE) { return FALSE; } chmod($dir_path.$filename, 0640); return TRUE; }
Write a query to a cache file @param string $sql @param object $object @return bool
entailment
public function delete($segment_one = '', $segment_two = '') { if ($segment_one === '') { $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); } if ($segment_two === '') { $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); } $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; delete_files($dir_path, TRUE); }
Delete cache files within a particular directory @param string $segment_one @param string $segment_two @return void
entailment
public function db_connect($persistent = FALSE) { if ($persistent) { } try { return ( ! $this->password) ? new SQLite3($this->database) : new SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password); } catch (Exception $e) { return FALSE; } }
Non-persistent database connection @param bool $persistent @return SQLite3
entailment
public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } $version = SQLite3::version(); return $this->data_cache['version'] = $version['versionString']; }
Database version number @return string
entailment
protected function _execute($sql) { return $this->is_write_type($sql) ? $this->conn_id->exec($sql) : $this->conn_id->query($sql); }
Execute the query @todo Implement use of SQLite3::querySingle(), if needed @param string $sql @return mixed SQLite3Result object or bool
entailment
public function temporary($sceneId, $expireSeconds = null) { $scene = ['scene_id' => intval($sceneId)]; return $this->create(self::SCENE_QR_TEMPORARY, $scene, true, $expireSeconds); }
Create temporary. @param string $sceneId @param null $expireSeconds @return array @throws \yii\httpclient\Exception
entailment
protected function create($actionName, $actionInfo, $temporary = true, $expireSeconds = null) { $expireSeconds !== null || $expireSeconds = 7 * self::DAY; $params = [ 'action_name' => $actionName, 'action_info' => ['scene' => $actionInfo], ]; if ($temporary) { $params['expire_seconds'] = min($expireSeconds, 30 * self::DAY); } return $this->json(self::API_CREATE, $params); }
Create a QRCode. @param string $actionName @param array $actionInfo @param bool $temporary @param int $expireSeconds @return array @throws \yii\httpclient\Exception
entailment
public function list_fields() { $field_names = array(); mysql_field_seek($this->result_id, 0); while ($field = mysql_fetch_field($this->result_id)) { $field_names[] = $field->name; } return $field_names; }
Fetch Field Names Generates an array of column names @return array
entailment
public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = mysql_field_name($this->result_id, $i); $retval[$i]->type = mysql_field_type($this->result_id, $i); $retval[$i]->max_length = mysql_field_len($this->result_id, $i); $retval[$i]->primary_key = (int) (strpos(mysql_field_flags($this->result_id, $i), 'primary_key') !== FALSE); } return $retval; }
Field data Generates an array of objects containing field meta-data @return array
entailment
public function free_result() { if (is_resource($this->result_id)) { mysql_free_result($this->result_id); $this->result_id = FALSE; } }
Free the result @return void
entailment
public function db_connect($persistent = FALSE) { $error = NULL; $conn_id = ($persistent === TRUE) ? sqlite_popen($this->database, 0666, $error) : sqlite_open($this->database, 0666, $error); isset($error); return $conn_id; }
Non-persistent database connection @param bool $persistent @return resource
entailment
protected function _execute($sql) { return $this->is_write_type($sql) ? sqlite_exec($this->conn_id, $sql) : sqlite_query($this->conn_id, $sql); }
Execute the query @param string $sql an SQL query @return resource
entailment
public function num_rows() { return is_int($this->num_rows) ? $this->num_rows : $this->num_rows = @sqlite_num_rows($this->result_id); }
Number of rows in the result set @return int
entailment
public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field_names[$i] = sqlite_field_name($this->result_id, $i); } return $field_names; }
Fetch Field Names Generates an array of column names @return array
entailment
public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = sqlite_field_name($this->result_id, $i); $retval[$i]->type = NULL; $retval[$i]->max_length = NULL; } return $retval; }
Field data Generates an array of objects containing field meta-data @return array
entailment
protected function isLocalNetwork($addr) { // local network IPv6 if (strpos($addr, ':') !== false) { return strpos($addr, 'fc00::') === 0; } if (($long = ip2long($addr)) === false) { return false; } return ($long >= ip2long('10.0.0.0') && $long <= ip2long('10.255.255.255')) || ($long >= ip2long('172.16.0.0') && $long <= ip2long('172.31.255.255')) || ($long >= ip2long('192.168.0.0') && $long <= ip2long('192.168.255.255')) ; }
@param string $addr @return bool
entailment
protected function validate($code) { $color = str_replace('#', '', DefinedColor::find($code)); if (strlen($color) === 3) { $color = $color[0] . $color[0] . $color[1] . $color[1] . $color[2] . $color[2]; } return preg_match('/^[a-f0-9]{6}$/i', $color) ? $color : false; }
@param string $code @return string|bool
entailment
protected function initialize($color) { return list($this->red, $this->green, $this->blue) = str_split($color, 2); }
@param string $color @return array
entailment
private function containsClassName($className, array $allowedClassNames) { foreach ($allowedClassNames as $allowedClassName) { if (false !== stripos($className, $allowedClassName)) { return true; } } return false; }
@param string $className @param array $allowedClassNames @return bool
entailment