copy dari repo om Irfan

This commit is contained in:
2026-06-13 16:02:07 +10:00
commit db327c0305
5376 changed files with 2770667 additions and 0 deletions
+398
View File
@@ -0,0 +1,398 @@
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* CodeIgniter Curl Class
*
* Work with remote servers via cURL much easier than using the native PHP bindings.
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author Philip Sturgeon
* @license http://philsturgeon.co.uk/code/dbad-license
* @link http://philsturgeon.co.uk/code/codeigniter-curl
*/
class Curl {
protected $_ci; // CodeIgniter instance
protected $response = ''; // Contains the cURL response for debug
protected $session; // Contains the cURL handler for a session
protected $url; // URL of the session
protected $options = array(); // Populates curl_setopt_array
protected $headers = array(); // Populates extra HTTP headers
public $error_code; // Error code returned as an int
public $error_string; // Error message returned as a string
public $info; // Returned after request (elapsed time, etc)
function __construct($url = '')
{
$this->_ci = & get_instance();
log_message('debug', 'cURL Class Initialized');
if ( ! $this->is_enabled())
{
log_message('error', 'cURL Class - PHP was not built with cURL enabled. Rebuild PHP with --with-curl to use cURL.');
}
$url AND $this->create($url);
}
public function __call($method, $arguments)
{
if (in_array($method, array('simple_get', 'simple_post', 'simple_put', 'simple_delete', 'simple_patch')))
{
// Take off the "simple_" and past get/post/put/delete/patch to _simple_call
$verb = str_replace('simple_', '', $method);
array_unshift($arguments, $verb);
return call_user_func_array(array($this, '_simple_call'), $arguments);
}
}
/* =================================================================================
* SIMPLE METHODS
* Using these methods you can make a quick and easy cURL call with one line.
* ================================================================================= */
public function _simple_call($method, $url, $params = array(), $options = array())
{
// Get acts differently, as it doesnt accept parameters in the same way
if ($method === 'get')
{
// If a URL is provided, create new session
$this->create($url.($params ? '?'.http_build_query($params, NULL, '&') : ''));
}
else
{
// If a URL is provided, create new session
$this->create($url);
$this->{$method}($params);
}
// Add in the specific options provided
$this->options($options);
return $this->execute();
}
public function simple_ftp_get($url, $file_path, $username = '', $password = '')
{
// If there is no ftp:// or any protocol entered, add ftp://
if ( ! preg_match('!^(ftp|sftp)://! i', $url))
{
$url = 'ftp://' . $url;
}
// Use an FTP login
if ($username != '')
{
$auth_string = $username;
if ($password != '')
{
$auth_string .= ':' . $password;
}
// Add the user auth string after the protocol
$url = str_replace('://', '://' . $auth_string . '@', $url);
}
// Add the filepath
$url .= $file_path;
$this->option(CURLOPT_BINARYTRANSFER, TRUE);
$this->option(CURLOPT_VERBOSE, TRUE);
return $this->execute();
}
/* =================================================================================
* ADVANCED METHODS
* Use these methods to build up more complex queries
* ================================================================================= */
public function post($params = array(), $options = array())
{
// If its an array (instead of a query string) then format it correctly
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
// Add in the specific options provided
$this->options($options);
$this->http_method('post');
$this->option(CURLOPT_POST, TRUE);
$this->option(CURLOPT_POSTFIELDS, $params);
}
public function put($params = array(), $options = array())
{
// If its an array (instead of a query string) then format it correctly
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
// Add in the specific options provided
$this->options($options);
$this->http_method('put');
$this->option(CURLOPT_POSTFIELDS, $params);
// Override method, I think this overrides $_POST with PUT data but... we'll see eh?
$this->option(CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
}
public function patch($params = array(), $options = array())
{
// If its an array (instead of a query string) then format it correctly
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
// Add in the specific options provided
$this->options($options);
$this->http_method('patch');
$this->option(CURLOPT_POSTFIELDS, $params);
// Override method, I think this overrides $_POST with PATCH data but... we'll see eh?
$this->option(CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PATCH'));
}
public function delete($params, $options = array())
{
// If its an array (instead of a query string) then format it correctly
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
// Add in the specific options provided
$this->options($options);
$this->http_method('delete');
$this->option(CURLOPT_POSTFIELDS, $params);
}
public function set_cookies($params = array())
{
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
$this->option(CURLOPT_COOKIE, $params);
return $this;
}
public function http_header($header, $content = NULL)
{
$this->headers[] = $content ? $header . ': ' . $content : $header;
return $this;
}
public function http_method($method)
{
$this->options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
return $this;
}
public function http_login($username = '', $password = '', $type = 'any')
{
$this->option(CURLOPT_HTTPAUTH, constant('CURLAUTH_' . strtoupper($type)));
$this->option(CURLOPT_USERPWD, $username . ':' . $password);
return $this;
}
public function proxy($url = '', $port = 80)
{
$this->option(CURLOPT_HTTPPROXYTUNNEL, TRUE);
$this->option(CURLOPT_PROXY, $url . ':' . $port);
return $this;
}
public function proxy_login($username = '', $password = '')
{
$this->option(CURLOPT_PROXYUSERPWD, $username . ':' . $password);
return $this;
}
public function ssl($verify_peer = TRUE, $verify_host = 2, $path_to_cert = NULL)
{
if ($verify_peer)
{
$this->option(CURLOPT_SSL_VERIFYPEER, TRUE);
$this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
if (isset($path_to_cert)) {
$path_to_cert = realpath($path_to_cert);
$this->option(CURLOPT_CAINFO, $path_to_cert);
}
}
else
{
$this->option(CURLOPT_SSL_VERIFYPEER, FALSE);
$this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
}
return $this;
}
public function options($options = array())
{
// Merge options in with the rest - done as array_merge() does not overwrite numeric keys
foreach ($options as $option_code => $option_value)
{
$this->option($option_code, $option_value);
}
// Set all options provided
curl_setopt_array($this->session, $this->options);
return $this;
}
public function option($code, $value, $prefix = 'opt')
{
if (is_string($code) && !is_numeric($code))
{
$code = constant('CURL' . strtoupper($prefix) . '_' . strtoupper($code));
}
$this->options[$code] = $value;
return $this;
}
// Start a session from a URL
public function create($url)
{
// If no a protocol in URL, assume its a CI link
if ( ! preg_match('!^\w+://! i', $url))
{
$this->_ci->load->helper('url');
$url = site_url($url);
}
$this->url = $url;
$this->session = curl_init($this->url);
return $this;
}
// End a session and return the results
public function execute()
{
// Set two default options, and merge any extra ones in
if ( ! isset($this->options[CURLOPT_TIMEOUT]))
{
$this->options[CURLOPT_TIMEOUT] = 30;
}
if ( ! isset($this->options[CURLOPT_RETURNTRANSFER]))
{
$this->options[CURLOPT_RETURNTRANSFER] = TRUE;
}
if ( ! isset($this->options[CURLOPT_FAILONERROR]))
{
$this->options[CURLOPT_FAILONERROR] = TRUE;
}
// Only set follow location if not running securely
if ( ! ini_get('safe_mode') && ! ini_get('open_basedir'))
{
// Ok, follow location is not set already so lets set it to true
if ( ! isset($this->options[CURLOPT_FOLLOWLOCATION]))
{
$this->options[CURLOPT_FOLLOWLOCATION] = TRUE;
}
}
if ( ! empty($this->headers))
{
$this->option(CURLOPT_HTTPHEADER, $this->headers);
}
$this->options();
// Execute the request & and hide all output
$this->response = curl_exec($this->session);
$this->info = curl_getinfo($this->session);
// Request failed
if ($this->response === FALSE)
{
$errno = curl_errno($this->session);
$error = curl_error($this->session);
curl_close($this->session);
$this->set_defaults();
$this->error_code = $errno;
$this->error_string = $error;
return FALSE;
}
// Request successful
else
{
curl_close($this->session);
$this->last_response = $this->response;
$this->set_defaults();
return $this->last_response;
}
}
public function is_enabled()
{
return function_exists('curl_init');
}
public function debug()
{
echo "=============================================<br/>\n";
echo "<h2>CURL Test</h2>\n";
echo "=============================================<br/>\n";
echo "<h3>Response</h3>\n";
echo "<code>" . nl2br(htmlentities($this->last_response)) . "</code><br/>\n\n";
if ($this->error_string)
{
echo "=============================================<br/>\n";
echo "<h3>Errors</h3>";
echo "<strong>Code:</strong> " . $this->error_code . "<br/>\n";
echo "<strong>Message:</strong> " . $this->error_string . "<br/>\n";
}
echo "=============================================<br/>\n";
echo "<h3>Info</h3>";
echo "<pre>";
print_r($this->info);
echo "</pre>";
}
public function debug_request()
{
return array(
'url' => $this->url
);
}
public function set_defaults()
{
$this->response = '';
$this->headers = array();
$this->options = array();
$this->error_code = NULL;
$this->error_string = '';
$this->session = NULL;
}
}
/* End of file Curl.php */
/* Location: ./application/libraries/Curl.php */
+640
View File
@@ -0,0 +1,640 @@
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Ignited Datatables
*
* This is a wrapper class/library based on the native Datatables server-side implementation by Allan Jardine
* found at http://datatables.net/examples/data_sources/server_side.html for CodeIgniter
*
* @package CodeIgniter
* @subpackage libraries
* @category library
* @version 2.0 <beta>
* @author Vincent Bambico <metal.conspiracy@gmail.com>
* Yusuf Ozdemir <yusuf@ozdemir.be>
* @link http://ellislab.com/forums/viewthread/160896/
*/
class Datatables
{
/**
* Global container variables for chained argument results
*
*/
private $ci;
private $table;
private $distinct;
private $group_by = array();
private $select = array();
private $joins = array();
private $columns = array();
private $where = array();
private $or_where = array();
private $where_in = array();
private $like = array();
private $or_like = array();
private $filter = array();
private $add_columns = array();
private $edit_columns = array();
private $unset_columns = array();
/**
* Copies an instance of CI
*/
public function __construct()
{
$this->ci =& get_instance();
}
/**
* If you establish multiple databases in config/database.php this will allow you to
* set the database (other than $active_group) - more info: http://ellislab.com/forums/viewthread/145901/#712942
*/
public function set_database($db_name)
{
$db_data = $this->ci->load->database($db_name, TRUE);
$this->ci->db = $db_data;
}
/**
* Generates the SELECT portion of the query
*
* @param string $columns
* @param bool $backtick_protect
* @return mixed
*/
public function select($columns, $backtick_protect = TRUE)
{
foreach($this->explode(',', $columns) as $val)
{
$column = trim(preg_replace('/(.*)\s+as\s+(\w*)/i', '$2', $val));
$column = preg_replace('/.*\.(.*)/i', '$1', $column); // get name after `.`
$this->columns[] = $column;
$this->select[$column] = trim(preg_replace('/(.*)\s+as\s+(\w*)/i', '$1', $val));
}
$this->ci->db->select($columns, $backtick_protect);
return $this;
}
/**
* Generates the DISTINCT portion of the query
*
* @param string $column
* @return mixed
*/
public function distinct($column)
{
$this->distinct = $column;
$this->ci->db->distinct($column);
return $this;
}
/**
* Generates a custom GROUP BY portion of the query
*
* @param string $val
* @return mixed
*/
public function group_by($val)
{
$this->group_by[] = $val;
$this->ci->db->group_by($val);
return $this;
}
/**
* Generates the FROM portion of the query
*
* @param string $table
* @return mixed
*/
public function from($table)
{
$this->table = $table;
return $this;
}
/**
* Generates the JOIN portion of the query
*
* @param string $table
* @param string $fk
* @param string $type
* @return mixed
*/
public function join($table, $fk, $type = NULL)
{
$this->joins[] = array($table, $fk, $type);
$this->ci->db->join($table, $fk, $type);
return $this;
}
/**
* Generates the WHERE portion of the query
*
* @param mixed $key_condition
* @param string $val
* @param bool $backtick_protect
* @return mixed
*/
public function where($key_condition, $val = NULL, $backtick_protect = TRUE)
{
$this->where[] = array($key_condition, $val, $backtick_protect);
$this->ci->db->where($key_condition, $val, $backtick_protect);
return $this;
}
/**
* Generates the WHERE portion of the query
*
* @param mixed $key_condition
* @param string $val
* @param bool $backtick_protect
* @return mixed
*/
public function or_where($key_condition, $val = NULL, $backtick_protect = TRUE)
{
$this->or_where[] = array($key_condition, $val, $backtick_protect);
$this->ci->db->or_where($key_condition, $val, $backtick_protect);
return $this;
}
/**
* Generates the WHERE IN portion of the query
*
* @param mixed $key_condition
* @param string $val
* @param bool $backtick_protect
* @return mixed
*/
public function where_in($key_condition, $val = NULL)
{
$this->where_in[] = array($key_condition, $val);
$this->ci->db->where_in($key_condition, $val);
return $this;
}
/**
* Generates the WHERE portion of the query
*
* @param mixed $key_condition
* @param string $val
* @param bool $backtick_protect
* @return mixed
*/
public function filter($key_condition, $val = NULL, $backtick_protect = TRUE)
{
$this->filter[] = array($key_condition, $val, $backtick_protect);
return $this;
}
/**
* Generates a %LIKE% portion of the query
*
* @param mixed $key_condition
* @param string $val
* @param bool $backtick_protect
* @return mixed
*/
public function like($key_condition, $val = NULL, $side = 'both')
{
$this->like[] = array($key_condition, $val, $side);
$this->ci->db->like($key_condition, $val, $side);
return $this;
}
/**
* Generates the OR %LIKE% portion of the query
*
* @param mixed $key_condition
* @param string $val
* @param bool $backtick_protect
* @return mixed
*/
public function or_like($key_condition, $val = NULL, $side = 'both')
{
$this->or_like[] = array($key_condition, $val, $side);
$this->ci->db->or_like($key_condition, $val, $side);
return $this;
}
/**
* Sets additional column variables for adding custom columns
*
* @param string $column
* @param string $content
* @param string $match_replacement
* @return mixed
*/
public function add_column($column, $content, $match_replacement = NULL)
{
$this->add_columns[$column] = array('content' => $content, 'replacement' => $this->explode(',', $match_replacement));
return $this;
}
/**
* Sets additional column variables for editing columns
*
* @param string $column
* @param string $content
* @param string $match_replacement
* @return mixed
*/
public function edit_column($column, $content, $match_replacement)
{
$this->edit_columns[$column][] = array('content' => $content, 'replacement' => $this->explode(',', $match_replacement));
return $this;
}
/**
* Unset column
*
* @param string $column
* @return mixed
*/
public function unset_column($column)
{
$column=explode(',',$column);
$this->unset_columns=array_merge($this->unset_columns,$column);
return $this;
}
/**
* Builds all the necessary query segments and performs the main query based on results set from chained statements
*
* @param string $output
* @param string $charset
* @return string
*/
public function generate($output = 'json', $charset = 'UTF-8')
{
if(strtolower($output) == 'json')
$this->get_paging();
$this->get_ordering();
$this->get_filtering();
return $this->produce_output(strtolower($output), strtolower($charset));
}
/**
* Generates the LIMIT portion of the query
*
* @return mixed
*/
private function get_paging()
{
$iStart = $this->ci->input->post('start');
$iLength = $this->ci->input->post('length');
if($iLength != '' && $iLength != '-1')
$this->ci->db->limit($iLength, ($iStart)? $iStart : 0);
}
/**
* Generates the ORDER BY portion of the query
*
* @return mixed
*/
private function get_ordering()
{
$Data = $this->ci->input->post('columns');
if ($this->ci->input->post('order'))
foreach ($this->ci->input->post('order') as $key)
if($this->check_cType())
$this->ci->db->order_by($Data[$key['column']]['data'], $key['dir']);
else
$this->ci->db->order_by($this->columns[$key['column']] , $key['dir']);
}
/**
* Generates a %LIKE% portion of the query
*
* @return mixed
*/
private function get_filtering()
{
$mColArray = $this->ci->input->post('columns');
$sWhere = '';
$search = $this->ci->input->post('search');
$sSearch = $this->ci->db->escape_like_str(trim($search['value']));
$columns = array_values(array_diff($this->columns, $this->unset_columns));
if($sSearch != '')
for($i = 0; $i < count($mColArray); $i++)
if ($mColArray[$i]['searchable'] == 'true' && !array_key_exists($mColArray[$i]['data'], $this->add_columns))
if($this->check_cType())
$sWhere .= $this->select[$mColArray[$i]['data']] . " LIKE '%" . $sSearch . "%' OR ";
else
$sWhere .= $this->select[$this->columns[$i]] . " LIKE '%" . $sSearch . "%' OR ";
$sWhere = substr_replace($sWhere, '', -3);
if($sWhere != '')
$this->ci->db->where('(' . $sWhere . ')');
// TODO : sRangeSeparator
foreach($this->filter as $val)
$this->ci->db->where($val[0], $val[1], $val[2]);
}
/**
* Compiles the select statement based on the other functions called and runs the query
*
* @return mixed
*/
private function get_display_result()
{
return $this->ci->db->get($this->table);
}
/**
* Builds an encoded string data. Returns JSON by default, and an array of aaData if output is set to raw.
*
* @param string $output
* @param string $charset
* @return mixed
*/
private function produce_output($output, $charset)
{
$aaData = array();
$rResult = $this->get_display_result();
if($output == 'json')
{
$iTotal = $this->get_total_results();
$iFilteredTotal = $this->get_total_results(TRUE);
}
foreach($rResult->result_array() as $row_key => $row_val)
{
$aaData[$row_key] = ($this->check_cType())? $row_val : array_values($row_val);
foreach($this->add_columns as $field => $val)
if($this->check_cType())
$aaData[$row_key][$field] = $this->exec_replace($val, $aaData[$row_key]);
else
$aaData[$row_key][] = $this->exec_replace($val, $aaData[$row_key]);
foreach($this->edit_columns as $modkey => $modval)
foreach($modval as $val)
$aaData[$row_key][($this->check_cType())? $modkey : array_search($modkey, $this->columns)] = $this->exec_replace($val, $aaData[$row_key]);
$aaData[$row_key] = array_diff_key($aaData[$row_key], ($this->check_cType())? $this->unset_columns : array_intersect($this->columns, $this->unset_columns));
if(!$this->check_cType())
$aaData[$row_key] = array_values($aaData[$row_key]);
}
if($output == 'json')
{
$sOutput = array
(
'draw' => intval($this->ci->input->post('draw')),
'recordsTotal' => $iTotal,
'recordsFiltered' => $iFilteredTotal,
'data' => $aaData
);
if($charset == 'utf-8')
return json_encode($sOutput);
else
return $this->jsonify($sOutput);
}
else
return array('aaData' => $aaData);
}
/**
* Get result count
*
* @return integer
*/
private function get_total_results($filtering = FALSE)
{
if($filtering)
$this->get_filtering();
foreach($this->joins as $val)
$this->ci->db->join($val[0], $val[1], $val[2]);
foreach($this->where as $val)
$this->ci->db->where($val[0], $val[1], $val[2]);
foreach($this->or_where as $val)
$this->ci->db->or_where($val[0], $val[1], $val[2]);
foreach($this->where_in as $val)
$this->ci->db->where_in($val[0], $val[1]);
foreach($this->group_by as $val)
$this->ci->db->group_by($val);
foreach($this->like as $val)
$this->ci->db->like($val[0], $val[1], $val[2]);
foreach($this->or_like as $val)
$this->ci->db->or_like($val[0], $val[1], $val[2]);
if(strlen($this->distinct) > 0)
{
$this->ci->db->distinct($this->distinct);
$this->ci->db->select($this->columns);
}
$query = $this->ci->db->get($this->table, NULL, NULL, FALSE);
return $query->num_rows();
}
/**
* Runs callback functions and makes replacements
*
* @param mixed $custom_val
* @param mixed $row_data
* @return string $custom_val['content']
*/
private function exec_replace($custom_val, $row_data)
{
$replace_string = '';
// Go through our array backwards, else $1 (foo) will replace $11, $12 etc with foo1, foo2 etc
$custom_val['replacement'] = array_reverse($custom_val['replacement'], true);
if(isset($custom_val['replacement']) && is_array($custom_val['replacement']))
{
//Added this line because when the replacement has over 10 elements replaced the variable "$1" first by the "$10"
$custom_val['replacement'] = array_reverse($custom_val['replacement'], true);
foreach($custom_val['replacement'] as $key => $val)
{
$sval = preg_replace("/(?<!\w)([\'\"])(.*)\\1(?!\w)/i", '$2', trim($val));
if(preg_match('/(\w+::\w+|\w+)\((.*)\)/i', $val, $matches) && is_callable($matches[1]))
{
$func = $matches[1];
$args = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|" . "[\s,]*'([^']+)'[\s,]*|" . "[,]+/", $matches[2], 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach($args as $args_key => $args_val)
{
$args_val = preg_replace("/(?<!\w)([\'\"])(.*)\\1(?!\w)/i", '$2', trim($args_val));
$args[$args_key] = (in_array($args_val, $this->columns))? ($row_data[($this->check_cType())? $args_val : array_search($args_val, $this->columns)]) : $args_val;
}
$replace_string = call_user_func_array($func, $args);
}
elseif(in_array($sval, $this->columns))
$replace_string = $row_data[($this->check_cType())? $sval : array_search($sval, $this->columns)];
else
$replace_string = $sval;
$custom_val['content'] = str_ireplace('$' . ($key + 1), $replace_string, $custom_val['content']);
}
}
return $custom_val['content'];
}
/**
* Check column type -numeric or column name
*
* @return bool
*/
private function check_cType()
{
$column = $this->ci->input->post('columns');
if(is_numeric($column[0]['data']))
return FALSE;
else
return TRUE;
}
/**
* Return the difference of open and close characters
*
* @param string $str
* @param string $open
* @param string $close
* @return string $retval
*/
private function balanceChars($str, $open, $close)
{
$openCount = substr_count($str, $open);
$closeCount = substr_count($str, $close);
$retval = $openCount - $closeCount;
return $retval;
}
/**
* Explode, but ignore delimiter until closing characters are found
*
* @param string $delimiter
* @param string $str
* @param string $open
* @param string $close
* @return mixed $retval
*/
private function explode($delimiter, $str, $open = '(', $close=')')
{
$retval = array();
$hold = array();
$balance = 0;
$parts = explode($delimiter, $str);
foreach($parts as $part)
{
$hold[] = $part;
$balance += $this->balanceChars($part, $open, $close);
if($balance < 1)
{
$retval[] = implode($delimiter, $hold);
$hold = array();
$balance = 0;
}
}
if(count($hold) > 0)
$retval[] = implode($delimiter, $hold);
return $retval;
}
/**
* Workaround for json_encode's UTF-8 encoding if a different charset needs to be used
*
* @param mixed $result
* @return string
*/
private function jsonify($result = FALSE)
{
if(is_null($result))
return 'null';
if($result === FALSE)
return 'false';
if($result === TRUE)
return 'true';
if(is_scalar($result))
{
if(is_float($result))
return floatval(str_replace(',', '.', strval($result)));
if(is_string($result))
{
static $jsonReplaces = array(array('\\', '/', '\n', '\t', '\r', '\b', '\f', '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $result) . '"';
}
else
return $result;
}
$isList = TRUE;
for($i = 0, reset($result); $i < count($result); $i++, next($result))
{
if(key($result) !== $i)
{
$isList = FALSE;
break;
}
}
$json = array();
if($isList)
{
foreach($result as $value)
$json[] = $this->jsonify($value);
return '[' . join(',', $json) . ']';
}
else
{
foreach($result as $key => $value)
$json[] = $this->jsonify($key) . ':' . $this->jsonify($value);
return '{' . join(',', $json) . '}';
}
}
/**
* returns the sql statement of the last query run
* @return type
*/
public function last_query()
{
return $this->ci->db->last_query();
}
}
/* End of file Datatables.php */
/* Location: ./application/libraries/Datatables.php */
+529
View File
@@ -0,0 +1,529 @@
<?php
namespace Restserver\Libraries;
use Exception;
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Format class
* Help convert between various formats such as XML, JSON, CSV, etc.
*
* @author Phil Sturgeon, Chris Kacerguis, @softwarespot
* @license http://www.dbad-license.org/
*/
class Format {
/**
* Array output format
*/
const ARRAY_FORMAT = 'array';
/**
* Comma Separated Value (CSV) output format
*/
const CSV_FORMAT = 'csv';
/**
* Json output format
*/
const JSON_FORMAT = 'json';
/**
* HTML output format
*/
const HTML_FORMAT = 'html';
/**
* PHP output format
*/
const PHP_FORMAT = 'php';
/**
* Serialized output format
*/
const SERIALIZED_FORMAT = 'serialized';
/**
* XML output format
*/
const XML_FORMAT = 'xml';
/**
* Default format of this class
*/
const DEFAULT_FORMAT = self::JSON_FORMAT; // Couldn't be DEFAULT, as this is a keyword
/**
* CodeIgniter instance
*
* @var object
*/
private $_CI;
/**
* Data to parse
*
* @var mixed
*/
protected $_data = [];
/**
* Type to convert from
*
* @var string
*/
protected $_from_type = NULL;
/**
* DO NOT CALL THIS DIRECTLY, USE factory()
*
* @param NULL $data
* @param NULL $from_type
* @throws Exception
*/
public function __construct($data = NULL, $from_type = NULL)
{
// Get the CodeIgniter reference
$this->_CI = &get_instance();
// Load the inflector helper
$this->_CI->load->helper('inflector');
// If the provided data is already formatted we should probably convert it to an array
if ($from_type !== NULL)
{
if (method_exists($this, '_from_'.$from_type))
{
$data = call_user_func([$this, '_from_'.$from_type], $data);
}
else
{
throw new Exception('Format class does not support conversion from "'.$from_type.'".');
}
}
// Set the member variable to the data passed
$this->_data = $data;
}
/**
* Create an instance of the format class
* e.g: echo $this->format->factory(['foo' => 'bar'])->to_csv();
*
* @param mixed $data Data to convert/parse
* @param string $from_type Type to convert from e.g. json, csv, html
*
* @return object Instance of the format class
*/
public static function factory($data, $from_type = NULL)
{
// $class = __CLASS__;
// return new $class();
return new static($data, $from_type);
}
// FORMATTING OUTPUT ---------------------------------------------------------
/**
* Format data as an array
*
* @param mixed|NULL $data Optional data to pass, so as to override the data passed
* to the constructor
* @return array Data parsed as an array; otherwise, an empty array
*/
public function to_array($data = NULL)
{
// If no data is passed as a parameter, then use the data passed
// via the constructor
if ($data === NULL && func_num_args() === 0)
{
$data = $this->_data;
}
// Cast as an array if not already
if (is_array($data) === FALSE)
{
$data = (array) $data;
}
$array = [];
foreach ((array) $data as $key => $value)
{
if (is_object($value) === TRUE || is_array($value) === TRUE)
{
$array[$key] = $this->to_array($value);
}
else
{
$array[$key] = $value;
}
}
return $array;
}
/**
* Format data as XML
*
* @param mixed|NULL $data Optional data to pass, so as to override the data passed
* to the constructor
* @param NULL $structure
* @param string $basenode
* @return mixed
*/
public function to_xml($data = NULL, $structure = NULL, $basenode = 'xml')
{
if ($data === NULL && func_num_args() === 0)
{
$data = $this->_data;
}
if ($structure === NULL)
{
$structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />");
}
// Force it to be something useful
if (is_array($data) === FALSE && is_object($data) === FALSE)
{
$data = (array) $data;
}
foreach ($data as $key => $value)
{
//change false/true to 0/1
if (is_bool($value))
{
$value = (int) $value;
}
// no numeric keys in our xml please!
if (is_numeric($key))
{
// make string key...
$key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
}
// replace anything not alpha numeric
$key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
if ($key === '_attributes' && (is_array($value) || is_object($value)))
{
$attributes = $value;
if (is_object($attributes))
{
$attributes = get_object_vars($attributes);
}
foreach ($attributes as $attribute_name => $attribute_value)
{
$structure->addAttribute($attribute_name, $attribute_value);
}
}
// if there is another array found recursively call this function
elseif (is_array($value) || is_object($value))
{
$node = $structure->addChild($key);
// recursive call.
$this->to_xml($value, $node, $key);
}
else
{
// add single node.
$value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
$structure->addChild($key, $value);
}
}
return $structure->asXML();
}
/**
* Format data as HTML
*
* @param mixed|NULL $data Optional data to pass, so as to override the data passed
* to the constructor
* @return mixed
*/
public function to_html($data = NULL)
{
// If no data is passed as a parameter, then use the data passed
// via the constructor
if ($data === NULL && func_num_args() === 0)
{
$data = $this->_data;
}
// Cast as an array if not already
if (is_array($data) === FALSE)
{
$data = (array) $data;
}
// Check if it's a multi-dimensional array
if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE))
{
// Multi-dimensional array
$headings = array_keys($data[0]);
}
else
{
// Single array
$headings = array_keys($data);
$data = [$data];
}
// Load the table library
$this->_CI->load->library('table');
$this->_CI->table->set_heading($headings);
foreach ($data as $row)
{
// Suppressing the "array to string conversion" notice
// Keep the "evil" @ here
$row = @array_map('strval', $row);
$this->_CI->table->add_row($row);
}
return $this->_CI->table->generate();
}
/**
* @link http://www.metashock.de/2014/02/create-csv-file-in-memory-php/
* @param mixed|NULL $data Optional data to pass, so as to override the data passed
* to the constructor
* @param string $delimiter The optional delimiter parameter sets the field
* delimiter (one character only). NULL will use the default value (,)
* @param string $enclosure The optional enclosure parameter sets the field
* enclosure (one character only). NULL will use the default value (")
* @return string A csv string
*/
public function to_csv($data = NULL, $delimiter = ',', $enclosure = '"')
{
// Use a threshold of 1 MB (1024 * 1024)
$handle = fopen('php://temp/maxmemory:1048576', 'w');
if ($handle === FALSE)
{
return NULL;
}
// If no data is passed as a parameter, then use the data passed
// via the constructor
if ($data === NULL && func_num_args() === 0)
{
$data = $this->_data;
}
// If NULL, then set as the default delimiter
if ($delimiter === NULL)
{
$delimiter = ',';
}
// If NULL, then set as the default enclosure
if ($enclosure === NULL)
{
$enclosure = '"';
}
// Cast as an array if not already
if (is_array($data) === FALSE)
{
$data = (array) $data;
}
// Check if it's a multi-dimensional array
if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE))
{
// Multi-dimensional array
$headings = array_keys($data[0]);
}
else
{
// Single array
$headings = array_keys($data);
$data = [$data];
}
// Apply the headings
fputcsv($handle, $headings, $delimiter, $enclosure);
foreach ($data as $record)
{
// If the record is not an array, then break. This is because the 2nd param of
// fputcsv() should be an array
if (is_array($record) === FALSE)
{
break;
}
// Suppressing the "array to string conversion" notice.
// Keep the "evil" @ here.
$record = @ array_map('strval', $record);
// Returns the length of the string written or FALSE
fputcsv($handle, $record, $delimiter, $enclosure);
}
// Reset the file pointer
rewind($handle);
// Retrieve the csv contents
$csv = stream_get_contents($handle);
// Close the handle
fclose($handle);
// Convert UTF-8 encoding to UTF-16LE which is supported by MS Excel
$csv = mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
return $csv;
}
/**
* Encode data as json
*
* @param mixed|NULL $data Optional data to pass, so as to override the data passed
* to the constructor
* @return string Json representation of a value
*/
public function to_json($data = NULL)
{
// If no data is passed as a parameter, then use the data passed
// via the constructor
if ($data === NULL && func_num_args() === 0)
{
$data = $this->_data;
}
// Get the callback parameter (if set)
$callback = $this->_CI->input->get('callback');
if (empty($callback) === TRUE)
{
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
// We only honour a jsonp callback which are valid javascript identifiers
elseif (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback))
{
// Return the data as encoded json with a callback
return $callback.'('.json_encode($data, JSON_UNESCAPED_UNICODE).');';
}
// An invalid jsonp callback function provided.
// Though I don't believe this should be hardcoded here
$data['warning'] = 'INVALID JSONP CALLBACK: '.$callback;
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
/**
* Encode data as a serialized array
*
* @param mixed|NULL $data Optional data to pass, so as to override the data passed
* to the constructor
* @return string Serialized data
*/
public function to_serialized($data = NULL)
{
// If no data is passed as a parameter, then use the data passed
// via the constructor
if ($data === NULL && func_num_args() === 0)
{
$data = $this->_data;
}
return serialize($data);
}
/**
* Format data using a PHP structure
*
* @param mixed|NULL $data Optional data to pass, so as to override the data passed
* to the constructor
* @return mixed String representation of a variable
*/
public function to_php($data = NULL)
{
// If no data is passed as a parameter, then use the data passed
// via the constructor
if ($data === NULL && func_num_args() === 0)
{
$data = $this->_data;
}
return var_export($data, TRUE);
}
// INTERNAL FUNCTIONS
/**
* @param string $data XML string
* @return array XML element object; otherwise, empty array
*/
protected function _from_xml($data)
{
return $data ? (array) simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA) : [];
}
/**
* @param string $data CSV string
* @param string $delimiter The optional delimiter parameter sets the field
* delimiter (one character only). NULL will use the default value (,)
* @param string $enclosure The optional enclosure parameter sets the field
* enclosure (one character only). NULL will use the default value (")
* @return array A multi-dimensional array with the outer array being the number of rows
* and the inner arrays the individual fields
*/
protected function _from_csv($data, $delimiter = ',', $enclosure = '"')
{
// If NULL, then set as the default delimiter
if ($delimiter === NULL)
{
$delimiter = ',';
}
// If NULL, then set as the default enclosure
if ($enclosure === NULL)
{
$enclosure = '"';
}
return str_getcsv($data, $delimiter, $enclosure);
}
/**
* @param string $data Encoded json string
* @return mixed Decoded json string with leading and trailing whitespace removed
*/
protected function _from_json($data)
{
return json_decode(trim($data));
}
/**
* @param string $data Data to unserialize
* @return mixed Unserialized data
*/
protected function _from_serialize($data)
{
return unserialize(trim($data));
}
/**
* @param string $data Data to trim leading and trailing whitespace
* @return string Data with leading and trailing whitespace removed
*/
protected function _from_php($data)
{
return trim($data);
}
}
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+8
View File
@@ -0,0 +1,8 @@
<?php
class pdf {
function __construct() {
include_once APPPATH . '/third_party/fpdf/fpdf.php';
}
}
?>