repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Sha1.php
system/libraries/Sha1.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SHA1 Encoding Class * * Purpose: Provides 160 bit hashing using The Secure Hash Algorithm * developed at the National Institute of Standards and Technology. The 40 * character SHA1 message hash is computationally infeasible to crack. * * This class is a fallback for servers that are not running PHP greater than * 4.3, or do not have the MHASH library. * * This class is based on two scripts: * * Marcus Campbell's PHP implementation (GNU license) * http://www.tecknik.net/sha-1/ * * ...which is based on Paul Johnston's JavaScript version * (BSD license). http://pajhome.org.uk/ * * I encapsulated the functions and wrote one additional method to fix * a hex conversion bug. - Rick Ellis * * @package CodeIgniter * @subpackage Libraries * @category Encryption * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/general/encryption.html */ class CI_SHA1 { public function __construct() { log_message('debug', "SHA1 Class Initialized"); } /** * Generate the Hash * * @access public * @param string * @return string */ function generate($str) { $n = ((strlen($str) + 8) >> 6) + 1; for ($i = 0; $i < $n * 16; $i++) { $x[$i] = 0; } for ($i = 0; $i < strlen($str); $i++) { $x[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8); } $x[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8); $x[$n * 16 - 1] = strlen($str) * 8; $a = 1732584193; $b = -271733879; $c = -1732584194; $d = 271733878; $e = -1009589776; for ($i = 0; $i < count($x); $i += 16) { $olda = $a; $oldb = $b; $oldc = $c; $oldd = $d; $olde = $e; for ($j = 0; $j < 80; $j++) { if ($j < 16) { $w[$j] = $x[$i + $j]; } else { $w[$j] = $this->_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1); } $t = $this->_safe_add($this->_safe_add($this->_rol($a, 5), $this->_ft($j, $b, $c, $d)), $this->_safe_add($this->_safe_add($e, $w[$j]), $this->_kt($j))); $e = $d; $d = $c; $c = $this->_rol($b, 30); $b = $a; $a = $t; } $a = $this->_safe_add($a, $olda); $b = $this->_safe_add($b, $oldb); $c = $this->_safe_add($c, $oldc); $d = $this->_safe_add($d, $oldd); $e = $this->_safe_add($e, $olde); } return $this->_hex($a).$this->_hex($b).$this->_hex($c).$this->_hex($d).$this->_hex($e); } // -------------------------------------------------------------------- /** * Convert a decimal to hex * * @access private * @param string * @return string */ function _hex($str) { $str = dechex($str); if (strlen($str) == 7) { $str = '0'.$str; } return $str; } // -------------------------------------------------------------------- /** * Return result based on iteration * * @access private * @return string */ function _ft($t, $b, $c, $d) { if ($t < 20) return ($b & $c) | ((~$b) & $d); if ($t < 40) return $b ^ $c ^ $d; if ($t < 60) return ($b & $c) | ($b & $d) | ($c & $d); return $b ^ $c ^ $d; } // -------------------------------------------------------------------- /** * Determine the additive constant * * @access private * @return string */ function _kt($t) { if ($t < 20) { return 1518500249; } else if ($t < 40) { return 1859775393; } else if ($t < 60) { return -1894007588; } else { return -899497514; } } // -------------------------------------------------------------------- /** * Add integers, wrapping at 2^32 * * @access private * @return string */ function _safe_add($x, $y) { $lsw = ($x & 0xFFFF) + ($y & 0xFFFF); $msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16); return ($msw << 16) | ($lsw & 0xFFFF); } // -------------------------------------------------------------------- /** * Bitwise rotate a 32-bit number * * @access private * @return integer */ function _rol($num, $cnt) { return ($num << $cnt) | $this->_zero_fill($num, 32 - $cnt); } // -------------------------------------------------------------------- /** * Pad string with zero * * @access private * @return string */ function _zero_fill($a, $b) { $bin = decbin($a); if (strlen($bin) < $b) { $bin = 0; } else { $bin = substr($bin, 0, strlen($bin) - $b); } for ($i=0; $i < $b; $i++) { $bin = "0".$bin; } return bindec($bin); } } // END CI_SHA /* End of file Sha1.php */ /* Location: ./system/libraries/Sha1.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Calendar.php
system/libraries/Calendar.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Calendar Class * * This class enables the creation of calendars * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/calendar.html */ class CI_Calendar { var $CI; var $lang; var $local_time; var $template = ''; var $start_day = 'sunday'; var $month_type = 'long'; var $day_type = 'abr'; var $show_next_prev = FALSE; var $next_prev_url = ''; /** * Constructor * * Loads the calendar language file and sets the default time reference */ public function __construct($config = array()) { $this->CI =& get_instance(); if ( ! in_array('calendar_lang.php', $this->CI->lang->is_loaded, TRUE)) { $this->CI->lang->load('calendar'); } $this->local_time = time(); if (count($config) > 0) { $this->initialize($config); } log_message('debug', "Calendar Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize the user preferences * * Accepts an associative array as input, containing display preferences * * @access public * @param array config preferences * @return void */ function initialize($config = array()) { foreach ($config as $key => $val) { if (isset($this->$key)) { $this->$key = $val; } } } // -------------------------------------------------------------------- /** * Generate the calendar * * @access public * @param integer the year * @param integer the month * @param array the data to be shown in the calendar cells * @return string */ function generate($year = '', $month = '', $data = array()) { // Set and validate the supplied month/year if ($year == '') $year = date("Y", $this->local_time); if ($month == '') $month = date("m", $this->local_time); if (strlen($year) == 1) $year = '200'.$year; if (strlen($year) == 2) $year = '20'.$year; if (strlen($month) == 1) $month = '0'.$month; $adjusted_date = $this->adjust_date($month, $year); $month = $adjusted_date['month']; $year = $adjusted_date['year']; // Determine the total days in the month $total_days = $this->get_total_days($month, $year); // Set the starting day of the week $start_days = array('sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6); $start_day = ( ! isset($start_days[$this->start_day])) ? 0 : $start_days[$this->start_day]; // Set the starting day number $local_date = mktime(12, 0, 0, $month, 1, $year); $date = getdate($local_date); $day = $start_day + 1 - $date["wday"]; while ($day > 1) { $day -= 7; } // Set the current month/year/day // We use this to determine the "today" date $cur_year = date("Y", $this->local_time); $cur_month = date("m", $this->local_time); $cur_day = date("j", $this->local_time); $is_current_month = ($cur_year == $year AND $cur_month == $month) ? TRUE : FALSE; // Generate the template data array $this->parse_template(); // Begin building the calendar output $out = $this->temp['table_open']; $out .= "\n"; $out .= "\n"; $out .= $this->temp['heading_row_start']; $out .= "\n"; // "previous" month link if ($this->show_next_prev == TRUE) { // Add a trailing slash to the URL if needed $this->next_prev_url = preg_replace("/(.+?)\/*$/", "\\1/", $this->next_prev_url); $adjusted_date = $this->adjust_date($month - 1, $year); $out .= str_replace('{previous_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->temp['heading_previous_cell']); $out .= "\n"; } // Heading containing the month/year $colspan = ($this->show_next_prev == TRUE) ? 5 : 7; $this->temp['heading_title_cell'] = str_replace('{colspan}', $colspan, $this->temp['heading_title_cell']); $this->temp['heading_title_cell'] = str_replace('{heading}', $this->get_month_name($month)."&nbsp;".$year, $this->temp['heading_title_cell']); $out .= $this->temp['heading_title_cell']; $out .= "\n"; // "next" month link if ($this->show_next_prev == TRUE) { $adjusted_date = $this->adjust_date($month + 1, $year); $out .= str_replace('{next_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->temp['heading_next_cell']); } $out .= "\n"; $out .= $this->temp['heading_row_end']; $out .= "\n"; // Write the cells containing the days of the week $out .= "\n"; $out .= $this->temp['week_row_start']; $out .= "\n"; $day_names = $this->get_day_names(); for ($i = 0; $i < 7; $i ++) { $out .= str_replace('{week_day}', $day_names[($start_day + $i) %7], $this->temp['week_day_cell']); } $out .= "\n"; $out .= $this->temp['week_row_end']; $out .= "\n"; // Build the main body of the calendar while ($day <= $total_days) { $out .= "\n"; $out .= $this->temp['cal_row_start']; $out .= "\n"; for ($i = 0; $i < 7; $i++) { $out .= ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_start_today'] : $this->temp['cal_cell_start']; if ($day > 0 AND $day <= $total_days) { if (isset($data[$day])) { // Cells with content $temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_content_today'] : $this->temp['cal_cell_content']; $out .= str_replace('{day}', $day, str_replace('{content}', $data[$day], $temp)); } else { // Cells with no content $temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_no_content_today'] : $this->temp['cal_cell_no_content']; $out .= str_replace('{day}', $day, $temp); } } else { // Blank cells $out .= $this->temp['cal_cell_blank']; } $out .= ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_end_today'] : $this->temp['cal_cell_end']; $day++; } $out .= "\n"; $out .= $this->temp['cal_row_end']; $out .= "\n"; } $out .= "\n"; $out .= $this->temp['table_close']; return $out; } // -------------------------------------------------------------------- /** * Get Month Name * * Generates a textual month name based on the numeric * month provided. * * @access public * @param integer the month * @return string */ function get_month_name($month) { if ($this->month_type == 'short') { $month_names = array('01' => 'cal_jan', '02' => 'cal_feb', '03' => 'cal_mar', '04' => 'cal_apr', '05' => 'cal_may', '06' => 'cal_jun', '07' => 'cal_jul', '08' => 'cal_aug', '09' => 'cal_sep', '10' => 'cal_oct', '11' => 'cal_nov', '12' => 'cal_dec'); } else { $month_names = array('01' => 'cal_january', '02' => 'cal_february', '03' => 'cal_march', '04' => 'cal_april', '05' => 'cal_mayl', '06' => 'cal_june', '07' => 'cal_july', '08' => 'cal_august', '09' => 'cal_september', '10' => 'cal_october', '11' => 'cal_november', '12' => 'cal_december'); } $month = $month_names[$month]; if ($this->CI->lang->line($month) === FALSE) { return ucfirst(str_replace('cal_', '', $month)); } return $this->CI->lang->line($month); } // -------------------------------------------------------------------- /** * Get Day Names * * Returns an array of day names (Sunday, Monday, etc.) based * on the type. Options: long, short, abrev * * @access public * @param string * @return array */ function get_day_names($day_type = '') { if ($day_type != '') $this->day_type = $day_type; if ($this->day_type == 'long') { $day_names = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'); } elseif ($this->day_type == 'short') { $day_names = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'); } else { $day_names = array('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'); } $days = array(); foreach ($day_names as $val) { $days[] = ($this->CI->lang->line('cal_'.$val) === FALSE) ? ucfirst($val) : $this->CI->lang->line('cal_'.$val); } return $days; } // -------------------------------------------------------------------- /** * Adjust Date * * This function makes sure that we have a valid month/year. * For example, if you submit 13 as the month, the year will * increment and the month will become January. * * @access public * @param integer the month * @param integer the year * @return array */ function adjust_date($month, $year) { $date = array(); $date['month'] = $month; $date['year'] = $year; while ($date['month'] > 12) { $date['month'] -= 12; $date['year']++; } while ($date['month'] <= 0) { $date['month'] += 12; $date['year']--; } if (strlen($date['month']) == 1) { $date['month'] = '0'.$date['month']; } return $date; } // -------------------------------------------------------------------- /** * Total days in a given month * * @access public * @param integer the month * @param integer the year * @return integer */ function get_total_days($month, $year) { $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); if ($month < 1 OR $month > 12) { return 0; } // Is the year a leap year? if ($month == 2) { if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0)) { return 29; } } return $days_in_month[$month - 1]; } // -------------------------------------------------------------------- /** * Set Default Template Data * * This is used in the event that the user has not created their own template * * @access public * @return array */ function default_template() { return array ( 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', 'heading_row_start' => '<tr>', 'heading_previous_cell' => '<th><a href="{previous_url}">&lt;&lt;</a></th>', 'heading_title_cell' => '<th colspan="{colspan}">{heading}</th>', 'heading_next_cell' => '<th><a href="{next_url}">&gt;&gt;</a></th>', 'heading_row_end' => '</tr>', 'week_row_start' => '<tr>', 'week_day_cell' => '<td>{week_day}</td>', 'week_row_end' => '</tr>', 'cal_row_start' => '<tr>', 'cal_cell_start' => '<td>', 'cal_cell_start_today' => '<td>', 'cal_cell_content' => '<a href="{content}">{day}</a>', 'cal_cell_content_today' => '<a href="{content}"><strong>{day}</strong></a>', 'cal_cell_no_content' => '{day}', 'cal_cell_no_content_today' => '<strong>{day}</strong>', 'cal_cell_blank' => '&nbsp;', 'cal_cell_end' => '</td>', 'cal_cell_end_today' => '</td>', 'cal_row_end' => '</tr>', 'table_close' => '</table>' ); } // -------------------------------------------------------------------- /** * Parse Template * * Harvests the data within the template {pseudo-variables} * used to display the calendar * * @access public * @return void */ function parse_template() { $this->temp = $this->default_template(); if ($this->template == '') { return; } $today = array('cal_cell_start_today', 'cal_cell_content_today', 'cal_cell_no_content_today', 'cal_cell_end_today'); foreach (array('table_open', 'table_close', 'heading_row_start', 'heading_previous_cell', 'heading_title_cell', 'heading_next_cell', 'heading_row_end', 'week_row_start', 'week_day_cell', 'week_row_end', 'cal_row_start', 'cal_cell_start', 'cal_cell_content', 'cal_cell_no_content', 'cal_cell_blank', 'cal_cell_end', 'cal_row_end', 'cal_cell_start_today', 'cal_cell_content_today', 'cal_cell_no_content_today', 'cal_cell_end_today') as $val) { if (preg_match("/\{".$val."\}(.*?)\{\/".$val."\}/si", $this->template, $match)) { $this->temp[$val] = $match['1']; } else { if (in_array($val, $today, TRUE)) { $this->temp[$val] = $this->temp[str_replace('_today', '', $val)]; } } } } } // END CI_Calendar class /* End of file Calendar.php */ /* Location: ./system/libraries/Calendar.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Email.php
system/libraries/Email.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Email Class * * Permits email to be sent using Mail, Sendmail, or SMTP. * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/email.html */ class CI_Email { var $useragent = "CodeIgniter"; var $mailpath = "/usr/sbin/sendmail"; // Sendmail path var $protocol = "mail"; // mail/sendmail/smtp var $smtp_host = ""; // SMTP Server. Example: mail.earthlink.net var $smtp_user = ""; // SMTP Username var $smtp_pass = ""; // SMTP Password var $smtp_port = "25"; // SMTP Port var $smtp_timeout = 5; // SMTP Timeout in seconds var $smtp_crypto = ""; // SMTP Encryption. Can be null, tls or ssl. var $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off var $wrapchars = "76"; // Number of characters to wrap at. var $mailtype = "text"; // text/html Defines email formatting var $charset = "utf-8"; // Default char set: iso-8859-1 or us-ascii var $multipart = "mixed"; // "mixed" (in the body) or "related" (separate) var $alt_message = ''; // Alternative message for HTML emails var $validate = FALSE; // TRUE/FALSE. Enables email validation var $priority = "3"; // Default priority (1 - 5) var $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822) var $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers, // even on the receiving end think they need to muck with CRLFs, so using "\n", while // distasteful, is the only thing that seems to work for all environments. var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo. var $bcc_batch_mode = FALSE; // TRUE/FALSE Turns on/off Bcc batch feature var $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch var $_safe_mode = FALSE; var $_subject = ""; var $_body = ""; var $_finalbody = ""; var $_alt_boundary = ""; var $_atc_boundary = ""; var $_header_str = ""; var $_smtp_connect = ""; var $_encoding = "8bit"; var $_IP = FALSE; var $_smtp_auth = FALSE; var $_replyto_flag = FALSE; var $_debug_msg = array(); var $_recipients = array(); var $_cc_array = array(); var $_bcc_array = array(); var $_headers = array(); var $_attach_name = array(); var $_attach_type = array(); var $_attach_disp = array(); var $_protocols = array('mail', 'sendmail', 'smtp'); var $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix) var $_bit_depths = array('7bit', '8bit'); var $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)'); /** * Constructor - Sets Email Preferences * * The constructor can be passed an array of config values */ public function __construct($config = array()) { if (count($config) > 0) { $this->initialize($config); } else { $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE; $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE; } log_message('debug', "Email Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize preferences * * @access public * @param array * @return void */ public function initialize($config = array()) { foreach ($config as $key => $val) { if (isset($this->$key)) { $method = 'set_'.$key; if (method_exists($this, $method)) { $this->$method($val); } else { $this->$key = $val; } } } $this->clear(); $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE; $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE; return $this; } // -------------------------------------------------------------------- /** * Initialize the Email Data * * @access public * @return void */ public function clear($clear_attachments = FALSE) { $this->_subject = ""; $this->_body = ""; $this->_finalbody = ""; $this->_header_str = ""; $this->_replyto_flag = FALSE; $this->_recipients = array(); $this->_cc_array = array(); $this->_bcc_array = array(); $this->_headers = array(); $this->_debug_msg = array(); $this->_set_header('User-Agent', $this->useragent); $this->_set_header('Date', $this->_set_date()); if ($clear_attachments !== FALSE) { $this->_attach_name = array(); $this->_attach_type = array(); $this->_attach_disp = array(); } return $this; } // -------------------------------------------------------------------- /** * Set FROM * * @access public * @param string * @param string * @return void */ public function from($from, $name = '') { if (preg_match( '/\<(.*)\>/', $from, $match)) { $from = $match['1']; } if ($this->validate) { $this->validate_email($this->_str_to_array($from)); } // prepare the display name if ($name != '') { // only use Q encoding if there are characters that would require it if ( ! preg_match('/[\200-\377]/', $name)) { // add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes $name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"'; } else { $name = $this->_prep_q_encoding($name, TRUE); } } $this->_set_header('From', $name.' <'.$from.'>'); $this->_set_header('Return-Path', '<'.$from.'>'); return $this; } // -------------------------------------------------------------------- /** * Set Reply-to * * @access public * @param string * @param string * @return void */ public function reply_to($replyto, $name = '') { if (preg_match( '/\<(.*)\>/', $replyto, $match)) { $replyto = $match['1']; } if ($this->validate) { $this->validate_email($this->_str_to_array($replyto)); } if ($name == '') { $name = $replyto; } if (strncmp($name, '"', 1) != 0) { $name = '"'.$name.'"'; } $this->_set_header('Reply-To', $name.' <'.$replyto.'>'); $this->_replyto_flag = TRUE; return $this; } // -------------------------------------------------------------------- /** * Set Recipients * * @access public * @param string * @return void */ public function to($to) { $to = $this->_str_to_array($to); $to = $this->clean_email($to); if ($this->validate) { $this->validate_email($to); } if ($this->_get_protocol() != 'mail') { $this->_set_header('To', implode(", ", $to)); } switch ($this->_get_protocol()) { case 'smtp' : $this->_recipients = $to; break; case 'sendmail' : case 'mail' : $this->_recipients = implode(", ", $to); break; } return $this; } // -------------------------------------------------------------------- /** * Set CC * * @access public * @param string * @return void */ public function cc($cc) { $cc = $this->_str_to_array($cc); $cc = $this->clean_email($cc); if ($this->validate) { $this->validate_email($cc); } $this->_set_header('Cc', implode(", ", $cc)); if ($this->_get_protocol() == "smtp") { $this->_cc_array = $cc; } return $this; } // -------------------------------------------------------------------- /** * Set BCC * * @access public * @param string * @param string * @return void */ public function bcc($bcc, $limit = '') { if ($limit != '' && is_numeric($limit)) { $this->bcc_batch_mode = TRUE; $this->bcc_batch_size = $limit; } $bcc = $this->_str_to_array($bcc); $bcc = $this->clean_email($bcc); if ($this->validate) { $this->validate_email($bcc); } if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size)) { $this->_bcc_array = $bcc; } else { $this->_set_header('Bcc', implode(", ", $bcc)); } return $this; } // -------------------------------------------------------------------- /** * Set Email Subject * * @access public * @param string * @return void */ public function subject($subject) { $subject = $this->_prep_q_encoding($subject); $this->_set_header('Subject', $subject); return $this; } // -------------------------------------------------------------------- /** * Set Body * * @access public * @param string * @return void */ public function message($body) { $this->_body = rtrim(str_replace("\r", "", $body)); /* strip slashes only if magic quotes is ON if we do it with magic quotes OFF, it strips real, user-inputted chars. NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and it will probably not exist in future versions at all. */ if ( ! is_php('5.4') && get_magic_quotes_gpc()) { $this->_body = stripslashes($this->_body); } return $this; } // -------------------------------------------------------------------- /** * Assign file attachments * * @access public * @param string * @return void */ public function attach($filename, $disposition = 'attachment') { $this->_attach_name[] = $filename; $this->_attach_type[] = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION)); $this->_attach_disp[] = $disposition; // Can also be 'inline' Not sure if it matters return $this; } // -------------------------------------------------------------------- /** * Add a Header Item * * @access protected * @param string * @param string * @return void */ protected function _set_header($header, $value) { $this->_headers[$header] = $value; } // -------------------------------------------------------------------- /** * Convert a String to an Array * * @access protected * @param string * @return array */ protected function _str_to_array($email) { if ( ! is_array($email)) { if (strpos($email, ',') !== FALSE) { $email = preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY); } else { $email = trim($email); settype($email, "array"); } } return $email; } // -------------------------------------------------------------------- /** * Set Multipart Value * * @access public * @param string * @return void */ public function set_alt_message($str = '') { $this->alt_message = $str; return $this; } // -------------------------------------------------------------------- /** * Set Mailtype * * @access public * @param string * @return void */ public function set_mailtype($type = 'text') { $this->mailtype = ($type == 'html') ? 'html' : 'text'; return $this; } // -------------------------------------------------------------------- /** * Set Wordwrap * * @access public * @param string * @return void */ public function set_wordwrap($wordwrap = TRUE) { $this->wordwrap = ($wordwrap === FALSE) ? FALSE : TRUE; return $this; } // -------------------------------------------------------------------- /** * Set Protocol * * @access public * @param string * @return void */ public function set_protocol($protocol = 'mail') { $this->protocol = ( ! in_array($protocol, $this->_protocols, TRUE)) ? 'mail' : strtolower($protocol); return $this; } // -------------------------------------------------------------------- /** * Set Priority * * @access public * @param integer * @return void */ public function set_priority($n = 3) { if ( ! is_numeric($n)) { $this->priority = 3; return; } if ($n < 1 OR $n > 5) { $this->priority = 3; return; } $this->priority = $n; return $this; } // -------------------------------------------------------------------- /** * Set Newline Character * * @access public * @param string * @return void */ public function set_newline($newline = "\n") { if ($newline != "\n" AND $newline != "\r\n" AND $newline != "\r") { $this->newline = "\n"; return; } $this->newline = $newline; return $this; } // -------------------------------------------------------------------- /** * Set CRLF * * @access public * @param string * @return void */ public function set_crlf($crlf = "\n") { if ($crlf != "\n" AND $crlf != "\r\n" AND $crlf != "\r") { $this->crlf = "\n"; return; } $this->crlf = $crlf; return $this; } // -------------------------------------------------------------------- /** * Set Message Boundary * * @access protected * @return void */ protected function _set_boundaries() { $this->_alt_boundary = "B_ALT_".uniqid(''); // multipart/alternative $this->_atc_boundary = "B_ATC_".uniqid(''); // attachment boundary } // -------------------------------------------------------------------- /** * Get the Message ID * * @access protected * @return string */ protected function _get_message_id() { $from = $this->_headers['Return-Path']; $from = str_replace(">", "", $from); $from = str_replace("<", "", $from); return "<".uniqid('').strstr($from, '@').">"; } // -------------------------------------------------------------------- /** * Get Mail Protocol * * @access protected * @param bool * @return string */ protected function _get_protocol($return = TRUE) { $this->protocol = strtolower($this->protocol); $this->protocol = ( ! in_array($this->protocol, $this->_protocols, TRUE)) ? 'mail' : $this->protocol; if ($return == TRUE) { return $this->protocol; } } // -------------------------------------------------------------------- /** * Get Mail Encoding * * @access protected * @param bool * @return string */ protected function _get_encoding($return = TRUE) { $this->_encoding = ( ! in_array($this->_encoding, $this->_bit_depths)) ? '8bit' : $this->_encoding; foreach ($this->_base_charsets as $charset) { if (strncmp($charset, $this->charset, strlen($charset)) == 0) { $this->_encoding = '7bit'; } } if ($return == TRUE) { return $this->_encoding; } } // -------------------------------------------------------------------- /** * Get content type (text/html/attachment) * * @access protected * @return string */ protected function _get_content_type() { if ($this->mailtype == 'html' && count($this->_attach_name) == 0) { return 'html'; } elseif ($this->mailtype == 'html' && count($this->_attach_name) > 0) { return 'html-attach'; } elseif ($this->mailtype == 'text' && count($this->_attach_name) > 0) { return 'plain-attach'; } else { return 'plain'; } } // -------------------------------------------------------------------- /** * Set RFC 822 Date * * @access protected * @return string */ protected function _set_date() { $timezone = date("Z"); $operator = (strncmp($timezone, '-', 1) == 0) ? '-' : '+'; $timezone = abs($timezone); $timezone = floor($timezone/3600) * 100 + ($timezone % 3600 ) / 60; return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone); } // -------------------------------------------------------------------- /** * Mime message * * @access protected * @return string */ protected function _get_mime_message() { return "This is a multi-part message in MIME format.".$this->newline."Your email application may not support this format."; } // -------------------------------------------------------------------- /** * Validate Email Address * * @access public * @param string * @return bool */ public function validate_email($email) { if ( ! is_array($email)) { $this->_set_error_message('lang:email_must_be_array'); return FALSE; } foreach ($email as $val) { if ( ! $this->valid_email($val)) { $this->_set_error_message('lang:email_invalid_address', $val); return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * Email Validation * * @access public * @param string * @return bool */ public function valid_email($address) { return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE; } // -------------------------------------------------------------------- /** * Clean Extended Email Address: Joe Smith <joe@smith.com> * * @access public * @param string * @return string */ public function clean_email($email) { if ( ! is_array($email)) { if (preg_match('/\<(.*)\>/', $email, $match)) { return $match['1']; } else { return $email; } } $clean_email = array(); foreach ($email as $addy) { if (preg_match( '/\<(.*)\>/', $addy, $match)) { $clean_email[] = $match['1']; } else { $clean_email[] = $addy; } } return $clean_email; } // -------------------------------------------------------------------- /** * Build alternative plain text message * * This public function provides the raw message for use * in plain-text headers of HTML-formatted emails. * If the user hasn't specified his own alternative message * it creates one by stripping the HTML * * @access protected * @return string */ protected function _get_alt_message() { if ($this->alt_message != "") { return $this->word_wrap($this->alt_message, '76'); } if (preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match)) { $body = $match['1']; } else { $body = $this->_body; } $body = trim(strip_tags($body)); $body = preg_replace( '#<!--(.*)--\>#', "", $body); $body = str_replace("\t", "", $body); for ($i = 20; $i >= 3; $i--) { $n = ""; for ($x = 1; $x <= $i; $x ++) { $n .= "\n"; } $body = str_replace($n, "\n\n", $body); } return $this->word_wrap($body, '76'); } // -------------------------------------------------------------------- /** * Word Wrap * * @access public * @param string * @param integer * @return string */ public function word_wrap($str, $charlim = '') { // Se the character limit if ($charlim == '') { $charlim = ($this->wrapchars == "") ? "76" : $this->wrapchars; } // Reduce multiple spaces $str = preg_replace("| +|", " ", $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } // If the current word is surrounded by {unwrap} tags we'll // strip the entire chunk and replace it with a marker. $unwrap = array(); if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches)) { for ($i = 0; $i < count($matches['0']); $i++) { $unwrap[] = $matches['1'][$i]; $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str); } } // Use PHP's native public function to do the initial wordwrap. // We set the cut flag to FALSE so that any individual words that are // too long get left alone. In the next step we'll deal with them. $str = wordwrap($str, $charlim, "\n", FALSE); // Split the string into individual lines of text and cycle through them $output = ""; foreach (explode("\n", $str) as $line) { // Is the line within the allowed character count? // If so we'll join it to the output and continue if (strlen($line) <= $charlim) { $output .= $line.$this->newline; continue; } $temp = ''; while ((strlen($line)) > $charlim) { // If the over-length word is a URL we won't wrap it if (preg_match("!\[url.+\]|://|wwww.!", $line)) { break; } // Trim the word down $temp .= substr($line, 0, $charlim-1); $line = substr($line, $charlim-1); } // If $temp contains data it means we had to split up an over-length // word into smaller chunks so we'll add it back to our current line if ($temp != '') { $output .= $temp.$this->newline.$line; } else { $output .= $line; } $output .= $this->newline; } // Put our markers back if (count($unwrap) > 0) { foreach ($unwrap as $key => $val) { $output = str_replace("{{unwrapped".$key."}}", $val, $output); } } return $output; } // -------------------------------------------------------------------- /** * Build final headers * * @access protected * @param string * @return string */ protected function _build_headers() { $this->_set_header('X-Sender', $this->clean_email($this->_headers['From'])); $this->_set_header('X-Mailer', $this->useragent); $this->_set_header('X-Priority', $this->_priorities[$this->priority - 1]); $this->_set_header('Message-ID', $this->_get_message_id()); $this->_set_header('Mime-Version', '1.0'); } // -------------------------------------------------------------------- /** * Write Headers as a string * * @access protected * @return void */ protected function _write_headers() { if ($this->protocol == 'mail') { $this->_subject = $this->_headers['Subject']; unset($this->_headers['Subject']); } reset($this->_headers); $this->_header_str = ""; foreach ($this->_headers as $key => $val) { $val = trim($val); if ($val != "") { $this->_header_str .= $key.": ".$val.$this->newline; } } if ($this->_get_protocol() == 'mail') { $this->_header_str = rtrim($this->_header_str); } } // -------------------------------------------------------------------- /** * Build Final Body and attachments * * @access protected * @return void */ protected function _build_message() { if ($this->wordwrap === TRUE AND $this->mailtype != 'html') { $this->_body = $this->word_wrap($this->_body); } $this->_set_boundaries(); $this->_write_headers(); $hdr = ($this->_get_protocol() == 'mail') ? $this->newline : ''; $body = ''; switch ($this->_get_content_type()) { case 'plain' : $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline; $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding(); if ($this->_get_protocol() == 'mail') { $this->_header_str .= $hdr; $this->_finalbody = $this->_body; } else { $this->_finalbody = $hdr . $this->newline . $this->newline . $this->_body; } return; break; case 'html' : if ($this->send_multipart === FALSE) { $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline; $hdr .= "Content-Transfer-Encoding: quoted-printable"; } else { $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline . $this->newline; $body .= $this->_get_mime_message() . $this->newline . $this->newline; $body .= "--" . $this->_alt_boundary . $this->newline; $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline; $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline; $body .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline; $body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline; $body .= "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline; } $this->_finalbody = $body . $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline; if ($this->_get_protocol() == 'mail') { $this->_header_str .= $hdr; } else { $this->_finalbody = $hdr . $this->_finalbody; } if ($this->send_multipart !== FALSE) { $this->_finalbody .= "--" . $this->_alt_boundary . "--"; } return; break; case 'plain-attach' : $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline; if ($this->_get_protocol() == 'mail') { $this->_header_str .= $hdr; } $body .= $this->_get_mime_message() . $this->newline . $this->newline; $body .= "--" . $this->_atc_boundary . $this->newline; $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline; $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline; $body .= $this->_body . $this->newline . $this->newline; break; case 'html-attach' : $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline; if ($this->_get_protocol() == 'mail') { $this->_header_str .= $hdr; } $body .= $this->_get_mime_message() . $this->newline . $this->newline; $body .= "--" . $this->_atc_boundary . $this->newline; $body .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline; $body .= "--" . $this->_alt_boundary . $this->newline; $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline; $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline; $body .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline; $body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline; $body .= "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline; $body .= $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline; $body .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline; break; } $attachment = array(); $z = 0; for ($i=0; $i < count($this->_attach_name); $i++) { $filename = $this->_attach_name[$i]; $basename = basename($filename); $ctype = $this->_attach_type[$i]; if ( ! file_exists($filename)) { $this->_set_error_message('lang:email_attachment_missing', $filename); return FALSE; } $h = "--".$this->_atc_boundary.$this->newline; $h .= "Content-type: ".$ctype."; "; $h .= "name=\"".$basename."\"".$this->newline; $h .= "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline; $h .= "Content-Transfer-Encoding: base64".$this->newline; $attachment[$z++] = $h; $file = filesize($filename) +1; if ( ! $fp = fopen($filename, FOPEN_READ)) { $this->_set_error_message('lang:email_attachment_unreadable', $filename); return FALSE; } $attachment[$z++] = chunk_split(base64_encode(fread($fp, $file))); fclose($fp); } $body .= implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--"; if ($this->_get_protocol() == 'mail') { $this->_finalbody = $body; } else { $this->_finalbody = $hdr . $body; } return; } // -------------------------------------------------------------------- /** * Prep Quoted Printable * * Prepares string for Quoted-Printable Content-Transfer-Encoding * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt * * @access protected * @param string * @param integer * @return string */ protected function _prep_quoted_printable($str, $charlim = '') { // Set the character limit // Don't allow over 76, as that will make servers and MUAs barf // all over quoted-printable data if ($charlim == '' OR $charlim > '76') { $charlim = '76'; } // Reduce multiple spaces $str = preg_replace("| +|", " ", $str); // kill nulls $str = preg_replace('/\x00+/', '', $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } // We are intentionally wrapping so mail servers will encode characters // properly and MUAs will behave, so {unwrap} must go! $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str); // Break into an array of lines $lines = explode("\n", $str); $escape = '='; $output = ''; foreach ($lines as $line) { $length = strlen($line); $temp = ''; // Loop through each character in the line to add soft-wrap // characters at the end of a line " =\r\n" and add the newly // processed line(s) to the output (see comment on $crlf class property) for ($i = 0; $i < $length; $i++) { // Grab the next character $char = substr($line, $i, 1); $ascii = ord($char); // Convert spaces and tabs but only if it's the end of the line if ($i == ($length - 1)) { $char = ($ascii == '32' OR $ascii == '9') ? $escape.sprintf('%02s', dechex($ascii)) : $char; } // encode = signs if ($ascii == '61') { $char = $escape.strtoupper(sprintf('%02s', dechex($ascii))); // =3D } // If we're at the character limit, add the line to the output, // reset our temp variable, and keep on chuggin' if ((strlen($temp) + strlen($char)) >= $charlim) { $output .= $temp.$escape.$this->crlf; $temp = ''; } // Add the character to our temporary line $temp .= $char; } // Add our completed line to the output $output .= $temp.$this->crlf; } // get rid of extra CRLF tacked onto the end $output = substr($output, 0, strlen($this->crlf) * -1); return $output; } // -------------------------------------------------------------------- /** * Prep Q Encoding * * Performs "Q Encoding" on a string for use in email headers. It's related * but not identical to quoted-printable, so it has its own method * * @access public * @param str * @param bool // set to TRUE for processing From: headers * @return str */ protected function _prep_q_encoding($str, $from = FALSE) { $str = str_replace(array("\r", "\n"), array('', ''), $str); // Line length must not exceed 76 characters, so we adjust for // a space, 7 extra characters =??Q??=, and the charset that we will add to each line $limit = 75 - 7 - strlen($this->charset); // these special characters must be converted too $convert = array('_', '=', '?'); if ($from === TRUE) { $convert[] = ','; $convert[] = ';'; } $output = ''; $temp = ''; for ($i = 0, $length = strlen($str); $i < $length; $i++) { // Grab the next character $char = substr($str, $i, 1); $ascii = ord($char); // convert ALL non-printable ASCII characters and our specials if ($ascii < 32 OR $ascii > 126 OR in_array($char, $convert)) { $char = '='.dechex($ascii); } // handle regular spaces a bit more compactly than =20 if ($ascii == 32) { $char = '_'; } // If we're at the character limit, add the line to the output, // reset our temp variable, and keep on chuggin' if ((strlen($temp) + strlen($char)) >= $limit) { $output .= $temp.$this->crlf; $temp = ''; } // Add the character to our temporary line $temp .= $char; } $str = $output.$temp; // wrap each line with the shebang, charset, and transfer encoding // the preceding space on successive lines is required for header "folding" $str = trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $str)); return $str; } // -------------------------------------------------------------------- /** * Send Email * * @access public * @return bool */ public function send() { if ($this->_replyto_flag == FALSE) { $this->reply_to($this->_headers['From']); } if (( ! isset($this->_recipients) AND ! isset($this->_headers['To'])) AND ( ! isset($this->_bcc_array) AND ! isset($this->_headers['Bcc'])) AND ( ! isset($this->_headers['Cc']))) { $this->_set_error_message('lang:email_no_recipients'); return FALSE; } $this->_build_headers(); if ($this->bcc_batch_mode AND count($this->_bcc_array) > 0) { if (count($this->_bcc_array) > $this->bcc_batch_size) return $this->batch_bcc_send(); } $this->_build_message(); if ( ! $this->_spool_email()) { return FALSE; } else { return TRUE; } } // -------------------------------------------------------------------- /** * Batch Bcc Send. Sends groups of BCCs in batches * * @access public * @return bool */ public function batch_bcc_send()
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
true
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Upload.php
system/libraries/Upload.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * File Uploading Class * * @package CodeIgniter * @subpackage Libraries * @category Uploads * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/file_uploading.html */ class CI_Upload { public $max_size = 0; public $max_width = 0; public $max_height = 0; public $max_filename = 0; public $allowed_types = ""; public $file_temp = ""; public $file_name = ""; public $orig_name = ""; public $file_type = ""; public $file_size = ""; public $file_ext = ""; public $upload_path = ""; public $overwrite = FALSE; public $encrypt_name = FALSE; public $is_image = FALSE; public $image_width = ''; public $image_height = ''; public $image_type = ''; public $image_size_str = ''; public $error_msg = array(); public $mimes = array(); public $remove_spaces = TRUE; public $xss_clean = FALSE; public $temp_prefix = "temp_file_"; public $client_name = ''; protected $_file_name_override = ''; /** * Constructor * * @access public */ public function __construct($props = array()) { if (count($props) > 0) { $this->initialize($props); } log_message('debug', "Upload Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize preferences * * @param array * @return void */ public function initialize($config = array()) { $defaults = array( 'max_size' => 0, 'max_width' => 0, 'max_height' => 0, 'max_filename' => 0, 'allowed_types' => "", 'file_temp' => "", 'file_name' => "", 'orig_name' => "", 'file_type' => "", 'file_size' => "", 'file_ext' => "", 'upload_path' => "", 'overwrite' => FALSE, 'encrypt_name' => FALSE, 'is_image' => FALSE, 'image_width' => '', 'image_height' => '', 'image_type' => '', 'image_size_str' => '', 'error_msg' => array(), 'mimes' => array(), 'remove_spaces' => TRUE, 'xss_clean' => FALSE, 'temp_prefix' => "temp_file_", 'client_name' => '' ); foreach ($defaults as $key => $val) { if (isset($config[$key])) { $method = 'set_'.$key; if (method_exists($this, $method)) { $this->$method($config[$key]); } else { $this->$key = $config[$key]; } } else { $this->$key = $val; } } // if a file_name was provided in the config, use it instead of the user input // supplied file name for all uploads until initialized again $this->_file_name_override = $this->file_name; } // -------------------------------------------------------------------- /** * Perform the file upload * * @return bool */ public function do_upload($field = 'userfile') { // Is $_FILES[$field] set? If not, no reason to continue. if ( ! isset($_FILES[$field])) { $this->set_error('upload_no_file_selected'); return FALSE; } // Is the upload path valid? if ( ! $this->validate_upload_path()) { // errors will already be set by validate_upload_path() so just return FALSE return FALSE; } // Was the file able to be uploaded? If not, determine the reason why. if ( ! is_uploaded_file($_FILES[$field]['tmp_name'])) { $error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error']; switch($error) { case 1: // UPLOAD_ERR_INI_SIZE $this->set_error('upload_file_exceeds_limit'); break; case 2: // UPLOAD_ERR_FORM_SIZE $this->set_error('upload_file_exceeds_form_limit'); break; case 3: // UPLOAD_ERR_PARTIAL $this->set_error('upload_file_partial'); break; case 4: // UPLOAD_ERR_NO_FILE $this->set_error('upload_no_file_selected'); break; case 6: // UPLOAD_ERR_NO_TMP_DIR $this->set_error('upload_no_temp_directory'); break; case 7: // UPLOAD_ERR_CANT_WRITE $this->set_error('upload_unable_to_write_file'); break; case 8: // UPLOAD_ERR_EXTENSION $this->set_error('upload_stopped_by_extension'); break; default : $this->set_error('upload_no_file_selected'); break; } return FALSE; } // Set the uploaded data as class variables $this->file_temp = $_FILES[$field]['tmp_name']; $this->file_size = $_FILES[$field]['size']; $this->_file_mime_type($_FILES[$field]); $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type); $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); $this->file_name = $this->_prep_filename($_FILES[$field]['name']); $this->file_ext = $this->get_extension($this->file_name); $this->client_name = $this->file_name; // Is the file type allowed to be uploaded? if ( ! $this->is_allowed_filetype()) { $this->set_error('upload_invalid_filetype'); return FALSE; } // if we're overriding, let's now make sure the new name and type is allowed if ($this->_file_name_override != '') { $this->file_name = $this->_prep_filename($this->_file_name_override); // If no extension was provided in the file_name config item, use the uploaded one if (strpos($this->_file_name_override, '.') === FALSE) { $this->file_name .= $this->file_ext; } // An extension was provided, lets have it! else { $this->file_ext = $this->get_extension($this->_file_name_override); } if ( ! $this->is_allowed_filetype(TRUE)) { $this->set_error('upload_invalid_filetype'); return FALSE; } } // Convert the file size to kilobytes if ($this->file_size > 0) { $this->file_size = round($this->file_size/1024, 2); } // Is the file size within the allowed maximum? if ( ! $this->is_allowed_filesize()) { $this->set_error('upload_invalid_filesize'); return FALSE; } // Are the image dimensions within the allowed size? // Note: This can fail if the server has an open_basdir restriction. if ( ! $this->is_allowed_dimensions()) { $this->set_error('upload_invalid_dimensions'); return FALSE; } // Sanitize the file name for security $this->file_name = $this->clean_file_name($this->file_name); // Truncate the file name if it's too long if ($this->max_filename > 0) { $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); } // Remove white spaces in the name if ($this->remove_spaces == TRUE) { $this->file_name = preg_replace("/\s+/", "_", $this->file_name); } /* * Validate the file name * This function appends an number onto the end of * the file if one with the same name already exists. * If it returns false there was a problem. */ $this->orig_name = $this->file_name; if ($this->overwrite == FALSE) { $this->file_name = $this->set_filename($this->upload_path, $this->file_name); if ($this->file_name === FALSE) { return FALSE; } } /* * Run the file through the XSS hacking filter * This helps prevent malicious code from being * embedded within a file. Scripts can easily * be disguised as images or other file types. */ if ($this->xss_clean) { if ($this->do_xss_clean() === FALSE) { $this->set_error('upload_unable_to_write_file'); return FALSE; } } /* * Move the file to the final destination * To deal with different server configurations * we'll attempt to use copy() first. If that fails * we'll use move_uploaded_file(). One of the two should * reliably work in most environments */ if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) { if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) { $this->set_error('upload_destination_error'); return FALSE; } } /* * Set the finalized image dimensions * This sets the image width/height (assuming the * file was an image). We use this information * in the "data" function. */ $this->set_image_properties($this->upload_path.$this->file_name); return TRUE; } // -------------------------------------------------------------------- /** * Finalized Data Array * * Returns an associative array containing all of the information * related to the upload, allowing the developer easy access in one array. * * @return array */ public function data() { return array ( 'file_name' => $this->file_name, 'file_type' => $this->file_type, 'file_path' => $this->upload_path, 'full_path' => $this->upload_path.$this->file_name, 'raw_name' => str_replace($this->file_ext, '', $this->file_name), 'orig_name' => $this->orig_name, 'client_name' => $this->client_name, 'file_ext' => $this->file_ext, 'file_size' => $this->file_size, 'is_image' => $this->is_image(), 'image_width' => $this->image_width, 'image_height' => $this->image_height, 'image_type' => $this->image_type, 'image_size_str' => $this->image_size_str, ); } // -------------------------------------------------------------------- /** * Set Upload Path * * @param string * @return void */ public function set_upload_path($path) { // Make sure it has a trailing slash $this->upload_path = rtrim($path, '/').'/'; } // -------------------------------------------------------------------- /** * Set the file name * * This function takes a filename/path as input and looks for the * existence of a file with the same name. If found, it will append a * number to the end of the filename to avoid overwriting a pre-existing file. * * @param string * @param string * @return string */ public function set_filename($path, $filename) { if ($this->encrypt_name == TRUE) { mt_srand(); $filename = md5(uniqid(mt_rand())).$this->file_ext; } if ( ! file_exists($path.$filename)) { return $filename; } $filename = str_replace($this->file_ext, '', $filename); $new_filename = ''; for ($i = 1; $i < 100; $i++) { if ( ! file_exists($path.$filename.$i.$this->file_ext)) { $new_filename = $filename.$i.$this->file_ext; break; } } if ($new_filename == '') { $this->set_error('upload_bad_filename'); return FALSE; } else { return $new_filename; } } // -------------------------------------------------------------------- /** * Set Maximum File Size * * @param integer * @return void */ public function set_max_filesize($n) { $this->max_size = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Maximum File Name Length * * @param integer * @return void */ public function set_max_filename($n) { $this->max_filename = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Maximum Image Width * * @param integer * @return void */ public function set_max_width($n) { $this->max_width = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Maximum Image Height * * @param integer * @return void */ public function set_max_height($n) { $this->max_height = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Allowed File Types * * @param string * @return void */ public function set_allowed_types($types) { if ( ! is_array($types) && $types == '*') { $this->allowed_types = '*'; return; } $this->allowed_types = explode('|', $types); } // -------------------------------------------------------------------- /** * Set Image Properties * * Uses GD to determine the width/height/type of image * * @param string * @return void */ public function set_image_properties($path = '') { if ( ! $this->is_image()) { return; } if (function_exists('getimagesize')) { if (FALSE !== ($D = @getimagesize($path))) { $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); $this->image_width = $D['0']; $this->image_height = $D['1']; $this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']]; $this->image_size_str = $D['3']; // string containing height and width } } } // -------------------------------------------------------------------- /** * Set XSS Clean * * Enables the XSS flag so that the file that was uploaded * will be run through the XSS filter. * * @param bool * @return void */ public function set_xss_clean($flag = FALSE) { $this->xss_clean = ($flag == TRUE) ? TRUE : FALSE; } // -------------------------------------------------------------------- /** * Validate the image * * @return bool */ public function is_image() { // IE will sometimes return odd mime-types during upload, so here we just standardize all // jpegs or pngs to the same file type. $png_mimes = array('image/x-png'); $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); if (in_array($this->file_type, $png_mimes)) { $this->file_type = 'image/png'; } if (in_array($this->file_type, $jpeg_mimes)) { $this->file_type = 'image/jpeg'; } $img_mimes = array( 'image/gif', 'image/jpeg', 'image/png', ); return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE; } // -------------------------------------------------------------------- /** * Verify that the filetype is allowed * * @return bool */ public function is_allowed_filetype($ignore_mime = FALSE) { if ($this->allowed_types == '*') { return TRUE; } if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types)) { $this->set_error('upload_no_file_types'); return FALSE; } $ext = strtolower(ltrim($this->file_ext, '.')); if ( ! in_array($ext, $this->allowed_types)) { return FALSE; } // Images get some additional checks $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe'); if (in_array($ext, $image_types)) { if (getimagesize($this->file_temp) === FALSE) { return FALSE; } } if ($ignore_mime === TRUE) { return TRUE; } $mime = $this->mimes_types($ext); if (is_array($mime)) { if (in_array($this->file_type, $mime, TRUE)) { return TRUE; } } elseif ($mime == $this->file_type) { return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Verify that the file is within the allowed size * * @return bool */ public function is_allowed_filesize() { if ($this->max_size != 0 AND $this->file_size > $this->max_size) { return FALSE; } else { return TRUE; } } // -------------------------------------------------------------------- /** * Verify that the image is within the allowed width/height * * @return bool */ public function is_allowed_dimensions() { if ( ! $this->is_image()) { return TRUE; } if (function_exists('getimagesize')) { $D = @getimagesize($this->file_temp); if ($this->max_width > 0 AND $D['0'] > $this->max_width) { return FALSE; } if ($this->max_height > 0 AND $D['1'] > $this->max_height) { return FALSE; } return TRUE; } return TRUE; } // -------------------------------------------------------------------- /** * Validate Upload Path * * Verifies that it is a valid upload path with proper permissions. * * * @return bool */ public function validate_upload_path() { if ($this->upload_path == '') { $this->set_error('upload_no_filepath'); return FALSE; } if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE) { $this->upload_path = str_replace("\\", "/", realpath($this->upload_path)); } if ( ! @is_dir($this->upload_path)) { $this->set_error('upload_no_filepath'); return FALSE; } if ( ! is_really_writable($this->upload_path)) { $this->set_error('upload_not_writable'); return FALSE; } $this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path); return TRUE; } // -------------------------------------------------------------------- /** * Extract the file extension * * @param string * @return string */ public function get_extension($filename) { $x = explode('.', $filename); return '.'.end($x); } // -------------------------------------------------------------------- /** * Clean the file name for security * * @param string * @return string */ public function clean_file_name($filename) { $bad = array( "<!--", "-->", "'", "<", ">", '"', '&', '$', '=', ';', '?', '/', "%20", "%22", "%3c", // < "%253c", // < "%3e", // > "%0e", // > "%28", // ( "%29", // ) "%2528", // ( "%26", // & "%24", // $ "%3f", // ? "%3b", // ; "%3d" // = ); $filename = str_replace($bad, '', $filename); return stripslashes($filename); } // -------------------------------------------------------------------- /** * Limit the File Name Length * * @param string * @return string */ public function limit_filename_length($filename, $length) { if (strlen($filename) < $length) { return $filename; } $ext = ''; if (strpos($filename, '.') !== FALSE) { $parts = explode('.', $filename); $ext = '.'.array_pop($parts); $filename = implode('.', $parts); } return substr($filename, 0, ($length - strlen($ext))).$ext; } // -------------------------------------------------------------------- /** * Runs the file through the XSS clean function * * This prevents people from embedding malicious code in their files. * I'm not sure that it won't negatively affect certain files in unexpected ways, * but so far I haven't found that it causes trouble. * * @return void */ public function do_xss_clean() { $file = $this->file_temp; if (filesize($file) == 0) { return FALSE; } if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '') { $current = ini_get('memory_limit') * 1024 * 1024; // There was a bug/behavioural change in PHP 5.2, where numbers over one million get output // into scientific notation. number_format() ensures this number is an integer // http://bugs.php.net/bug.php?id=43053 $new_memory = number_format(ceil(filesize($file) + $current), 0, '.', ''); ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net } // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an // attempted XSS attack. if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) { if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary { return FALSE; // Couldn't open the file, return FALSE } $opening_bytes = fread($file, 256); fclose($file); // These are known to throw IE into mime-type detection chaos // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title // title is basically just in SVG, but we filter it anyhow if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes)) { return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good } else { return FALSE; } } if (($data = @file_get_contents($file)) === FALSE) { return FALSE; } $CI =& get_instance(); return $CI->security->xss_clean($data, TRUE); } // -------------------------------------------------------------------- /** * Set an error message * * @param string * @return void */ public function set_error($msg) { $CI =& get_instance(); $CI->lang->load('upload'); if (is_array($msg)) { foreach ($msg as $val) { $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val); $this->error_msg[] = $msg; log_message('error', $msg); } } else { $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg); $this->error_msg[] = $msg; log_message('error', $msg); } } // -------------------------------------------------------------------- /** * Display the error message * * @param string * @param string * @return string */ public function display_errors($open = '<p>', $close = '</p>') { $str = ''; foreach ($this->error_msg as $val) { $str .= $open.$val.$close; } return $str; } // -------------------------------------------------------------------- /** * List of Mime Types * * This is a list of mime types. We use it to validate * the "allowed types" set by the developer * * @param string * @return string */ public function mimes_types($mime) { global $mimes; if (count($this->mimes) == 0) { if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); } elseif (is_file(APPPATH.'config/mimes.php')) { include(APPPATH.'config//mimes.php'); } else { return FALSE; } $this->mimes = $mimes; unset($mimes); } return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime]; } // -------------------------------------------------------------------- /** * Prep Filename * * Prevents possible script execution from Apache's handling of files multiple extensions * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext * * @param string * @return string */ protected function _prep_filename($filename) { if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*') { return $filename; } $parts = explode('.', $filename); $ext = array_pop($parts); $filename = array_shift($parts); foreach ($parts as $part) { if ( ! in_array(strtolower($part), $this->allowed_types) OR $this->mimes_types(strtolower($part)) === FALSE) { $filename .= '.'.$part.'_'; } else { $filename .= '.'.$part; } } $filename .= '.'.$ext; return $filename; } // -------------------------------------------------------------------- /** * File MIME type * * Detects the (actual) MIME type of the uploaded file, if possible. * The input array is expected to be $_FILES[$field] * * @param array * @return void */ protected function _file_mime_type($file) { // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; /* Fileinfo extension - most reliable method * * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the * more convenient FILEINFO_MIME_TYPE flag doesn't exist. */ if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system { $mime = @finfo_file($finfo, $file['tmp_name']); finfo_close($finfo); /* According to the comments section of the PHP manual page, * it is possible that this function returns an empty string * for some files (e.g. if they don't exist in the magic MIME database) */ if (is_string($mime) && preg_match($regexp, $mime, $matches)) { $this->file_type = $matches[1]; return; } } } /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better * than mime_content_type() as well, hence the attempts to try calling the command line with * three different functions. * * Notes: * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system * - many system admins would disable the exec(), shell_exec(), popen() and similar functions * due to security concerns, hence the function_exists() checks */ if (DIRECTORY_SEPARATOR !== '\\') { $cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1'; if (function_exists('exec')) { /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. * However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy * value, which is only put to allow us to get the return status code. */ $mime = @exec($cmd, $mime, $return_status); if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) { $this->file_type = $matches[1]; return; } } if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec')) { $mime = @shell_exec($cmd); if (strlen($mime) > 0) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { $this->file_type = $matches[1]; return; } } } if (function_exists('popen')) { $proc = @popen($cmd, 'r'); if (is_resource($proc)) { $mime = @fread($proc, 512); @pclose($proc); if ($mime !== FALSE) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { $this->file_type = $matches[1]; return; } } } } } // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) if (function_exists('mime_content_type')) { $this->file_type = @mime_content_type($file['tmp_name']); if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string { return; } } $this->file_type = $file['type']; } // -------------------------------------------------------------------- } // END Upload Class /* End of file Upload.php */ /* Location: ./system/libraries/Upload.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Log.php
system/libraries/Log.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Logging Class * * @package CodeIgniter * @subpackage Libraries * @category Logging * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/general/errors.html */ class CI_Log { protected $_log_path; protected $_threshold = 1; protected $_date_fmt = 'Y-m-d H:i:s'; protected $_enabled = TRUE; protected $_levels = array('ERROR' => '1', 'DEBUG' => '2', 'INFO' => '3', 'ALL' => '4'); /** * Constructor */ public function __construct() { $config =& get_config(); $this->_log_path = ($config['log_path'] != '') ? $config['log_path'] : APPPATH.'logs/'; if ( ! is_dir($this->_log_path) OR ! is_really_writable($this->_log_path)) { $this->_enabled = FALSE; } if (is_numeric($config['log_threshold'])) { $this->_threshold = $config['log_threshold']; } if ($config['log_date_format'] != '') { $this->_date_fmt = $config['log_date_format']; } } // -------------------------------------------------------------------- /** * Write Log File * * Generally this function will be called using the global log_message() function * * @param string the error level * @param string the error message * @param bool whether the error is a native PHP error * @return bool */ public function write_log($level = 'error', $msg, $php_error = FALSE) { if ($this->_enabled === FALSE) { return FALSE; } $level = strtoupper($level); if ( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold)) { return FALSE; } $filepath = $this->_log_path.'log-'.date('Y-m-d').'.php'; $message = ''; if ( ! file_exists($filepath)) { $message .= "<"."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n"; } if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE)) { return FALSE; } $message .= $level.' '.(($level == 'INFO') ? ' -' : '-').' '.date($this->_date_fmt). ' --> '.$msg."\n"; flock($fp, LOCK_EX); fwrite($fp, $message); flock($fp, LOCK_UN); fclose($fp); @chmod($filepath, FILE_WRITE_MODE); return TRUE; } } // END Log Class /* End of file Log.php */ /* Location: ./system/libraries/Log.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Trackback.php
system/libraries/Trackback.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Trackback Class * * Trackback Sending/Receiving Class * * @package CodeIgniter * @subpackage Libraries * @category Trackbacks * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/trackback.html */ class CI_Trackback { var $time_format = 'local'; var $charset = 'UTF-8'; var $data = array('url' => '', 'title' => '', 'excerpt' => '', 'blog_name' => '', 'charset' => ''); var $convert_ascii = TRUE; var $response = ''; var $error_msg = array(); /** * Constructor * * @access public */ public function __construct() { log_message('debug', "Trackback Class Initialized"); } // -------------------------------------------------------------------- /** * Send Trackback * * @access public * @param array * @return bool */ function send($tb_data) { if ( ! is_array($tb_data)) { $this->set_error('The send() method must be passed an array'); return FALSE; } // Pre-process the Trackback Data foreach (array('url', 'title', 'excerpt', 'blog_name', 'ping_url') as $item) { if ( ! isset($tb_data[$item])) { $this->set_error('Required item missing: '.$item); return FALSE; } switch ($item) { case 'ping_url' : $$item = $this->extract_urls($tb_data[$item]); break; case 'excerpt' : $$item = $this->limit_characters($this->convert_xml(strip_tags(stripslashes($tb_data[$item])))); break; case 'url' : $$item = str_replace('&#45;', '-', $this->convert_xml(strip_tags(stripslashes($tb_data[$item])))); break; default : $$item = $this->convert_xml(strip_tags(stripslashes($tb_data[$item]))); break; } // Convert High ASCII Characters if ($this->convert_ascii == TRUE) { if ($item == 'excerpt') { $$item = $this->convert_ascii($$item); } elseif ($item == 'title') { $$item = $this->convert_ascii($$item); } elseif ($item == 'blog_name') { $$item = $this->convert_ascii($$item); } } } // Build the Trackback data string $charset = ( ! isset($tb_data['charset'])) ? $this->charset : $tb_data['charset']; $data = "url=".rawurlencode($url)."&title=".rawurlencode($title)."&blog_name=".rawurlencode($blog_name)."&excerpt=".rawurlencode($excerpt)."&charset=".rawurlencode($charset); // Send Trackback(s) $return = TRUE; if (count($ping_url) > 0) { foreach ($ping_url as $url) { if ($this->process($url, $data) == FALSE) { $return = FALSE; } } } return $return; } // -------------------------------------------------------------------- /** * Receive Trackback Data * * This function simply validates the incoming TB data. * It returns FALSE on failure and TRUE on success. * If the data is valid it is set to the $this->data array * so that it can be inserted into a database. * * @access public * @return bool */ function receive() { foreach (array('url', 'title', 'blog_name', 'excerpt') as $val) { if ( ! isset($_POST[$val]) OR $_POST[$val] == '') { $this->set_error('The following required POST variable is missing: '.$val); return FALSE; } $this->data['charset'] = ( ! isset($_POST['charset'])) ? 'auto' : strtoupper(trim($_POST['charset'])); if ($val != 'url' && function_exists('mb_convert_encoding')) { $_POST[$val] = mb_convert_encoding($_POST[$val], $this->charset, $this->data['charset']); } $_POST[$val] = ($val != 'url') ? $this->convert_xml(strip_tags($_POST[$val])) : strip_tags($_POST[$val]); if ($val == 'excerpt') { $_POST['excerpt'] = $this->limit_characters($_POST['excerpt']); } $this->data[$val] = $_POST[$val]; } return TRUE; } // -------------------------------------------------------------------- /** * Send Trackback Error Message * * Allows custom errors to be set. By default it * sends the "incomplete information" error, as that's * the most common one. * * @access public * @param string * @return void */ function send_error($message = 'Incomplete Information') { echo "<?xml version=\"1.0\" encoding=\"utf-8\"?".">\n<response>\n<error>1</error>\n<message>".$message."</message>\n</response>"; exit; } // -------------------------------------------------------------------- /** * Send Trackback Success Message * * This should be called when a trackback has been * successfully received and inserted. * * @access public * @return void */ function send_success() { echo "<?xml version=\"1.0\" encoding=\"utf-8\"?".">\n<response>\n<error>0</error>\n</response>"; exit; } // -------------------------------------------------------------------- /** * Fetch a particular item * * @access public * @param string * @return string */ function data($item) { return ( ! isset($this->data[$item])) ? '' : $this->data[$item]; } // -------------------------------------------------------------------- /** * Process Trackback * * Opens a socket connection and passes the data to * the server. Returns TRUE on success, FALSE on failure * * @access public * @param string * @param string * @return bool */ function process($url, $data) { $target = parse_url($url); // Open the socket if ( ! $fp = @fsockopen($target['host'], 80)) { $this->set_error('Invalid Connection: '.$url); return FALSE; } // Build the path $ppath = ( ! isset($target['path'])) ? $url : $target['path']; $path = (isset($target['query']) && $target['query'] != "") ? $ppath.'?'.$target['query'] : $ppath; // Add the Trackback ID to the data string if ($id = $this->get_id($url)) { $data = "tb_id=".$id."&".$data; } // Transfer the data fputs ($fp, "POST " . $path . " HTTP/1.0\r\n" ); fputs ($fp, "Host: " . $target['host'] . "\r\n" ); fputs ($fp, "Content-type: application/x-www-form-urlencoded\r\n" ); fputs ($fp, "Content-length: " . strlen($data) . "\r\n" ); fputs ($fp, "Connection: close\r\n\r\n" ); fputs ($fp, $data); // Was it successful? $this->response = ""; while ( ! feof($fp)) { $this->response .= fgets($fp, 128); } @fclose($fp); if (stristr($this->response, '<error>0</error>') === FALSE) { $message = 'An unknown error was encountered'; if (preg_match("/<message>(.*?)<\/message>/is", $this->response, $match)) { $message = trim($match['1']); } $this->set_error($message); return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Extract Trackback URLs * * This function lets multiple trackbacks be sent. * It takes a string of URLs (separated by comma or * space) and puts each URL into an array * * @access public * @param string * @return string */ function extract_urls($urls) { // Remove the pesky white space and replace with a comma. $urls = preg_replace("/\s*(\S+)\s*/", "\\1,", $urls); // If they use commas get rid of the doubles. $urls = str_replace(",,", ",", $urls); // Remove any comma that might be at the end if (substr($urls, -1) == ",") { $urls = substr($urls, 0, -1); } // Break into an array via commas $urls = preg_split('/[,]/', $urls); // Removes duplicates $urls = array_unique($urls); array_walk($urls, array($this, 'validate_url')); return $urls; } // -------------------------------------------------------------------- /** * Validate URL * * Simply adds "http://" if missing * * @access public * @param string * @return string */ function validate_url($url) { $url = trim($url); if (substr($url, 0, 4) != "http") { $url = "http://".$url; } } // -------------------------------------------------------------------- /** * Find the Trackback URL's ID * * @access public * @param string * @return string */ function get_id($url) { $tb_id = ""; if (strpos($url, '?') !== FALSE) { $tb_array = explode('/', $url); $tb_end = $tb_array[count($tb_array)-1]; if ( ! is_numeric($tb_end)) { $tb_end = $tb_array[count($tb_array)-2]; } $tb_array = explode('=', $tb_end); $tb_id = $tb_array[count($tb_array)-1]; } else { $url = rtrim($url, '/'); $tb_array = explode('/', $url); $tb_id = $tb_array[count($tb_array)-1]; if ( ! is_numeric($tb_id)) { $tb_id = $tb_array[count($tb_array)-2]; } } if ( ! preg_match ("/^([0-9]+)$/", $tb_id)) { return FALSE; } else { return $tb_id; } } // -------------------------------------------------------------------- /** * Convert Reserved XML characters to Entities * * @access public * @param string * @return string */ function convert_xml($str) { $temp = '__TEMP_AMPERSANDS__'; $str = preg_replace("/&#(\d+);/", "$temp\\1;", $str); $str = preg_replace("/&(\w+);/", "$temp\\1;", $str); $str = str_replace(array("&","<",">","\"", "'", "-"), array("&amp;", "&lt;", "&gt;", "&quot;", "&#39;", "&#45;"), $str); $str = preg_replace("/$temp(\d+);/","&#\\1;",$str); $str = preg_replace("/$temp(\w+);/","&\\1;", $str); return $str; } // -------------------------------------------------------------------- /** * Character limiter * * Limits the string based on the character count. Will preserve complete words. * * @access public * @param string * @param integer * @param string * @return string */ function limit_characters($str, $n = 500, $end_char = '&#8230;') { if (strlen($str) < $n) { return $str; } $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); if (strlen($str) <= $n) { return $str; } $out = ""; foreach (explode(' ', trim($str)) as $val) { $out .= $val.' '; if (strlen($out) >= $n) { return trim($out).$end_char; } } } // -------------------------------------------------------------------- /** * High ASCII to Entities * * Converts Hight ascii text and MS Word special chars * to character entities * * @access public * @param string * @return string */ function convert_ascii($str) { $count = 1; $out = ''; $temp = array(); for ($i = 0, $s = strlen($str); $i < $s; $i++) { $ordinal = ord($str[$i]); if ($ordinal < 128) { $out .= $str[$i]; } else { if (count($temp) == 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; if (count($temp) == $count) { $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64); $out .= '&#'.$number.';'; $count = 1; $temp = array(); } } } return $out; } // -------------------------------------------------------------------- /** * Set error message * * @access public * @param string * @return void */ function set_error($msg) { log_message('error', $msg); $this->error_msg[] = $msg; } // -------------------------------------------------------------------- /** * Show error messages * * @access public * @param string * @param string * @return string */ function display_errors($open = '<p>', $close = '</p>') { $str = ''; foreach ($this->error_msg as $val) { $str .= $open.$val.$close; } return $str; } } // END Trackback Class /* End of file Trackback.php */ /* Location: ./system/libraries/Trackback.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Xmlrpcs.php
system/libraries/Xmlrpcs.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ if ( ! function_exists('xml_parser_create')) { show_error('Your PHP installation does not support XML'); } if ( ! class_exists('CI_Xmlrpc')) { show_error('You must load the Xmlrpc class before loading the Xmlrpcs class in order to create a server.'); } // ------------------------------------------------------------------------ /** * XML-RPC server class * * @package CodeIgniter * @subpackage Libraries * @category XML-RPC * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ class CI_Xmlrpcs extends CI_Xmlrpc { var $methods = array(); //array of methods mapped to function names and signatures var $debug_msg = ''; // Debug Message var $system_methods = array(); // XML RPC Server methods var $controller_obj; var $object = FALSE; /** * Constructor */ public function __construct($config=array()) { parent::__construct(); $this->set_system_methods(); if (isset($config['functions']) && is_array($config['functions'])) { $this->methods = array_merge($this->methods, $config['functions']); } log_message('debug', "XML-RPC Server Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize Prefs and Serve * * @access public * @param mixed * @return void */ function initialize($config=array()) { if (isset($config['functions']) && is_array($config['functions'])) { $this->methods = array_merge($this->methods, $config['functions']); } if (isset($config['debug'])) { $this->debug = $config['debug']; } if (isset($config['object']) && is_object($config['object'])) { $this->object = $config['object']; } if (isset($config['xss_clean'])) { $this->xss_clean = $config['xss_clean']; } } // -------------------------------------------------------------------- /** * Setting of System Methods * * @access public * @return void */ function set_system_methods() { $this->methods = array( 'system.listMethods' => array( 'function' => 'this.listMethods', 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString), array($this->xmlrpcArray)), 'docstring' => 'Returns an array of available methods on this server'), 'system.methodHelp' => array( 'function' => 'this.methodHelp', 'signature' => array(array($this->xmlrpcString, $this->xmlrpcString)), 'docstring' => 'Returns a documentation string for the specified method'), 'system.methodSignature' => array( 'function' => 'this.methodSignature', 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString)), 'docstring' => 'Returns an array describing the return type and required parameters of a method'), 'system.multicall' => array( 'function' => 'this.multicall', 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcArray)), 'docstring' => 'Combine multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details') ); } // -------------------------------------------------------------------- /** * Main Server Function * * @access public * @return void */ function serve() { $r = $this->parseRequest(); $payload = '<?xml version="1.0" encoding="'.$this->xmlrpc_defencoding.'"?'.'>'."\n"; $payload .= $this->debug_msg; $payload .= $r->prepare_response(); header("Content-Type: text/xml"); header("Content-Length: ".strlen($payload)); exit($payload); } // -------------------------------------------------------------------- /** * Add Method to Class * * @access public * @param string method name * @param string function * @param string signature * @param string docstring * @return void */ function add_to_map($methodname, $function, $sig, $doc) { $this->methods[$methodname] = array( 'function' => $function, 'signature' => $sig, 'docstring' => $doc ); } // -------------------------------------------------------------------- /** * Parse Server Request * * @access public * @param string data * @return object xmlrpc response */ function parseRequest($data='') { global $HTTP_RAW_POST_DATA; //------------------------------------- // Get Data //------------------------------------- if ($data == '') { $data = $HTTP_RAW_POST_DATA; } //------------------------------------- // Set up XML Parser //------------------------------------- $parser = xml_parser_create($this->xmlrpc_defencoding); $parser_object = new XML_RPC_Message("filler"); $parser_object->xh[$parser] = array(); $parser_object->xh[$parser]['isf'] = 0; $parser_object->xh[$parser]['isf_reason'] = ''; $parser_object->xh[$parser]['params'] = array(); $parser_object->xh[$parser]['stack'] = array(); $parser_object->xh[$parser]['valuestack'] = array(); $parser_object->xh[$parser]['method'] = ''; xml_set_object($parser, $parser_object); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); xml_set_element_handler($parser, 'open_tag', 'closing_tag'); xml_set_character_data_handler($parser, 'character_data'); //xml_set_default_handler($parser, 'default_handler'); //------------------------------------- // PARSE + PROCESS XML DATA //------------------------------------- if ( ! xml_parse($parser, $data, 1)) { // return XML error as a faultCode $r = new XML_RPC_Response(0, $this->xmlrpcerrxml + xml_get_error_code($parser), sprintf('XML error: %s at line %d', xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); xml_parser_free($parser); } elseif ($parser_object->xh[$parser]['isf']) { return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']); } else { xml_parser_free($parser); $m = new XML_RPC_Message($parser_object->xh[$parser]['method']); $plist=''; for ($i=0; $i < count($parser_object->xh[$parser]['params']); $i++) { if ($this->debug === TRUE) { $plist .= "$i - " . print_r(get_object_vars($parser_object->xh[$parser]['params'][$i]), TRUE). ";\n"; } $m->addParam($parser_object->xh[$parser]['params'][$i]); } if ($this->debug === TRUE) { echo "<pre>"; echo "---PLIST---\n" . $plist . "\n---PLIST END---\n\n"; echo "</pre>"; } $r = $this->_execute($m); } //------------------------------------- // SET DEBUGGING MESSAGE //------------------------------------- if ($this->debug === TRUE) { $this->debug_msg = "<!-- DEBUG INFO:\n\n".$plist."\n END DEBUG-->\n"; } return $r; } // -------------------------------------------------------------------- /** * Executes the Method * * @access protected * @param object * @return mixed */ function _execute($m) { $methName = $m->method_name; // Check to see if it is a system call $system_call = (strncmp($methName, 'system', 5) == 0) ? TRUE : FALSE; if ($this->xss_clean == FALSE) { $m->xss_clean = FALSE; } //------------------------------------- // Valid Method //------------------------------------- if ( ! isset($this->methods[$methName]['function'])) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } //------------------------------------- // Check for Method (and Object) //------------------------------------- $method_parts = explode(".", $this->methods[$methName]['function']); $objectCall = (isset($method_parts['1']) && $method_parts['1'] != "") ? TRUE : FALSE; if ($system_call === TRUE) { if ( ! is_callable(array($this,$method_parts['1']))) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } } else { if ($objectCall && ! is_callable(array($method_parts['0'],$method_parts['1']))) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } elseif ( ! $objectCall && ! is_callable($this->methods[$methName]['function'])) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } } //------------------------------------- // Checking Methods Signature //------------------------------------- if (isset($this->methods[$methName]['signature'])) { $sig = $this->methods[$methName]['signature']; for ($i=0; $i<count($sig); $i++) { $current_sig = $sig[$i]; if (count($current_sig) == count($m->params)+1) { for ($n=0; $n < count($m->params); $n++) { $p = $m->params[$n]; $pt = ($p->kindOf() == 'scalar') ? $p->scalarval() : $p->kindOf(); if ($pt != $current_sig[$n+1]) { $pno = $n+1; $wanted = $current_sig[$n+1]; return new XML_RPC_Response(0, $this->xmlrpcerr['incorrect_params'], $this->xmlrpcstr['incorrect_params'] . ": Wanted {$wanted}, got {$pt} at param {$pno})"); } } } } } //------------------------------------- // Calls the Function //------------------------------------- if ($objectCall === TRUE) { if ($method_parts[0] == "this" && $system_call == TRUE) { return call_user_func(array($this, $method_parts[1]), $m); } else { if ($this->object === FALSE) { $CI =& get_instance(); return $CI->$method_parts['1']($m); } else { return $this->object->$method_parts['1']($m); //return call_user_func(array(&$method_parts['0'],$method_parts['1']), $m); } } } else { return call_user_func($this->methods[$methName]['function'], $m); } } // -------------------------------------------------------------------- /** * Server Function: List Methods * * @access public * @param mixed * @return object */ function listMethods($m) { $v = new XML_RPC_Values(); $output = array(); foreach ($this->methods as $key => $value) { $output[] = new XML_RPC_Values($key, 'string'); } foreach ($this->system_methods as $key => $value) { $output[]= new XML_RPC_Values($key, 'string'); } $v->addArray($output); return new XML_RPC_Response($v); } // -------------------------------------------------------------------- /** * Server Function: Return Signature for Method * * @access public * @param mixed * @return object */ function methodSignature($m) { $parameters = $m->output_parameters(); $method_name = $parameters[0]; if (isset($this->methods[$method_name])) { if ($this->methods[$method_name]['signature']) { $sigs = array(); $signature = $this->methods[$method_name]['signature']; for ($i=0; $i < count($signature); $i++) { $cursig = array(); $inSig = $signature[$i]; for ($j=0; $j<count($inSig); $j++) { $cursig[]= new XML_RPC_Values($inSig[$j], 'string'); } $sigs[]= new XML_RPC_Values($cursig, 'array'); } $r = new XML_RPC_Response(new XML_RPC_Values($sigs, 'array')); } else { $r = new XML_RPC_Response(new XML_RPC_Values('undef', 'string')); } } else { $r = new XML_RPC_Response(0,$this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); } return $r; } // -------------------------------------------------------------------- /** * Server Function: Doc String for Method * * @access public * @param mixed * @return object */ function methodHelp($m) { $parameters = $m->output_parameters(); $method_name = $parameters[0]; if (isset($this->methods[$method_name])) { $docstring = isset($this->methods[$method_name]['docstring']) ? $this->methods[$method_name]['docstring'] : ''; return new XML_RPC_Response(new XML_RPC_Values($docstring, 'string')); } else { return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); } } // -------------------------------------------------------------------- /** * Server Function: Multi-call * * @access public * @param mixed * @return object */ function multicall($m) { // Disabled return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); $parameters = $m->output_parameters(); $calls = $parameters[0]; $result = array(); foreach ($calls as $value) { //$attempt = $this->_execute(new XML_RPC_Message($value[0], $value[1])); $m = new XML_RPC_Message($value[0]); $plist=''; for ($i=0; $i < count($value[1]); $i++) { $m->addParam(new XML_RPC_Values($value[1][$i], 'string')); } $attempt = $this->_execute($m); if ($attempt->faultCode() != 0) { return $attempt; } $result[] = new XML_RPC_Values(array($attempt->value()), 'array'); } return new XML_RPC_Response(new XML_RPC_Values($result, 'array')); } // -------------------------------------------------------------------- /** * Multi-call Function: Error Handling * * @access public * @param mixed * @return object */ function multicall_error($err) { $str = is_string($err) ? $this->xmlrpcstr["multicall_${err}"] : $err->faultString(); $code = is_string($err) ? $this->xmlrpcerr["multicall_${err}"] : $err->faultCode(); $struct['faultCode'] = new XML_RPC_Values($code, 'int'); $struct['faultString'] = new XML_RPC_Values($str, 'string'); return new XML_RPC_Values($struct, 'struct'); } // -------------------------------------------------------------------- /** * Multi-call Function: Processes method * * @access public * @param mixed * @return object */ function do_multicall($call) { if ($call->kindOf() != 'struct') { return $this->multicall_error('notstruct'); } elseif ( ! $methName = $call->me['struct']['methodName']) { return $this->multicall_error('nomethod'); } list($scalar_type,$scalar_value)=each($methName->me); $scalar_type = $scalar_type == $this->xmlrpcI4 ? $this->xmlrpcInt : $scalar_type; if ($methName->kindOf() != 'scalar' OR $scalar_type != 'string') { return $this->multicall_error('notstring'); } elseif ($scalar_value == 'system.multicall') { return $this->multicall_error('recursion'); } elseif ( ! $params = $call->me['struct']['params']) { return $this->multicall_error('noparams'); } elseif ($params->kindOf() != 'array') { return $this->multicall_error('notarray'); } list($a,$b)=each($params->me); $numParams = count($b); $msg = new XML_RPC_Message($scalar_value); for ($i = 0; $i < $numParams; $i++) { $msg->params[] = $params->me['array'][$i]; } $result = $this->_execute($msg); if ($result->faultCode() != 0) { return $this->multicall_error($result); } return new XML_RPC_Values(array($result->value()), 'array'); } } // END XML_RPC_Server class /* End of file Xmlrpcs.php */ /* Location: ./system/libraries/Xmlrpcs.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Javascript.php
system/libraries/Javascript.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Javascript Class * * @package CodeIgniter * @subpackage Libraries * @category Javascript * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/javascript.html */ class CI_Javascript { var $_javascript_location = 'js'; public function __construct($params = array()) { $defaults = array('js_library_driver' => 'jquery', 'autoload' => TRUE); foreach ($defaults as $key => $val) { if (isset($params[$key]) && $params[$key] !== "") { $defaults[$key] = $params[$key]; } } extract($defaults); $this->CI =& get_instance(); // load the requested js library $this->CI->load->library('javascript/'.$js_library_driver, array('autoload' => $autoload)); // make js to refer to current library $this->js =& $this->CI->$js_library_driver; log_message('debug', "Javascript Class Initialized and loaded. Driver used: $js_library_driver"); } // -------------------------------------------------------------------- // Event Code // -------------------------------------------------------------------- /** * Blur * * Outputs a javascript library blur event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function blur($element = 'this', $js = '') { return $this->js->_blur($element, $js); } // -------------------------------------------------------------------- /** * Change * * Outputs a javascript library change event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function change($element = 'this', $js = '') { return $this->js->_change($element, $js); } // -------------------------------------------------------------------- /** * Click * * Outputs a javascript library click event * * @access public * @param string The element to attach the event to * @param string The code to execute * @param boolean whether or not to return false * @return string */ function click($element = 'this', $js = '', $ret_false = TRUE) { return $this->js->_click($element, $js, $ret_false); } // -------------------------------------------------------------------- /** * Double Click * * Outputs a javascript library dblclick event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function dblclick($element = 'this', $js = '') { return $this->js->_dblclick($element, $js); } // -------------------------------------------------------------------- /** * Error * * Outputs a javascript library error event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function error($element = 'this', $js = '') { return $this->js->_error($element, $js); } // -------------------------------------------------------------------- /** * Focus * * Outputs a javascript library focus event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function focus($element = 'this', $js = '') { return $this->js->__add_event($focus, $js); } // -------------------------------------------------------------------- /** * Hover * * Outputs a javascript library hover event * * @access public * @param string - element * @param string - Javascript code for mouse over * @param string - Javascript code for mouse out * @return string */ function hover($element = 'this', $over, $out) { return $this->js->__hover($element, $over, $out); } // -------------------------------------------------------------------- /** * Keydown * * Outputs a javascript library keydown event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function keydown($element = 'this', $js = '') { return $this->js->_keydown($element, $js); } // -------------------------------------------------------------------- /** * Keyup * * Outputs a javascript library keydown event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function keyup($element = 'this', $js = '') { return $this->js->_keyup($element, $js); } // -------------------------------------------------------------------- /** * Load * * Outputs a javascript library load event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function load($element = 'this', $js = '') { return $this->js->_load($element, $js); } // -------------------------------------------------------------------- /** * Mousedown * * Outputs a javascript library mousedown event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function mousedown($element = 'this', $js = '') { return $this->js->_mousedown($element, $js); } // -------------------------------------------------------------------- /** * Mouse Out * * Outputs a javascript library mouseout event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function mouseout($element = 'this', $js = '') { return $this->js->_mouseout($element, $js); } // -------------------------------------------------------------------- /** * Mouse Over * * Outputs a javascript library mouseover event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function mouseover($element = 'this', $js = '') { return $this->js->_mouseover($element, $js); } // -------------------------------------------------------------------- /** * Mouseup * * Outputs a javascript library mouseup event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function mouseup($element = 'this', $js = '') { return $this->js->_mouseup($element, $js); } // -------------------------------------------------------------------- /** * Output * * Outputs the called javascript to the screen * * @access public * @param string The code to output * @return string */ function output($js) { return $this->js->_output($js); } // -------------------------------------------------------------------- /** * Ready * * Outputs a javascript library mouseup event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function ready($js) { return $this->js->_document_ready($js); } // -------------------------------------------------------------------- /** * Resize * * Outputs a javascript library resize event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function resize($element = 'this', $js = '') { return $this->js->_resize($element, $js); } // -------------------------------------------------------------------- /** * Scroll * * Outputs a javascript library scroll event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function scroll($element = 'this', $js = '') { return $this->js->_scroll($element, $js); } // -------------------------------------------------------------------- /** * Unload * * Outputs a javascript library unload event * * @access public * @param string The element to attach the event to * @param string The code to execute * @return string */ function unload($element = 'this', $js = '') { return $this->js->_unload($element, $js); } // -------------------------------------------------------------------- // Effects // -------------------------------------------------------------------- /** * Add Class * * Outputs a javascript library addClass event * * @access public * @param string - element * @param string - Class to add * @return string */ function addClass($element = 'this', $class = '') { return $this->js->_addClass($element, $class); } // -------------------------------------------------------------------- /** * Animate * * Outputs a javascript library animate event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function animate($element = 'this', $params = array(), $speed = '', $extra = '') { return $this->js->_animate($element, $params, $speed, $extra); } // -------------------------------------------------------------------- /** * Fade In * * Outputs a javascript library hide event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function fadeIn($element = 'this', $speed = '', $callback = '') { return $this->js->_fadeIn($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Fade Out * * Outputs a javascript library hide event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function fadeOut($element = 'this', $speed = '', $callback = '') { return $this->js->_fadeOut($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Slide Up * * Outputs a javascript library slideUp event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function slideUp($element = 'this', $speed = '', $callback = '') { return $this->js->_slideUp($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Remove Class * * Outputs a javascript library removeClass event * * @access public * @param string - element * @param string - Class to add * @return string */ function removeClass($element = 'this', $class = '') { return $this->js->_removeClass($element, $class); } // -------------------------------------------------------------------- /** * Slide Down * * Outputs a javascript library slideDown event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function slideDown($element = 'this', $speed = '', $callback = '') { return $this->js->_slideDown($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Slide Toggle * * Outputs a javascript library slideToggle event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function slideToggle($element = 'this', $speed = '', $callback = '') { return $this->js->_slideToggle($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Hide * * Outputs a javascript library hide action * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function hide($element = 'this', $speed = '', $callback = '') { return $this->js->_hide($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Toggle * * Outputs a javascript library toggle event * * @access public * @param string - element * @return string */ function toggle($element = 'this') { return $this->js->_toggle($element); } // -------------------------------------------------------------------- /** * Toggle Class * * Outputs a javascript library toggle class event * * @access public * @param string - element * @return string */ function toggleClass($element = 'this', $class='') { return $this->js->_toggleClass($element, $class); } // -------------------------------------------------------------------- /** * Show * * Outputs a javascript library show event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function show($element = 'this', $speed = '', $callback = '') { return $this->js->_show($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Compile * * gather together all script needing to be output * * @access public * @param string The element to attach the event to * @return string */ function compile($view_var = 'script_foot', $script_tags = TRUE) { $this->js->_compile($view_var, $script_tags); } /** * Clear Compile * * Clears any previous javascript collected for output * * @access public * @return void */ function clear_compile() { $this->js->_clear_compile(); } // -------------------------------------------------------------------- /** * External * * Outputs a <script> tag with the source as an external js file * * @access public * @param string The element to attach the event to * @return string */ function external($external_file = '', $relative = FALSE) { if ($external_file !== '') { $this->_javascript_location = $external_file; } else { if ($this->CI->config->item('javascript_location') != '') { $this->_javascript_location = $this->CI->config->item('javascript_location'); } } if ($relative === TRUE OR strncmp($external_file, 'http://', 7) == 0 OR strncmp($external_file, 'https://', 8) == 0) { $str = $this->_open_script($external_file); } elseif (strpos($this->_javascript_location, 'http://') !== FALSE) { $str = $this->_open_script($this->_javascript_location.$external_file); } else { $str = $this->_open_script($this->CI->config->slash_item('base_url').$this->_javascript_location.$external_file); } $str .= $this->_close_script(); return $str; } // -------------------------------------------------------------------- /** * Inline * * Outputs a <script> tag * * @access public * @param string The element to attach the event to * @param boolean If a CDATA section should be added * @return string */ function inline($script, $cdata = TRUE) { $str = $this->_open_script(); $str .= ($cdata) ? "\n// <![CDATA[\n{$script}\n// ]]>\n" : "\n{$script}\n"; $str .= $this->_close_script(); return $str; } // -------------------------------------------------------------------- /** * Open Script * * Outputs an opening <script> * * @access private * @param string * @return string */ function _open_script($src = '') { $str = '<script type="text/javascript" charset="'.strtolower($this->CI->config->item('charset')).'"'; $str .= ($src == '') ? '>' : ' src="'.$src.'">'; return $str; } // -------------------------------------------------------------------- /** * Close Script * * Outputs an closing </script> * * @access private * @param string * @return string */ function _close_script($extra = "\n") { return "</script>$extra"; } // -------------------------------------------------------------------- // -------------------------------------------------------------------- // AJAX-Y STUFF - still a testbed // -------------------------------------------------------------------- // -------------------------------------------------------------------- /** * Update * * Outputs a javascript library slideDown event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function update($element = 'this', $speed = '', $callback = '') { return $this->js->_updater($element, $speed, $callback); } // -------------------------------------------------------------------- /** * Generate JSON * * Can be passed a database result or associative array and returns a JSON formatted string * * @param mixed result set or array * @param bool match array types (defaults to objects) * @return string a json formatted string */ function generate_json($result = NULL, $match_array_type = FALSE) { // JSON data can optionally be passed to this function // either as a database result object or an array, or a user supplied array if ( ! is_null($result)) { if (is_object($result)) { $json_result = $result->result_array(); } elseif (is_array($result)) { $json_result = $result; } else { return $this->_prep_args($result); } } else { return 'null'; } $json = array(); $_is_assoc = TRUE; if ( ! is_array($json_result) AND empty($json_result)) { show_error("Generate JSON Failed - Illegal key, value pair."); } elseif ($match_array_type) { $_is_assoc = $this->_is_associative_array($json_result); } foreach ($json_result as $k => $v) { if ($_is_assoc) { $json[] = $this->_prep_args($k, TRUE).':'.$this->generate_json($v, $match_array_type); } else { $json[] = $this->generate_json($v, $match_array_type); } } $json = implode(',', $json); return $_is_assoc ? "{".$json."}" : "[".$json."]"; } // -------------------------------------------------------------------- /** * Is associative array * * Checks for an associative array * * @access public * @param type * @return type */ function _is_associative_array($arr) { foreach (array_keys($arr) as $key => $val) { if ($key !== $val) { return TRUE; } } return FALSE; } // -------------------------------------------------------------------- /** * Prep Args * * Ensures a standard json value and escapes values * * @access public * @param type * @return type */ function _prep_args($result, $is_key = FALSE) { if (is_null($result)) { return 'null'; } elseif (is_bool($result)) { return ($result === TRUE) ? 'true' : 'false'; } elseif (is_string($result) OR $is_key) { return '"'.str_replace(array('\\', "\t", "\n", "\r", '"', '/'), array('\\\\', '\\t', '\\n', "\\r", '\"', '\/'), $result).'"'; } elseif (is_scalar($result)) { return $result; } } // -------------------------------------------------------------------- } // END Javascript Class /* End of file Javascript.php */ /* Location: ./system/libraries/Javascript.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Typography.php
system/libraries/Typography.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Typography Class * * * @access private * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/ */ class CI_Typography { // Block level elements that should not be wrapped inside <p> tags var $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul'; // Elements that should not have <p> and <br /> tags within them. var $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d'; // Tags we want the parser to completely ignore when splitting the string. var $inline_elements = 'a|abbr|acronym|b|bdo|big|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|q|samp|select|small|span|strong|sub|sup|textarea|tt|var'; // array of block level elements that require inner content to be within another block level element var $inner_block_required = array('blockquote'); // the last block element parsed var $last_block_element = ''; // whether or not to protect quotes within { curly braces } var $protect_braced_quotes = FALSE; /** * Auto Typography * * This function converts text, making it typographically correct: * - Converts double spaces into paragraphs. * - Converts single line breaks into <br /> tags * - Converts single and double quotes into correctly facing curly quote entities. * - Converts three dots into ellipsis. * - Converts double dashes into em-dashes. * - Converts two spaces into entities * * @access public * @param string * @param bool whether to reduce more then two consecutive newlines to two * @return string */ function auto_typography($str, $reduce_linebreaks = FALSE) { if ($str == '') { return ''; } // Standardize Newlines to make matching easier if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } // Reduce line breaks. If there are more than two consecutive linebreaks // we'll compress them down to a maximum of two since there's no benefit to more. if ($reduce_linebreaks === TRUE) { $str = preg_replace("/\n\n+/", "\n\n", $str); } // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed $html_comments = array(); if (strpos($str, '<!--') !== FALSE) { if (preg_match_all("#(<!\-\-.*?\-\->)#s", $str, $matches)) { for ($i = 0, $total = count($matches[0]); $i < $total; $i++) { $html_comments[] = $matches[0][$i]; $str = str_replace($matches[0][$i], '{@HC'.$i.'}', $str); } } } // match and yank <pre> tags if they exist. It's cheaper to do this separately since most content will // not contain <pre> tags, and it keeps the PCRE patterns below simpler and faster if (strpos($str, '<pre') !== FALSE) { $str = preg_replace_callback("#<pre.*?>.*?</pre>#si", array($this, '_protect_characters'), $str); } // Convert quotes within tags to temporary markers. $str = preg_replace_callback("#<.+?>#si", array($this, '_protect_characters'), $str); // Do the same with braces if necessary if ($this->protect_braced_quotes === TRUE) { $str = preg_replace_callback("#\{.+?\}#si", array($this, '_protect_characters'), $str); } // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG} $str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str); // Split the string at every tag. This expression creates an array with this prototype: // // [array] // { // [0] = <opening tag> // [1] = Content... // [2] = <closing tag> // Etc... // } $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text $str = ''; $process = TRUE; $paragraph = FALSE; $current_chunk = 0; $total_chunks = count($chunks); foreach ($chunks as $chunk) { $current_chunk++; // Are we dealing with a tag? If so, we'll skip the processing for this cycle. // Well also set the "process" flag which allows us to skip <pre> tags and a few other things. if (preg_match("#<(/*)(".$this->block_elements.").*?>#", $chunk, $match)) { if (preg_match("#".$this->skip_elements."#", $match[2])) { $process = ($match[1] == '/') ? TRUE : FALSE; } if ($match[1] == '') { $this->last_block_element = $match[2]; } $str .= $chunk; continue; } if ($process == FALSE) { $str .= $chunk; continue; } // Force a newline to make sure end tags get processed by _format_newlines() if ($current_chunk == $total_chunks) { $chunk .= "\n"; } // Convert Newlines into <p> and <br /> tags $str .= $this->_format_newlines($chunk); } // No opening block level tag? Add it if needed. if ( ! preg_match("/^\s*<(?:".$this->block_elements.")/i", $str)) { $str = preg_replace("/^(.*?)<(".$this->block_elements.")/i", '<p>$1</p><$2', $str); } // Convert quotes, elipsis, em-dashes, non-breaking spaces, and ampersands $str = $this->format_characters($str); // restore HTML comments for ($i = 0, $total = count($html_comments); $i < $total; $i++) { // remove surrounding paragraph tags, but only if there's an opening paragraph tag // otherwise HTML comments at the ends of paragraphs will have the closing tag removed // if '<p>{@HC1}' then replace <p>{@HC1}</p> with the comment, else replace only {@HC1} with the comment $str = preg_replace('#(?(?=<p>\{@HC'.$i.'\})<p>\{@HC'.$i.'\}(\s*</p>)|\{@HC'.$i.'\})#s', $html_comments[$i], $str); } // Final clean up $table = array( // If the user submitted their own paragraph tags within the text // we will retain them instead of using our tags. '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix // Reduce multiple instances of opening/closing paragraph tags to a single one '#(</p>)+#' => '</p>', '/(<p>\W*<p>)+/' => '<p>', // Clean up stray paragraph tags that appear before block level elements '#<p></p><('.$this->block_elements.')#' => '<$1', // Clean up stray non-breaking spaces preceeding block elements '#(&nbsp;\s*)+<('.$this->block_elements.')#' => ' <$2', // Replace the temporary markers we added earlier '/\{@TAG\}/' => '<', '/\{@DQ\}/' => '"', '/\{@SQ\}/' => "'", '/\{@DD\}/' => '--', '/\{@NBS\}/' => ' ', // An unintended consequence of the _format_newlines function is that // some of the newlines get truncated, resulting in <p> tags // starting immediately after <block> tags on the same line. // This forces a newline after such occurrences, which looks much nicer. "/><p>\n/" => ">\n<p>", // Similarly, there might be cases where a closing </block> will follow // a closing </p> tag, so we'll correct it by adding a newline in between "#</p></#" => "</p>\n</" ); // Do we need to reduce empty lines? if ($reduce_linebreaks === TRUE) { $table['#<p>\n*</p>#'] = ''; } else { // If we have empty paragraph tags we add a non-breaking space // otherwise most browsers won't treat them as true paragraphs $table['#<p></p>#'] = '<p>&nbsp;</p>'; } return preg_replace(array_keys($table), $table, $str); } // -------------------------------------------------------------------- /** * Format Characters * * This function mainly converts double and single quotes * to curly entities, but it also converts em-dashes, * double spaces, and ampersands * * @access public * @param string * @return string */ function format_characters($str) { static $table; if ( ! isset($table)) { $table = array( // nested smart quotes, opening and closing // note that rules for grammar (English) allow only for two levels deep // and that single quotes are _supposed_ to always be on the outside // but we'll accommodate both // Note that in all cases, whitespace is the primary determining factor // on which direction to curl, with non-word characters like punctuation // being a secondary factor only after whitespace is addressed. '/\'"(\s|$)/' => '&#8217;&#8221;$1', '/(^|\s|<p>)\'"/' => '$1&#8216;&#8220;', '/\'"(\W)/' => '&#8217;&#8221;$1', '/(\W)\'"/' => '$1&#8216;&#8220;', '/"\'(\s|$)/' => '&#8221;&#8217;$1', '/(^|\s|<p>)"\'/' => '$1&#8220;&#8216;', '/"\'(\W)/' => '&#8221;&#8217;$1', '/(\W)"\'/' => '$1&#8220;&#8216;', // single quote smart quotes '/\'(\s|$)/' => '&#8217;$1', '/(^|\s|<p>)\'/' => '$1&#8216;', '/\'(\W)/' => '&#8217;$1', '/(\W)\'/' => '$1&#8216;', // double quote smart quotes '/"(\s|$)/' => '&#8221;$1', '/(^|\s|<p>)"/' => '$1&#8220;', '/"(\W)/' => '&#8221;$1', '/(\W)"/' => '$1&#8220;', // apostrophes "/(\w)'(\w)/" => '$1&#8217;$2', // Em dash and ellipses dots '/\s?\-\-\s?/' => '&#8212;', '/(\w)\.{3}/' => '$1&#8230;', // double space after sentences '/(\W) /' => '$1&nbsp; ', // ampersands, if not a character entity '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;' ); } return preg_replace(array_keys($table), $table, $str); } // -------------------------------------------------------------------- /** * Format Newlines * * Converts newline characters into either <p> tags or <br /> * * @access public * @param string * @return string */ function _format_newlines($str) { if ($str == '') { return $str; } if (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required)) { return $str; } // Convert two consecutive newlines to paragraphs $str = str_replace("\n\n", "</p>\n\n<p>", $str); // Convert single spaces to <br /> tags $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str); // Wrap the whole enchilada in enclosing paragraphs if ($str != "\n") { // We trim off the right-side new line so that the closing </p> tag // will be positioned immediately following the string, matching // the behavior of the opening <p> tag $str = '<p>'.rtrim($str).'</p>'; } // Remove empty paragraphs if they are on the first line, as this // is a potential unintended consequence of the previous code $str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1); return $str; } // ------------------------------------------------------------------------ /** * Protect Characters * * Protects special characters from being formatted later * We don't want quotes converted within tags so we'll temporarily convert them to {@DQ} and {@SQ} * and we don't want double dashes converted to emdash entities, so they are marked with {@DD} * likewise double spaces are converted to {@NBS} to prevent entity conversion * * @access public * @param array * @return string */ function _protect_characters($match) { return str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $match[0]); } // -------------------------------------------------------------------- /** * Convert newlines to HTML line breaks except within PRE tags * * @access public * @param string * @return string */ function nl2br_except_pre($str) { $ex = explode("pre>",$str); $ct = count($ex); $newstr = ""; for ($i = 0; $i < $ct; $i++) { if (($i % 2) == 0) { $newstr .= nl2br($ex[$i]); } else { $newstr .= $ex[$i]; } if ($ct - 1 != $i) $newstr .= "pre>"; } return $newstr; } } // END Typography Class /* End of file Typography.php */ /* Location: ./system/libraries/Typography.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/User_agent.php
system/libraries/User_agent.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * User Agent Class * * Identifies the platform, browser, robot, or mobile devise of the browsing agent * * @package CodeIgniter * @subpackage Libraries * @category User Agent * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/user_agent.html */ class CI_User_agent { var $agent = NULL; var $is_browser = FALSE; var $is_robot = FALSE; var $is_mobile = FALSE; var $languages = array(); var $charsets = array(); var $platforms = array(); var $browsers = array(); var $mobiles = array(); var $robots = array(); var $platform = ''; var $browser = ''; var $version = ''; var $mobile = ''; var $robot = ''; /** * Constructor * * Sets the User Agent and runs the compilation routine * * @access public * @return void */ public function __construct() { if (isset($_SERVER['HTTP_USER_AGENT'])) { $this->agent = trim($_SERVER['HTTP_USER_AGENT']); } if ( ! is_null($this->agent)) { if ($this->_load_agent_file()) { $this->_compile_data(); } } log_message('debug', "User Agent Class Initialized"); } // -------------------------------------------------------------------- /** * Compile the User Agent Data * * @access private * @return bool */ private function _load_agent_file() { if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php'); } elseif (is_file(APPPATH.'config/user_agents.php')) { include(APPPATH.'config/user_agents.php'); } else { return FALSE; } $return = FALSE; if (isset($platforms)) { $this->platforms = $platforms; unset($platforms); $return = TRUE; } if (isset($browsers)) { $this->browsers = $browsers; unset($browsers); $return = TRUE; } if (isset($mobiles)) { $this->mobiles = $mobiles; unset($mobiles); $return = TRUE; } if (isset($robots)) { $this->robots = $robots; unset($robots); $return = TRUE; } return $return; } // -------------------------------------------------------------------- /** * Compile the User Agent Data * * @access private * @return bool */ private function _compile_data() { $this->_set_platform(); foreach (array('_set_robot', '_set_browser', '_set_mobile') as $function) { if ($this->$function() === TRUE) { break; } } } // -------------------------------------------------------------------- /** * Set the Platform * * @access private * @return mixed */ private function _set_platform() { if (is_array($this->platforms) AND count($this->platforms) > 0) { foreach ($this->platforms as $key => $val) { if (preg_match("|".preg_quote($key)."|i", $this->agent)) { $this->platform = $val; return TRUE; } } } $this->platform = 'Unknown Platform'; } // -------------------------------------------------------------------- /** * Set the Browser * * @access private * @return bool */ private function _set_browser() { if (is_array($this->browsers) AND count($this->browsers) > 0) { foreach ($this->browsers as $key => $val) { if (preg_match("|".preg_quote($key).".*?([0-9\.]+)|i", $this->agent, $match)) { $this->is_browser = TRUE; $this->version = $match[1]; $this->browser = $val; $this->_set_mobile(); return TRUE; } } } return FALSE; } // -------------------------------------------------------------------- /** * Set the Robot * * @access private * @return bool */ private function _set_robot() { if (is_array($this->robots) AND count($this->robots) > 0) { foreach ($this->robots as $key => $val) { if (preg_match("|".preg_quote($key)."|i", $this->agent)) { $this->is_robot = TRUE; $this->robot = $val; return TRUE; } } } return FALSE; } // -------------------------------------------------------------------- /** * Set the Mobile Device * * @access private * @return bool */ private function _set_mobile() { if (is_array($this->mobiles) AND count($this->mobiles) > 0) { foreach ($this->mobiles as $key => $val) { if (FALSE !== (strpos(strtolower($this->agent), $key))) { $this->is_mobile = TRUE; $this->mobile = $val; return TRUE; } } } return FALSE; } // -------------------------------------------------------------------- /** * Set the accepted languages * * @access private * @return void */ private function _set_languages() { if ((count($this->languages) == 0) AND isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) AND $_SERVER['HTTP_ACCEPT_LANGUAGE'] != '') { $languages = preg_replace('/(;q=[0-9\.]+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE']))); $this->languages = explode(',', $languages); } if (count($this->languages) == 0) { $this->languages = array('Undefined'); } } // -------------------------------------------------------------------- /** * Set the accepted character sets * * @access private * @return void */ private function _set_charsets() { if ((count($this->charsets) == 0) AND isset($_SERVER['HTTP_ACCEPT_CHARSET']) AND $_SERVER['HTTP_ACCEPT_CHARSET'] != '') { $charsets = preg_replace('/(;q=.+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET']))); $this->charsets = explode(',', $charsets); } if (count($this->charsets) == 0) { $this->charsets = array('Undefined'); } } // -------------------------------------------------------------------- /** * Is Browser * * @access public * @return bool */ public function is_browser($key = NULL) { if ( ! $this->is_browser) { return FALSE; } // No need to be specific, it's a browser if ($key === NULL) { return TRUE; } // Check for a specific browser return array_key_exists($key, $this->browsers) AND $this->browser === $this->browsers[$key]; } // -------------------------------------------------------------------- /** * Is Robot * * @access public * @return bool */ public function is_robot($key = NULL) { if ( ! $this->is_robot) { return FALSE; } // No need to be specific, it's a robot if ($key === NULL) { return TRUE; } // Check for a specific robot return array_key_exists($key, $this->robots) AND $this->robot === $this->robots[$key]; } // -------------------------------------------------------------------- /** * Is Mobile * * @access public * @return bool */ public function is_mobile($key = NULL) { if ( ! $this->is_mobile) { return FALSE; } // No need to be specific, it's a mobile if ($key === NULL) { return TRUE; } // Check for a specific robot return array_key_exists($key, $this->mobiles) AND $this->mobile === $this->mobiles[$key]; } // -------------------------------------------------------------------- /** * Is this a referral from another site? * * @access public * @return bool */ public function is_referral() { if ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') { return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Agent String * * @access public * @return string */ public function agent_string() { return $this->agent; } // -------------------------------------------------------------------- /** * Get Platform * * @access public * @return string */ public function platform() { return $this->platform; } // -------------------------------------------------------------------- /** * Get Browser Name * * @access public * @return string */ public function browser() { return $this->browser; } // -------------------------------------------------------------------- /** * Get the Browser Version * * @access public * @return string */ public function version() { return $this->version; } // -------------------------------------------------------------------- /** * Get The Robot Name * * @access public * @return string */ public function robot() { return $this->robot; } // -------------------------------------------------------------------- /** * Get the Mobile Device * * @access public * @return string */ public function mobile() { return $this->mobile; } // -------------------------------------------------------------------- /** * Get the referrer * * @access public * @return bool */ public function referrer() { return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? '' : trim($_SERVER['HTTP_REFERER']); } // -------------------------------------------------------------------- /** * Get the accepted languages * * @access public * @return array */ public function languages() { if (count($this->languages) == 0) { $this->_set_languages(); } return $this->languages; } // -------------------------------------------------------------------- /** * Get the accepted Character Sets * * @access public * @return array */ public function charsets() { if (count($this->charsets) == 0) { $this->_set_charsets(); } return $this->charsets; } // -------------------------------------------------------------------- /** * Test for a particular language * * @access public * @return bool */ public function accept_lang($lang = 'en') { return (in_array(strtolower($lang), $this->languages(), TRUE)); } // -------------------------------------------------------------------- /** * Test for a particular character set * * @access public * @return bool */ public function accept_charset($charset = 'utf-8') { return (in_array(strtolower($charset), $this->charsets(), TRUE)); } } /* End of file User_agent.php */ /* Location: ./system/libraries/User_agent.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Parser.php
system/libraries/Parser.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Parser Class * * @package CodeIgniter * @subpackage Libraries * @category Parser * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/parser.html */ class CI_Parser { var $l_delim = '{'; var $r_delim = '}'; var $object; /** * Parse a template * * Parses pseudo-variables contained in the specified template view, * replacing them with the data in the second param * * @access public * @param string * @param array * @param bool * @return string */ public function parse($template, $data, $return = FALSE) { $CI =& get_instance(); $template = $CI->load->view($template, $data, TRUE); return $this->_parse($template, $data, $return); } // -------------------------------------------------------------------- /** * Parse a String * * Parses pseudo-variables contained in the specified string, * replacing them with the data in the second param * * @access public * @param string * @param array * @param bool * @return string */ function parse_string($template, $data, $return = FALSE) { return $this->_parse($template, $data, $return); } // -------------------------------------------------------------------- /** * Parse a template * * Parses pseudo-variables contained in the specified template, * replacing them with the data in the second param * * @access public * @param string * @param array * @param bool * @return string */ function _parse($template, $data, $return = FALSE) { if ($template == '') { return FALSE; } foreach ($data as $key => $val) { if (is_array($val)) { $template = $this->_parse_pair($key, $val, $template); } else { $template = $this->_parse_single($key, (string)$val, $template); } } if ($return == FALSE) { $CI =& get_instance(); $CI->output->append_output($template); } return $template; } // -------------------------------------------------------------------- /** * Set the left/right variable delimiters * * @access public * @param string * @param string * @return void */ function set_delimiters($l = '{', $r = '}') { $this->l_delim = $l; $this->r_delim = $r; } // -------------------------------------------------------------------- /** * Parse a single key/value * * @access private * @param string * @param string * @param string * @return string */ function _parse_single($key, $val, $string) { return str_replace($this->l_delim.$key.$this->r_delim, $val, $string); } // -------------------------------------------------------------------- /** * Parse a tag pair * * Parses tag pairs: {some_tag} string... {/some_tag} * * @access private * @param string * @param array * @param string * @return string */ function _parse_pair($variable, $data, $string) { if (FALSE === ($match = $this->_match_pair($string, $variable))) { return $string; } $str = ''; foreach ($data as $row) { $temp = $match['1']; foreach ($row as $key => $val) { if ( ! is_array($val)) { $temp = $this->_parse_single($key, $val, $temp); } else { $temp = $this->_parse_pair($key, $val, $temp); } } $str .= $temp; } return str_replace($match['0'], $str, $string); } // -------------------------------------------------------------------- /** * Matches a variable pair * * @access private * @param string * @param string * @return mixed */ function _match_pair($string, $variable) { if ( ! preg_match("|" . preg_quote($this->l_delim) . $variable . preg_quote($this->r_delim) . "(.+?)". preg_quote($this->l_delim) . '/' . $variable . preg_quote($this->r_delim) . "|s", $string, $match)) { return FALSE; } return $match; } } // END Parser Class /* End of file Parser.php */ /* Location: ./system/libraries/Parser.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Cart.php
system/libraries/Cart.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2006 - 2012, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Shopping Cart Class * * @package CodeIgniter * @subpackage Libraries * @category Shopping Cart * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/cart.html */ class CI_Cart { // These are the regular expression rules that we use to validate the product ID and product name var $product_id_rules = '\.a-z0-9_-'; // alpha-numeric, dashes, underscores, or periods var $product_name_rules = '\.\:\-_ a-z0-9'; // alpha-numeric, dashes, underscores, colons or periods // Private variables. Do not change! var $CI; var $_cart_contents = array(); /** * Shopping Class Constructor * * The constructor loads the Session class, used to store the shopping cart contents. */ public function __construct($params = array()) { // Set the super object to a local variable for use later $this->CI =& get_instance(); // Are any config settings being passed manually? If so, set them $config = array(); if (count($params) > 0) { foreach ($params as $key => $val) { $config[$key] = $val; } } // Load the Sessions class $this->CI->load->library('session', $config); // Grab the shopping cart array from the session table, if it exists if ($this->CI->session->userdata('cart_contents') !== FALSE) { $this->_cart_contents = $this->CI->session->userdata('cart_contents'); } else { // No cart exists so we'll set some base values $this->_cart_contents['cart_total'] = 0; $this->_cart_contents['total_items'] = 0; } log_message('debug', "Cart Class Initialized"); } // -------------------------------------------------------------------- /** * Insert items into the cart and save it to the session table * * @access public * @param array * @return bool */ function insert($items = array()) { // Was any cart data passed? No? Bah... if ( ! is_array($items) OR count($items) == 0) { log_message('error', 'The insert method must be passed an array containing data.'); return FALSE; } // You can either insert a single product using a one-dimensional array, // or multiple products using a multi-dimensional one. The way we // determine the array type is by looking for a required array key named "id" // at the top level. If it's not found, we will assume it's a multi-dimensional array. $save_cart = FALSE; if (isset($items['id'])) { if (($rowid = $this->_insert($items))) { $save_cart = TRUE; } } else { foreach ($items as $val) { if (is_array($val) AND isset($val['id'])) { if ($this->_insert($val)) { $save_cart = TRUE; } } } } // Save the cart data if the insert was successful if ($save_cart == TRUE) { $this->_save_cart(); return isset($rowid) ? $rowid : TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Insert * * @access private * @param array * @return bool */ function _insert($items = array()) { // Was any cart data passed? No? Bah... if ( ! is_array($items) OR count($items) == 0) { log_message('error', 'The insert method must be passed an array containing data.'); return FALSE; } // -------------------------------------------------------------------- // Does the $items array contain an id, quantity, price, and name? These are required if ( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name'])) { log_message('error', 'The cart array must contain a product ID, quantity, price, and name.'); return FALSE; } // -------------------------------------------------------------------- // Prep the quantity. It can only be a number. Duh... $items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty'])); // Trim any leading zeros $items['qty'] = trim(preg_replace('/(^[0]+)/i', '', $items['qty'])); // If the quantity is zero or blank there's nothing for us to do if ( ! is_numeric($items['qty']) OR $items['qty'] == 0) { return FALSE; } // -------------------------------------------------------------------- // Validate the product ID. It can only be alpha-numeric, dashes, underscores or periods // Not totally sure we should impose this rule, but it seems prudent to standardize IDs. // Note: These can be user-specified by setting the $this->product_id_rules variable. if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items['id'])) { log_message('error', 'Invalid product ID. The product ID can only contain alpha-numeric characters, dashes, and underscores'); return FALSE; } // -------------------------------------------------------------------- // Validate the product name. It can only be alpha-numeric, dashes, underscores, colons or periods. // Note: These can be user-specified by setting the $this->product_name_rules variable. if ( ! preg_match("/^[".$this->product_name_rules."]+$/i", $items['name'])) { log_message('error', 'An invalid name was submitted as the product name: '.$items['name'].' The name can only contain alpha-numeric characters, dashes, underscores, colons, and spaces'); return FALSE; } // -------------------------------------------------------------------- // Prep the price. Remove anything that isn't a number or decimal point. $items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price'])); // Trim any leading zeros $items['price'] = trim(preg_replace('/(^[0]+)/i', '', $items['price'])); // Is the price a valid number? if ( ! is_numeric($items['price'])) { log_message('error', 'An invalid price was submitted for product ID: '.$items['id']); return FALSE; } // -------------------------------------------------------------------- // We now need to create a unique identifier for the item being inserted into the cart. // Every time something is added to the cart it is stored in the master cart array. // Each row in the cart array, however, must have a unique index that identifies not only // a particular product, but makes it possible to store identical products with different options. // For example, what if someone buys two identical t-shirts (same product ID), but in // different sizes? The product ID (and other attributes, like the name) will be identical for // both sizes because it's the same shirt. The only difference will be the size. // Internally, we need to treat identical submissions, but with different options, as a unique product. // Our solution is to convert the options array to a string and MD5 it along with the product ID. // This becomes the unique "row ID" if (isset($items['options']) AND count($items['options']) > 0) { $rowid = md5($items['id'].implode('', $items['options'])); } else { // No options were submitted so we simply MD5 the product ID. // Technically, we don't need to MD5 the ID in this case, but it makes // sense to standardize the format of array indexes for both conditions $rowid = md5($items['id']); } // -------------------------------------------------------------------- // Now that we have our unique "row ID", we'll add our cart items to the master array // let's unset this first, just to make sure our index contains only the data from this submission unset($this->_cart_contents[$rowid]); // Create a new index with our new row ID $this->_cart_contents[$rowid]['rowid'] = $rowid; // And add the new items to the cart array foreach ($items as $key => $val) { $this->_cart_contents[$rowid][$key] = $val; } // Woot! return $rowid; } // -------------------------------------------------------------------- /** * Update the cart * * This function permits the quantity of a given item to be changed. * Typically it is called from the "view cart" page if a user makes * changes to the quantity before checkout. That array must contain the * product ID and quantity for each item. * * @access public * @param array * @param string * @return bool */ function update($items = array()) { // Was any cart data passed? if ( ! is_array($items) OR count($items) == 0) { return FALSE; } // You can either update a single product using a one-dimensional array, // or multiple products using a multi-dimensional one. The way we // determine the array type is by looking for a required array key named "id". // If it's not found we assume it's a multi-dimensional array $save_cart = FALSE; if (isset($items['rowid']) AND isset($items['qty'])) { if ($this->_update($items) == TRUE) { $save_cart = TRUE; } } else { foreach ($items as $val) { if (is_array($val) AND isset($val['rowid']) AND isset($val['qty'])) { if ($this->_update($val) == TRUE) { $save_cart = TRUE; } } } } // Save the cart data if the insert was successful if ($save_cart == TRUE) { $this->_save_cart(); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Update the cart * * This function permits the quantity of a given item to be changed. * Typically it is called from the "view cart" page if a user makes * changes to the quantity before checkout. That array must contain the * product ID and quantity for each item. * * @access private * @param array * @return bool */ function _update($items = array()) { // Without these array indexes there is nothing we can do if ( ! isset($items['qty']) OR ! isset($items['rowid']) OR ! isset($this->_cart_contents[$items['rowid']])) { return FALSE; } // Prep the quantity $items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']); // Is the quantity a number? if ( ! is_numeric($items['qty'])) { return FALSE; } // Is the new quantity different than what is already saved in the cart? // If it's the same there's nothing to do if ($this->_cart_contents[$items['rowid']]['qty'] == $items['qty']) { return FALSE; } // Is the quantity zero? If so we will remove the item from the cart. // If the quantity is greater than zero we are updating if ($items['qty'] == 0) { unset($this->_cart_contents[$items['rowid']]); } else { $this->_cart_contents[$items['rowid']]['qty'] = $items['qty']; } return TRUE; } // -------------------------------------------------------------------- /** * Save the cart array to the session DB * * @access private * @return bool */ function _save_cart() { // Unset these so our total can be calculated correctly below unset($this->_cart_contents['total_items']); unset($this->_cart_contents['cart_total']); // Lets add up the individual prices and set the cart sub-total $total = 0; $items = 0; foreach ($this->_cart_contents as $key => $val) { // We make sure the array contains the proper indexes if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty'])) { continue; } $total += ($val['price'] * $val['qty']); $items += $val['qty']; // Set the subtotal $this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']); } // Set the cart total and total items. $this->_cart_contents['total_items'] = $items; $this->_cart_contents['cart_total'] = $total; // Is our cart empty? If so we delete it from the session if (count($this->_cart_contents) <= 2) { $this->CI->session->unset_userdata('cart_contents'); // Nothing more to do... coffee time! return FALSE; } // If we made it this far it means that our cart has data. // Let's pass it to the Session class so it can be stored $this->CI->session->set_userdata(array('cart_contents' => $this->_cart_contents)); // Woot! return TRUE; } // -------------------------------------------------------------------- /** * Cart Total * * @access public * @return integer */ function total() { return $this->_cart_contents['cart_total']; } // -------------------------------------------------------------------- /** * Total Items * * Returns the total item count * * @access public * @return integer */ function total_items() { return $this->_cart_contents['total_items']; } // -------------------------------------------------------------------- /** * Cart Contents * * Returns the entire cart array * * @access public * @return array */ function contents() { $cart = $this->_cart_contents; // Remove these so they don't create a problem when showing the cart table unset($cart['total_items']); unset($cart['cart_total']); return $cart; } // -------------------------------------------------------------------- /** * Has options * * Returns TRUE if the rowid passed to this function correlates to an item * that has options associated with it. * * @access public * @return array */ function has_options($rowid = '') { if ( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0) { return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Product options * * Returns the an array of options, for a particular product row ID * * @access public * @return array */ function product_options($rowid = '') { if ( ! isset($this->_cart_contents[$rowid]['options'])) { return array(); } return $this->_cart_contents[$rowid]['options']; } // -------------------------------------------------------------------- /** * Format Number * * Returns the supplied number with commas and a decimal point. * * @access public * @return integer */ function format_number($n = '') { if ($n == '') { return ''; } // Remove anything that isn't a number or decimal point. $n = trim(preg_replace('/([^0-9\.])/i', '', $n)); return number_format($n, 2, '.', ','); } // -------------------------------------------------------------------- /** * Destroy the cart * * Empties the cart and kills the session * * @access public * @return null */ function destroy() { unset($this->_cart_contents); $this->_cart_contents['cart_total'] = 0; $this->_cart_contents['total_items'] = 0; $this->CI->session->unset_userdata('cart_contents'); } } // END Cart Class /* End of file Cart.php */ /* Location: ./system/libraries/Cart.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Profiler.php
system/libraries/Profiler.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Profiler Class * * This class enables you to display benchmark, query, and other data * in order to help with debugging and optimization. * * Note: At some point it would be good to move all the HTML in this class * into a set of template files in order to allow customization. * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/general/profiling.html */ class CI_Profiler { protected $_available_sections = array( 'benchmarks', 'get', 'memory_usage', 'post', 'uri_string', 'controller_info', 'queries', 'http_headers', 'session_data', 'config' ); protected $_query_toggle_count = 25; protected $CI; // -------------------------------------------------------------------- public function __construct($config = array()) { $this->CI =& get_instance(); $this->CI->load->language('profiler'); if (isset($config['query_toggle_count'])) { $this->_query_toggle_count = (int) $config['query_toggle_count']; unset($config['query_toggle_count']); } // default all sections to display foreach ($this->_available_sections as $section) { if ( ! isset($config[$section])) { $this->_compile_{$section} = TRUE; } } $this->set_sections($config); } // -------------------------------------------------------------------- /** * Set Sections * * Sets the private _compile_* properties to enable/disable Profiler sections * * @param mixed * @return void */ public function set_sections($config) { foreach ($config as $method => $enable) { if (in_array($method, $this->_available_sections)) { $this->_compile_{$method} = ($enable !== FALSE) ? TRUE : FALSE; } } } // -------------------------------------------------------------------- /** * Auto Profiler * * This function cycles through the entire array of mark points and * matches any two points that are named identically (ending in "_start" * and "_end" respectively). It then compiles the execution times for * all points and returns it as an array * * @return array */ protected function _compile_benchmarks() { $profile = array(); foreach ($this->CI->benchmark->marker as $key => $val) { // We match the "end" marker so that the list ends // up in the order that it was defined if (preg_match("/(.+?)_end/i", $key, $match)) { if (isset($this->CI->benchmark->marker[$match[1].'_end']) AND isset($this->CI->benchmark->marker[$match[1].'_start'])) { $profile[$match[1]] = $this->CI->benchmark->elapsed_time($match[1].'_start', $key); } } } // Build a table containing the profile data. // Note: At some point we should turn this into a template that can // be modified. We also might want to make this data available to be logged $output = "\n\n"; $output .= '<fieldset id="ci_profiler_benchmarks" style="border:1px solid #900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#900;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_benchmarks').'&nbsp;&nbsp;</legend>'; $output .= "\n"; $output .= "\n\n<table style='width:100%'>\n"; foreach ($profile as $key => $val) { $key = ucwords(str_replace(array('_', '-'), ' ', $key)); $output .= "<tr><td style='padding:5px;width:50%;color:#000;font-weight:bold;background-color:#ddd;'>".$key."&nbsp;&nbsp;</td><td style='padding:5px;width:50%;color:#900;font-weight:normal;background-color:#ddd;'>".$val."</td></tr>\n"; } $output .= "</table>\n"; $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Compile Queries * * @return string */ protected function _compile_queries() { $dbs = array(); // Let's determine which databases are currently connected to foreach (get_object_vars($this->CI) as $CI_object) { if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB') ) { $dbs[] = $CI_object; } } if (count($dbs) == 0) { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_queries" style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#0000FF;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_queries').'&nbsp;&nbsp;</legend>'; $output .= "\n"; $output .= "\n\n<table style='border:none; width:100%;'>\n"; $output .="<tr><td style='width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px'>".$this->CI->lang->line('profiler_no_db')."</td></tr>\n"; $output .= "</table>\n"; $output .= "</fieldset>"; return $output; } // Load the text helper so we can highlight the SQL $this->CI->load->helper('text'); // Key words we want bolded $highlight = array('SELECT', 'DISTINCT', 'FROM', 'WHERE', 'AND', 'LEFT&nbsp;JOIN', 'ORDER&nbsp;BY', 'GROUP&nbsp;BY', 'LIMIT', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'OR&nbsp;', 'HAVING', 'OFFSET', 'NOT&nbsp;IN', 'IN', 'LIKE', 'NOT&nbsp;LIKE', 'COUNT', 'MAX', 'MIN', 'ON', 'AS', 'AVG', 'SUM', '(', ')'); $output = "\n\n"; $count = 0; foreach ($dbs as $db) { $count++; $hide_queries = (count($db->queries) > $this->_query_toggle_count) ? ' display:none' : ''; $show_hide_js = '(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_queries_db_'.$count.'\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_hide').'\'?\''.$this->CI->lang->line('profiler_section_show').'\':\''.$this->CI->lang->line('profiler_section_hide').'\';">'.$this->CI->lang->line('profiler_section_hide').'</span>)'; if ($hide_queries != '') { $show_hide_js = '(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_queries_db_'.$count.'\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)'; } $output .= '<fieldset style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#0000FF;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_database').':&nbsp; '.$db->database.'&nbsp;&nbsp;&nbsp;'.$this->CI->lang->line('profiler_queries').': '.count($db->queries).'&nbsp;&nbsp;'.$show_hide_js.'</legend>'; $output .= "\n"; $output .= "\n\n<table style='width:100%;{$hide_queries}' id='ci_profiler_queries_db_{$count}'>\n"; if (count($db->queries) == 0) { $output .= "<tr><td style='width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;'>".$this->CI->lang->line('profiler_no_queries')."</td></tr>\n"; } else { foreach ($db->queries as $key => $val) { $time = number_format($db->query_times[$key], 4); $val = highlight_code($val, ENT_QUOTES); foreach ($highlight as $bold) { $val = str_replace($bold, '<strong>'.$bold.'</strong>', $val); } $output .= "<tr><td style='padding:5px; vertical-align: top;width:1%;color:#900;font-weight:normal;background-color:#ddd;'>".$time."&nbsp;&nbsp;</td><td style='padding:5px; color:#000;font-weight:normal;background-color:#ddd;'>".$val."</td></tr>\n"; } } $output .= "</table>\n"; $output .= "</fieldset>"; } return $output; } // -------------------------------------------------------------------- /** * Compile $_GET Data * * @return string */ protected function _compile_get() { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_get" style="border:1px solid #cd6e00;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#cd6e00;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_get_data').'&nbsp;&nbsp;</legend>'; $output .= "\n"; if (count($_GET) == 0) { $output .= "<div style='color:#cd6e00;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_get')."</div>"; } else { $output .= "\n\n<table style='width:100%; border:none'>\n"; foreach ($_GET as $key => $val) { if ( ! is_numeric($key)) { $key = "'".$key."'"; } $output .= "<tr><td style='width:50%;color:#000;background-color:#ddd;padding:5px'>&#36;_GET[".$key."]&nbsp;&nbsp; </td><td style='width:50%;padding:5px;color:#cd6e00;font-weight:normal;background-color:#ddd;'>"; if (is_array($val)) { $output .= "<pre>" . htmlspecialchars(stripslashes(print_r($val, true))) . "</pre>"; } else { $output .= htmlspecialchars(stripslashes($val)); } $output .= "</td></tr>\n"; } $output .= "</table>\n"; } $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Compile $_POST Data * * @return string */ protected function _compile_post() { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_post" style="border:1px solid #009900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#009900;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_post_data').'&nbsp;&nbsp;</legend>'; $output .= "\n"; if (count($_POST) == 0) { $output .= "<div style='color:#009900;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_post')."</div>"; } else { $output .= "\n\n<table style='width:100%'>\n"; foreach ($_POST as $key => $val) { if ( ! is_numeric($key)) { $key = "'".$key."'"; } $output .= "<tr><td style='width:50%;padding:5px;color:#000;background-color:#ddd;'>&#36;_POST[".$key."]&nbsp;&nbsp; </td><td style='width:50%;padding:5px;color:#009900;font-weight:normal;background-color:#ddd;'>"; if (is_array($val)) { $output .= "<pre>" . htmlspecialchars(stripslashes(print_r($val, TRUE))) . "</pre>"; } else { $output .= htmlspecialchars(stripslashes($val)); } $output .= "</td></tr>\n"; } $output .= "</table>\n"; } $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Show query string * * @return string */ protected function _compile_uri_string() { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_uri_string" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_uri_string').'&nbsp;&nbsp;</legend>'; $output .= "\n"; if ($this->CI->uri->uri_string == '') { $output .= "<div style='color:#000;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_uri')."</div>"; } else { $output .= "<div style='color:#000;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->uri->uri_string."</div>"; } $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Show the controller and function that were called * * @return string */ protected function _compile_controller_info() { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_controller_info" style="border:1px solid #995300;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#995300;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_controller_info').'&nbsp;&nbsp;</legend>'; $output .= "\n"; $output .= "<div style='color:#995300;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->router->fetch_class()."/".$this->CI->router->fetch_method()."</div>"; $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Compile memory usage * * Display total used memory * * @return string */ protected function _compile_memory_usage() { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_memory_usage" style="border:1px solid #5a0099;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#5a0099;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_memory_usage').'&nbsp;&nbsp;</legend>'; $output .= "\n"; if (function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '') { $output .= "<div style='color:#5a0099;font-weight:normal;padding:4px 0 4px 0'>".number_format($usage).' bytes</div>'; } else { $output .= "<div style='color:#5a0099;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_memory')."</div>"; } $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Compile header information * * Lists HTTP headers * * @return string */ protected function _compile_http_headers() { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_http_headers" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_headers').'&nbsp;&nbsp;(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_httpheaders_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>'; $output .= "\n"; $output .= "\n\n<table style='width:100%;display:none' id='ci_profiler_httpheaders_table'>\n"; foreach (array('HTTP_ACCEPT', 'HTTP_USER_AGENT', 'HTTP_CONNECTION', 'SERVER_PORT', 'SERVER_NAME', 'REMOTE_ADDR', 'SERVER_SOFTWARE', 'HTTP_ACCEPT_LANGUAGE', 'SCRIPT_NAME', 'REQUEST_METHOD',' HTTP_HOST', 'REMOTE_HOST', 'CONTENT_TYPE', 'SERVER_PROTOCOL', 'QUERY_STRING', 'HTTP_ACCEPT_ENCODING', 'HTTP_X_FORWARDED_FOR') as $header) { $val = (isset($_SERVER[$header])) ? $_SERVER[$header] : ''; $output .= "<tr><td style='vertical-align: top;width:50%;padding:5px;color:#900;background-color:#ddd;'>".$header."&nbsp;&nbsp;</td><td style='width:50%;padding:5px;color:#000;background-color:#ddd;'>".$val."</td></tr>\n"; } $output .= "</table>\n"; $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Compile config information * * Lists developer config variables * * @return string */ protected function _compile_config() { $output = "\n\n"; $output .= '<fieldset id="ci_profiler_config" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= "\n"; $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_config').'&nbsp;&nbsp;(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_config_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>'; $output .= "\n"; $output .= "\n\n<table style='width:100%; display:none' id='ci_profiler_config_table'>\n"; foreach ($this->CI->config->config as $config=>$val) { if (is_array($val)) { $val = print_r($val, TRUE); } $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$config."&nbsp;&nbsp;</td><td style='padding:5px; color:#000;background-color:#ddd;'>".htmlspecialchars($val)."</td></tr>\n"; } $output .= "</table>\n"; $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Compile session userdata * * @return string */ private function _compile_session_data() { if ( ! isset($this->CI->session)) { return; } $output = '<fieldset id="ci_profiler_csession" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">'; $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_session_data').'&nbsp;&nbsp;(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_session_data\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>'; $output .= "<table style='width:100%;display:none' id='ci_profiler_session_data'>"; foreach ($this->CI->session->all_userdata() as $key => $val) { if (is_array($val) OR is_object($val)) { $val = print_r($val, TRUE); } $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$key."&nbsp;&nbsp;</td><td style='padding:5px; color:#000;background-color:#ddd;'>".htmlspecialchars($val)."</td></tr>\n"; } $output .= '</table>'; $output .= "</fieldset>"; return $output; } // -------------------------------------------------------------------- /** * Run the Profiler * * @return string */ public function run() { $output = "<div id='codeigniter_profiler' style='clear:both;background-color:#fff;padding:10px;'>"; $fields_displayed = 0; foreach ($this->_available_sections as $section) { if ($this->_compile_{$section} !== FALSE) { $func = "_compile_{$section}"; $output .= $this->{$func}(); $fields_displayed++; } } if ($fields_displayed == 0) { $output .= '<p style="border:1px solid #5a0099;padding:10px;margin:20px 0;background-color:#eee">'.$this->CI->lang->line('profiler_no_profiles').'</p>'; } $output .= '</div>'; return $output; } } // END CI_Profiler class /* End of file Profiler.php */ /* Location: ./system/libraries/Profiler.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Session.php
system/libraries/Session.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Session Class * * @package CodeIgniter * @subpackage Libraries * @category Sessions * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/sessions.html */ class CI_Session { var $sess_encrypt_cookie = FALSE; var $sess_use_database = FALSE; var $sess_table_name = ''; var $sess_expiration = 7200; var $sess_expire_on_close = FALSE; var $sess_match_ip = FALSE; var $sess_match_useragent = TRUE; var $sess_cookie_name = 'ci_session'; var $cookie_prefix = ''; var $cookie_path = ''; var $cookie_domain = ''; var $cookie_secure = FALSE; var $sess_time_to_update = 300; var $encryption_key = ''; var $flashdata_key = 'flash'; var $time_reference = 'time'; var $gc_probability = 5; var $userdata = array(); var $CI; var $now; /** * Session Constructor * * The constructor runs the session routines automatically * whenever the class is instantiated. */ public function __construct($params = array()) { log_message('debug', "Session Class Initialized"); // Set the super object to a local variable for use throughout the class $this->CI =& get_instance(); // Set all the session preferences, which can either be set // manually via the $params array above or via the config file foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration', 'sess_expire_on_close', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path', 'cookie_domain', 'cookie_secure', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key') as $key) { $this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key); } if ($this->encryption_key == '') { show_error('In order to use the Session class you are required to set an encryption key in your config file.'); } // Load the string helper so we can use the strip_slashes() function $this->CI->load->helper('string'); // Do we need encryption? If so, load the encryption class if ($this->sess_encrypt_cookie == TRUE) { $this->CI->load->library('encrypt'); } // Are we using a database? If so, load it if ($this->sess_use_database === TRUE AND $this->sess_table_name != '') { $this->CI->load->database(); } // Set the "now" time. Can either be GMT or server time, based on the // config prefs. We use this to set the "last activity" time $this->now = $this->_get_time(); // Set the session length. If the session expiration is // set to zero we'll set the expiration two years from now. if ($this->sess_expiration == 0) { $this->sess_expiration = (60*60*24*365*2); } // Set the cookie name $this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name; // Run the Session routine. If a session doesn't exist we'll // create a new one. If it does, we'll update it. if ( ! $this->sess_read()) { $this->sess_create(); } else { $this->sess_update(); } // Delete 'old' flashdata (from last request) $this->_flashdata_sweep(); // Mark all new flashdata as old (data will be deleted before next request) $this->_flashdata_mark(); // Delete expired sessions if necessary $this->_sess_gc(); log_message('debug', "Session routines successfully run"); } // -------------------------------------------------------------------- /** * Fetch the current session data if it exists * * @access public * @return bool */ function sess_read() { // Fetch the cookie $session = $this->CI->input->cookie($this->sess_cookie_name); // No cookie? Goodbye cruel world!... if ($session === FALSE) { log_message('debug', 'A session cookie was not found.'); return FALSE; } // Decrypt the cookie data if ($this->sess_encrypt_cookie == TRUE) { $session = $this->CI->encrypt->decode($session); } else { // encryption was not used, so we need to check the md5 hash $hash = substr($session, strlen($session)-32); // get last 32 chars $session = substr($session, 0, strlen($session)-32); // Does the md5 hash match? This is to prevent manipulation of session data in userspace if ($hash !== md5($session.$this->encryption_key)) { log_message('error', 'The session cookie data did not match what was expected. This could be a possible hacking attempt.'); $this->sess_destroy(); return FALSE; } } // Unserialize the session array $session = $this->_unserialize($session); // Is the session data we unserialized an array with the correct format? if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity'])) { $this->sess_destroy(); return FALSE; } // Is the session current? if (($session['last_activity'] + $this->sess_expiration) < $this->now) { $this->sess_destroy(); return FALSE; } // Does the IP Match? if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address()) { $this->sess_destroy(); return FALSE; } // Does the User Agent Match? if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 120))) { $this->sess_destroy(); return FALSE; } // Is there a corresponding session in the DB? if ($this->sess_use_database === TRUE) { $this->CI->db->where('session_id', $session['session_id']); if ($this->sess_match_ip == TRUE) { $this->CI->db->where('ip_address', $session['ip_address']); } if ($this->sess_match_useragent == TRUE) { $this->CI->db->where('user_agent', $session['user_agent']); } $query = $this->CI->db->get($this->sess_table_name); // No result? Kill it! if ($query->num_rows() == 0) { $this->sess_destroy(); return FALSE; } // Is there custom data? If so, add it to the main session array $row = $query->row(); if (isset($row->user_data) AND $row->user_data != '') { $custom_data = $this->_unserialize($row->user_data); if (is_array($custom_data)) { foreach ($custom_data as $key => $val) { $session[$key] = $val; } } } } // Session is valid! $this->userdata = $session; unset($session); return TRUE; } // -------------------------------------------------------------------- /** * Write the session data * * @access public * @return void */ function sess_write() { // Are we saving custom data to the DB? If not, all we do is update the cookie if ($this->sess_use_database === FALSE) { $this->_set_cookie(); return; } // set the custom userdata, the session data we will set in a second $custom_userdata = $this->userdata; $cookie_userdata = array(); // Before continuing, we need to determine if there is any custom data to deal with. // Let's determine this by removing the default indexes to see if there's anything left in the array // and set the session data while we're at it foreach (array('session_id','ip_address','user_agent','last_activity') as $val) { unset($custom_userdata[$val]); $cookie_userdata[$val] = $this->userdata[$val]; } // Did we find any custom data? If not, we turn the empty array into a string // since there's no reason to serialize and store an empty array in the DB if (count($custom_userdata) === 0) { $custom_userdata = ''; } else { // Serialize the custom data array so we can store it $custom_userdata = $this->_serialize($custom_userdata); } // Run the update query $this->CI->db->where('session_id', $this->userdata['session_id']); $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata)); // Write the cookie. Notice that we manually pass the cookie data array to the // _set_cookie() function. Normally that function will store $this->userdata, but // in this case that array contains custom data, which we do not want in the cookie. $this->_set_cookie($cookie_userdata); } // -------------------------------------------------------------------- /** * Create a new session * * @access public * @return void */ function sess_create() { $sessid = ''; while (strlen($sessid) < 32) { $sessid .= mt_rand(0, mt_getrandmax()); } // To make the session ID even more secure we'll combine it with the user's IP $sessid .= $this->CI->input->ip_address(); $this->userdata = array( 'session_id' => md5(uniqid($sessid, TRUE)), 'ip_address' => $this->CI->input->ip_address(), 'user_agent' => substr($this->CI->input->user_agent(), 0, 120), 'last_activity' => $this->now, 'user_data' => '' ); // Save the data to the DB if needed if ($this->sess_use_database === TRUE) { $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata)); } // Write the cookie $this->_set_cookie(); } // -------------------------------------------------------------------- /** * Update an existing session * * @access public * @return void */ function sess_update() { // We only update the session every five minutes by default if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now) { return; } // Save the old session id so we know which record to // update in the database if we need it $old_sessid = $this->userdata['session_id']; $new_sessid = ''; while (strlen($new_sessid) < 32) { $new_sessid .= mt_rand(0, mt_getrandmax()); } // To make the session ID even more secure we'll combine it with the user's IP $new_sessid .= $this->CI->input->ip_address(); // Turn it into a hash $new_sessid = md5(uniqid($new_sessid, TRUE)); // Update the session data in the session data array $this->userdata['session_id'] = $new_sessid; $this->userdata['last_activity'] = $this->now; // _set_cookie() will handle this for us if we aren't using database sessions // by pushing all userdata to the cookie. $cookie_data = NULL; // Update the session ID and last_activity field in the DB if needed if ($this->sess_use_database === TRUE) { // set cookie explicitly to only have our session data $cookie_data = array(); foreach (array('session_id','ip_address','user_agent','last_activity') as $val) { $cookie_data[$val] = $this->userdata[$val]; } $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid))); } // Write the cookie $this->_set_cookie($cookie_data); } // -------------------------------------------------------------------- /** * Destroy the current session * * @access public * @return void */ function sess_destroy() { // Kill the session DB row if ($this->sess_use_database === TRUE && isset($this->userdata['session_id'])) { $this->CI->db->where('session_id', $this->userdata['session_id']); $this->CI->db->delete($this->sess_table_name); } // Kill the cookie setcookie( $this->sess_cookie_name, addslashes(serialize(array())), ($this->now - 31500000), $this->cookie_path, $this->cookie_domain, 0 ); // Kill session data $this->userdata = array(); } // -------------------------------------------------------------------- /** * Fetch a specific item from the session array * * @access public * @param string * @return string */ function userdata($item) { return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item]; } // -------------------------------------------------------------------- /** * Fetch all session data * * @access public * @return array */ function all_userdata() { return $this->userdata; } // -------------------------------------------------------------------- /** * Add or change data in the "userdata" array * * @access public * @param mixed * @param string * @return void */ function set_userdata($newdata = array(), $newval = '') { if (is_string($newdata)) { $newdata = array($newdata => $newval); } if (count($newdata) > 0) { foreach ($newdata as $key => $val) { $this->userdata[$key] = $val; } } $this->sess_write(); } // -------------------------------------------------------------------- /** * Delete a session variable from the "userdata" array * * @access array * @return void */ function unset_userdata($newdata = array()) { if (is_string($newdata)) { $newdata = array($newdata => ''); } if (count($newdata) > 0) { foreach ($newdata as $key => $val) { unset($this->userdata[$key]); } } $this->sess_write(); } // ------------------------------------------------------------------------ /** * Add or change flashdata, only available * until the next request * * @access public * @param mixed * @param string * @return void */ function set_flashdata($newdata = array(), $newval = '') { if (is_string($newdata)) { $newdata = array($newdata => $newval); } if (count($newdata) > 0) { foreach ($newdata as $key => $val) { $flashdata_key = $this->flashdata_key.':new:'.$key; $this->set_userdata($flashdata_key, $val); } } } // ------------------------------------------------------------------------ /** * Keeps existing flashdata available to next request. * * @access public * @param string * @return void */ function keep_flashdata($key) { // 'old' flashdata gets removed. Here we mark all // flashdata as 'new' to preserve it from _flashdata_sweep() // Note the function will return FALSE if the $key // provided cannot be found $old_flashdata_key = $this->flashdata_key.':old:'.$key; $value = $this->userdata($old_flashdata_key); $new_flashdata_key = $this->flashdata_key.':new:'.$key; $this->set_userdata($new_flashdata_key, $value); } // ------------------------------------------------------------------------ /** * Fetch a specific flashdata item from the session array * * @access public * @param string * @return string */ function flashdata($key) { $flashdata_key = $this->flashdata_key.':old:'.$key; return $this->userdata($flashdata_key); } // ------------------------------------------------------------------------ /** * Identifies flashdata as 'old' for removal * when _flashdata_sweep() runs. * * @access private * @return void */ function _flashdata_mark() { $userdata = $this->all_userdata(); foreach ($userdata as $name => $value) { $parts = explode(':new:', $name); if (is_array($parts) && count($parts) === 2) { $new_name = $this->flashdata_key.':old:'.$parts[1]; $this->set_userdata($new_name, $value); $this->unset_userdata($name); } } } // ------------------------------------------------------------------------ /** * Removes all flashdata marked as 'old' * * @access private * @return void */ function _flashdata_sweep() { $userdata = $this->all_userdata(); foreach ($userdata as $key => $value) { if (strpos($key, ':old:')) { $this->unset_userdata($key); } } } // -------------------------------------------------------------------- /** * Get the "now" time * * @access private * @return string */ function _get_time() { if (strtolower($this->time_reference) == 'gmt') { $now = time(); $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now)); } else { $time = time(); } return $time; } // -------------------------------------------------------------------- /** * Write the session cookie * * @access public * @return void */ function _set_cookie($cookie_data = NULL) { if (is_null($cookie_data)) { $cookie_data = $this->userdata; } // Serialize the userdata for the cookie $cookie_data = $this->_serialize($cookie_data); if ($this->sess_encrypt_cookie == TRUE) { $cookie_data = $this->CI->encrypt->encode($cookie_data); } else { // if encryption is not used, we provide an md5 hash to prevent userside tampering $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key); } $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time(); // Set the cookie setcookie( $this->sess_cookie_name, $cookie_data, $expire, $this->cookie_path, $this->cookie_domain, $this->cookie_secure ); } // -------------------------------------------------------------------- /** * Serialize an array * * This function first converts any slashes found in the array to a temporary * marker, so when it gets unserialized the slashes will be preserved * * @access private * @param array * @return string */ function _serialize($data) { if (is_array($data)) { foreach ($data as $key => $val) { if (is_string($val)) { $data[$key] = str_replace('\\', '{{slash}}', $val); } } } else { if (is_string($data)) { $data = str_replace('\\', '{{slash}}', $data); } } return serialize($data); } // -------------------------------------------------------------------- /** * Unserialize * * This function unserializes a data string, then converts any * temporary slash markers back to actual slashes * * @access private * @param array * @return string */ function _unserialize($data) { $data = @unserialize(strip_slashes($data)); if (is_array($data)) { foreach ($data as $key => $val) { if (is_string($val)) { $data[$key] = str_replace('{{slash}}', '\\', $val); } } return $data; } return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data; } // -------------------------------------------------------------------- /** * Garbage collection * * This deletes expired session rows from database * if the probability percentage is met * * @access public * @return void */ function _sess_gc() { if ($this->sess_use_database != TRUE) { return; } srand(time()); if ((rand() % 100) < $this->gc_probability) { $expire = $this->now - $this->sess_expiration; $this->CI->db->where("last_activity < {$expire}"); $this->CI->db->delete($this->sess_table_name); log_message('debug', 'Session garbage collection performed.'); } } } // END Session Class /* End of file Session.php */ /* Location: ./system/libraries/Session.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Unit_test.php
system/libraries/Unit_test.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.3.1 * @filesource */ // ------------------------------------------------------------------------ /** * Unit Testing Class * * Simple testing class * * @package CodeIgniter * @subpackage Libraries * @category UnitTesting * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/uri.html */ class CI_Unit_test { var $active = TRUE; var $results = array(); var $strict = FALSE; var $_template = NULL; var $_template_rows = NULL; var $_test_items_visible = array(); public function __construct() { // These are the default items visible when a test is run. $this->_test_items_visible = array ( 'test_name', 'test_datatype', 'res_datatype', 'result', 'file', 'line', 'notes' ); log_message('debug', "Unit Testing Class Initialized"); } // -------------------------------------------------------------------- /** * Run the tests * * Runs the supplied tests * * @access public * @param array * @return void */ function set_test_items($items = array()) { if ( ! empty($items) AND is_array($items)) { $this->_test_items_visible = $items; } } // -------------------------------------------------------------------- /** * Run the tests * * Runs the supplied tests * * @access public * @param mixed * @param mixed * @param string * @return string */ function run($test, $expected = TRUE, $test_name = 'undefined', $notes = '') { if ($this->active == FALSE) { return FALSE; } if (in_array($expected, array('is_object', 'is_string', 'is_bool', 'is_true', 'is_false', 'is_int', 'is_numeric', 'is_float', 'is_double', 'is_array', 'is_null'), TRUE)) { $expected = str_replace('is_float', 'is_double', $expected); $result = ($expected($test)) ? TRUE : FALSE; $extype = str_replace(array('true', 'false'), 'bool', str_replace('is_', '', $expected)); } else { if ($this->strict == TRUE) $result = ($test === $expected) ? TRUE : FALSE; else $result = ($test == $expected) ? TRUE : FALSE; $extype = gettype($expected); } $back = $this->_backtrace(); $report[] = array ( 'test_name' => $test_name, 'test_datatype' => gettype($test), 'res_datatype' => $extype, 'result' => ($result === TRUE) ? 'passed' : 'failed', 'file' => $back['file'], 'line' => $back['line'], 'notes' => $notes ); $this->results[] = $report; return($this->report($this->result($report))); } // -------------------------------------------------------------------- /** * Generate a report * * Displays a table with the test data * * @access public * @return string */ function report($result = array()) { if (count($result) == 0) { $result = $this->result(); } $CI =& get_instance(); $CI->load->language('unit_test'); $this->_parse_template(); $r = ''; foreach ($result as $res) { $table = ''; foreach ($res as $key => $val) { if ($key == $CI->lang->line('ut_result')) { if ($val == $CI->lang->line('ut_passed')) { $val = '<span style="color: #0C0;">'.$val.'</span>'; } elseif ($val == $CI->lang->line('ut_failed')) { $val = '<span style="color: #C00;">'.$val.'</span>'; } } $temp = $this->_template_rows; $temp = str_replace('{item}', $key, $temp); $temp = str_replace('{result}', $val, $temp); $table .= $temp; } $r .= str_replace('{rows}', $table, $this->_template); } return $r; } // -------------------------------------------------------------------- /** * Use strict comparison * * Causes the evaluation to use === rather than == * * @access public * @param bool * @return null */ function use_strict($state = TRUE) { $this->strict = ($state == FALSE) ? FALSE : TRUE; } // -------------------------------------------------------------------- /** * Make Unit testing active * * Enables/disables unit testing * * @access public * @param bool * @return null */ function active($state = TRUE) { $this->active = ($state == FALSE) ? FALSE : TRUE; } // -------------------------------------------------------------------- /** * Result Array * * Returns the raw result data * * @access public * @return array */ function result($results = array()) { $CI =& get_instance(); $CI->load->language('unit_test'); if (count($results) == 0) { $results = $this->results; } $retval = array(); foreach ($results as $result) { $temp = array(); foreach ($result as $key => $val) { if ( ! in_array($key, $this->_test_items_visible)) { continue; } if (is_array($val)) { foreach ($val as $k => $v) { if (FALSE !== ($line = $CI->lang->line(strtolower('ut_'.$v)))) { $v = $line; } $temp[$CI->lang->line('ut_'.$k)] = $v; } } else { if (FALSE !== ($line = $CI->lang->line(strtolower('ut_'.$val)))) { $val = $line; } $temp[$CI->lang->line('ut_'.$key)] = $val; } } $retval[] = $temp; } return $retval; } // -------------------------------------------------------------------- /** * Set the template * * This lets us set the template to be used to display results * * @access public * @param string * @return void */ function set_template($template) { $this->_template = $template; } // -------------------------------------------------------------------- /** * Generate a backtrace * * This lets us show file names and line numbers * * @access private * @return array */ function _backtrace() { if (function_exists('debug_backtrace')) { $back = debug_backtrace(); $file = ( ! isset($back['1']['file'])) ? '' : $back['1']['file']; $line = ( ! isset($back['1']['line'])) ? '' : $back['1']['line']; return array('file' => $file, 'line' => $line); } return array('file' => 'Unknown', 'line' => 'Unknown'); } // -------------------------------------------------------------------- /** * Get Default Template * * @access private * @return string */ function _default_template() { $this->_template = "\n".'<table style="width:100%; font-size:small; margin:10px 0; border-collapse:collapse; border:1px solid #CCC;">'; $this->_template .= '{rows}'; $this->_template .= "\n".'</table>'; $this->_template_rows = "\n\t".'<tr>'; $this->_template_rows .= "\n\t\t".'<th style="text-align: left; border-bottom:1px solid #CCC;">{item}</th>'; $this->_template_rows .= "\n\t\t".'<td style="border-bottom:1px solid #CCC;">{result}</td>'; $this->_template_rows .= "\n\t".'</tr>'; } // -------------------------------------------------------------------- /** * Parse Template * * Harvests the data within the template {pseudo-variables} * * @access private * @return void */ function _parse_template() { if ( ! is_null($this->_template_rows)) { return; } if (is_null($this->_template)) { $this->_default_template(); return; } if ( ! preg_match("/\{rows\}(.*?)\{\/rows\}/si", $this->_template, $match)) { $this->_default_template(); return; } $this->_template_rows = $match['1']; $this->_template = str_replace($match['0'], '{rows}', $this->_template); } } // END Unit_test Class /** * Helper functions to test boolean true/false * * * @access private * @return bool */ function is_true($test) { return (is_bool($test) AND $test === TRUE) ? TRUE : FALSE; } function is_false($test) { return (is_bool($test) AND $test === FALSE) ? TRUE : FALSE; } /* End of file Unit_test.php */ /* Location: ./system/libraries/Unit_test.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Driver.php
system/libraries/Driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2006 - 2012, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Driver Library Class * * This class enables you to create "Driver" libraries that add runtime ability * to extend the capabilities of a class via additional driver objects * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author EllisLab Dev Team * @link */ class CI_Driver_Library { protected $valid_drivers = array(); protected $lib_name; // The first time a child is used it won't exist, so we instantiate it // subsequents calls will go straight to the proper child. function __get($child) { if ( ! isset($this->lib_name)) { $this->lib_name = get_class($this); } // The class will be prefixed with the parent lib $child_class = $this->lib_name.'_'.$child; // Remove the CI_ prefix and lowercase $lib_name = ucfirst(strtolower(str_replace('CI_', '', $this->lib_name))); $driver_name = strtolower(str_replace('CI_', '', $child_class)); if (in_array($driver_name, array_map('strtolower', $this->valid_drivers))) { // check and see if the driver is in a separate file if ( ! class_exists($child_class)) { // check application path first foreach (get_instance()->load->get_package_paths(TRUE) as $path) { // loves me some nesting! foreach (array(ucfirst($driver_name), $driver_name) as $class) { $filepath = $path.'libraries/'.$lib_name.'/drivers/'.$class.'.php'; if (file_exists($filepath)) { include_once $filepath; break; } } } // it's a valid driver, but the file simply can't be found if ( ! class_exists($child_class)) { log_message('error', "Unable to load the requested driver: ".$child_class); show_error("Unable to load the requested driver: ".$child_class); } } $obj = new $child_class; $obj->decorate($this); $this->$child = $obj; return $this->$child; } // The requested driver isn't valid! log_message('error', "Invalid driver requested: ".$child_class); show_error("Invalid driver requested: ".$child_class); } // -------------------------------------------------------------------- } // END CI_Driver_Library CLASS /** * CodeIgniter Driver Class * * This class enables you to create drivers for a Library based on the Driver Library. * It handles the drivers' access to the parent library * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author EllisLab Dev Team * @link */ class CI_Driver { protected $parent; private $methods = array(); private $properties = array(); private static $reflections = array(); /** * Decorate * * Decorates the child with the parent driver lib's methods and properties * * @param object * @return void */ public function decorate($parent) { $this->parent = $parent; // Lock down attributes to what is defined in the class // and speed up references in magic methods $class_name = get_class($parent); if ( ! isset(self::$reflections[$class_name])) { $r = new ReflectionObject($parent); foreach ($r->getMethods() as $method) { if ($method->isPublic()) { $this->methods[] = $method->getName(); } } foreach ($r->getProperties() as $prop) { if ($prop->isPublic()) { $this->properties[] = $prop->getName(); } } self::$reflections[$class_name] = array($this->methods, $this->properties); } else { list($this->methods, $this->properties) = self::$reflections[$class_name]; } } // -------------------------------------------------------------------- /** * __call magic method * * Handles access to the parent driver library's methods * * @access public * @param string * @param array * @return mixed */ public function __call($method, $args = array()) { if (in_array($method, $this->methods)) { return call_user_func_array(array($this->parent, $method), $args); } $trace = debug_backtrace(); _exception_handler(E_ERROR, "No such method '{$method}'", $trace[1]['file'], $trace[1]['line']); exit; } // -------------------------------------------------------------------- /** * __get magic method * * Handles reading of the parent driver library's properties * * @param string * @return mixed */ public function __get($var) { if (in_array($var, $this->properties)) { return $this->parent->$var; } } // -------------------------------------------------------------------- /** * __set magic method * * Handles writing to the parent driver library's properties * * @param string * @param array * @return mixed */ public function __set($var, $val) { if (in_array($var, $this->properties)) { $this->parent->$var = $val; } } // -------------------------------------------------------------------- } // END CI_Driver CLASS /* End of file Driver.php */ /* Location: ./system/libraries/Driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Image_lib.php
system/libraries/Image_lib.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Image Manipulation class * * @package CodeIgniter * @subpackage Libraries * @category Image_lib * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/image_lib.html */ class CI_Image_lib { var $image_library = 'gd2'; // Can be: imagemagick, netpbm, gd, gd2 var $library_path = ''; var $dynamic_output = FALSE; // Whether to send to browser or write to disk var $source_image = ''; var $new_image = ''; var $width = ''; var $height = ''; var $quality = '90'; var $create_thumb = FALSE; var $thumb_marker = '_thumb'; var $maintain_ratio = TRUE; // Whether to maintain aspect ratio when resizing or use hard values var $master_dim = 'auto'; // auto, height, or width. Determines what to use as the master dimension var $rotation_angle = ''; var $x_axis = ''; var $y_axis = ''; // Watermark Vars var $wm_text = ''; // Watermark text if graphic is not used var $wm_type = 'text'; // Type of watermarking. Options: text/overlay var $wm_x_transp = 4; var $wm_y_transp = 4; var $wm_overlay_path = ''; // Watermark image path var $wm_font_path = ''; // TT font var $wm_font_size = 17; // Font size (different versions of GD will either use points or pixels) var $wm_vrt_alignment = 'B'; // Vertical alignment: T M B var $wm_hor_alignment = 'C'; // Horizontal alignment: L R C var $wm_padding = 0; // Padding around text var $wm_hor_offset = 0; // Lets you push text to the right var $wm_vrt_offset = 0; // Lets you push text down var $wm_font_color = '#ffffff'; // Text color var $wm_shadow_color = ''; // Dropshadow color var $wm_shadow_distance = 2; // Dropshadow distance var $wm_opacity = 50; // Image opacity: 1 - 100 Only works with image // Private Vars var $source_folder = ''; var $dest_folder = ''; var $mime_type = ''; var $orig_width = ''; var $orig_height = ''; var $image_type = ''; var $size_str = ''; var $full_src_path = ''; var $full_dst_path = ''; var $create_fnc = 'imagecreatetruecolor'; var $copy_fnc = 'imagecopyresampled'; var $error_msg = array(); var $wm_use_drop_shadow = FALSE; var $wm_use_truetype = FALSE; /** * Constructor * * @param string * @return void */ public function __construct($props = array()) { if (count($props) > 0) { $this->initialize($props); } log_message('debug', "Image Lib Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize image properties * * Resets values in case this class is used in a loop * * @access public * @return void */ function clear() { $props = array('source_folder', 'dest_folder', 'source_image', 'full_src_path', 'full_dst_path', 'new_image', 'image_type', 'size_str', 'quality', 'orig_width', 'orig_height', 'width', 'height', 'rotation_angle', 'x_axis', 'y_axis', 'create_fnc', 'copy_fnc', 'wm_overlay_path', 'wm_use_truetype', 'dynamic_output', 'wm_font_size', 'wm_text', 'wm_vrt_alignment', 'wm_hor_alignment', 'wm_padding', 'wm_hor_offset', 'wm_vrt_offset', 'wm_font_color', 'wm_use_drop_shadow', 'wm_shadow_color', 'wm_shadow_distance', 'wm_opacity'); foreach ($props as $val) { $this->$val = ''; } // special consideration for master_dim $this->master_dim = 'auto'; } // -------------------------------------------------------------------- /** * initialize image preferences * * @access public * @param array * @return bool */ function initialize($props = array()) { /* * Convert array elements into class variables */ if (count($props) > 0) { foreach ($props as $key => $val) { $this->$key = $val; } } /* * Is there a source image? * * If not, there's no reason to continue * */ if ($this->source_image == '') { $this->set_error('imglib_source_image_required'); return FALSE; } /* * Is getimagesize() Available? * * We use it to determine the image properties (width/height). * Note: We need to figure out how to determine image * properties using ImageMagick and NetPBM * */ if ( ! function_exists('getimagesize')) { $this->set_error('imglib_gd_required_for_props'); return FALSE; } $this->image_library = strtolower($this->image_library); /* * Set the full server path * * The source image may or may not contain a path. * Either way, we'll try use realpath to generate the * full server path in order to more reliably read it. * */ if (function_exists('realpath') AND @realpath($this->source_image) !== FALSE) { $full_source_path = str_replace("\\", "/", realpath($this->source_image)); } else { $full_source_path = $this->source_image; } $x = explode('/', $full_source_path); $this->source_image = end($x); $this->source_folder = str_replace($this->source_image, '', $full_source_path); // Set the Image Properties if ( ! $this->get_image_properties($this->source_folder.$this->source_image)) { return FALSE; } /* * Assign the "new" image name/path * * If the user has set a "new_image" name it means * we are making a copy of the source image. If not * it means we are altering the original. We'll * set the destination filename and path accordingly. * */ if ($this->new_image == '') { $this->dest_image = $this->source_image; $this->dest_folder = $this->source_folder; } else { if (strpos($this->new_image, '/') === FALSE AND strpos($this->new_image, '\\') === FALSE) { $this->dest_folder = $this->source_folder; $this->dest_image = $this->new_image; } else { if (function_exists('realpath') AND @realpath($this->new_image) !== FALSE) { $full_dest_path = str_replace("\\", "/", realpath($this->new_image)); } else { $full_dest_path = $this->new_image; } // Is there a file name? if ( ! preg_match("#\.(jpg|jpeg|gif|png)$#i", $full_dest_path)) { $this->dest_folder = $full_dest_path.'/'; $this->dest_image = $this->source_image; } else { $x = explode('/', $full_dest_path); $this->dest_image = end($x); $this->dest_folder = str_replace($this->dest_image, '', $full_dest_path); } } } /* * Compile the finalized filenames/paths * * We'll create two master strings containing the * full server path to the source image and the * full server path to the destination image. * We'll also split the destination image name * so we can insert the thumbnail marker if needed. * */ if ($this->create_thumb === FALSE OR $this->thumb_marker == '') { $this->thumb_marker = ''; } $xp = $this->explode_name($this->dest_image); $filename = $xp['name']; $file_ext = $xp['ext']; $this->full_src_path = $this->source_folder.$this->source_image; $this->full_dst_path = $this->dest_folder.$filename.$this->thumb_marker.$file_ext; /* * Should we maintain image proportions? * * When creating thumbs or copies, the target width/height * might not be in correct proportion with the source * image's width/height. We'll recalculate it here. * */ if ($this->maintain_ratio === TRUE && ($this->width != '' AND $this->height != '')) { $this->image_reproportion(); } /* * Was a width and height specified? * * If the destination width/height was * not submitted we will use the values * from the actual file * */ if ($this->width == '') $this->width = $this->orig_width; if ($this->height == '') $this->height = $this->orig_height; // Set the quality $this->quality = trim(str_replace("%", "", $this->quality)); if ($this->quality == '' OR $this->quality == 0 OR ! is_numeric($this->quality)) $this->quality = 90; // Set the x/y coordinates $this->x_axis = ($this->x_axis == '' OR ! is_numeric($this->x_axis)) ? 0 : $this->x_axis; $this->y_axis = ($this->y_axis == '' OR ! is_numeric($this->y_axis)) ? 0 : $this->y_axis; // Watermark-related Stuff... if ($this->wm_font_color != '') { if (strlen($this->wm_font_color) == 6) { $this->wm_font_color = '#'.$this->wm_font_color; } } if ($this->wm_shadow_color != '') { if (strlen($this->wm_shadow_color) == 6) { $this->wm_shadow_color = '#'.$this->wm_shadow_color; } } if ($this->wm_overlay_path != '') { $this->wm_overlay_path = str_replace("\\", "/", realpath($this->wm_overlay_path)); } if ($this->wm_shadow_color != '') { $this->wm_use_drop_shadow = TRUE; } if ($this->wm_font_path != '') { $this->wm_use_truetype = TRUE; } return TRUE; } // -------------------------------------------------------------------- /** * Image Resize * * This is a wrapper function that chooses the proper * resize function based on the protocol specified * * @access public * @return bool */ function resize() { $protocol = 'image_process_'.$this->image_library; if (preg_match('/gd2$/i', $protocol)) { $protocol = 'image_process_gd'; } return $this->$protocol('resize'); } // -------------------------------------------------------------------- /** * Image Crop * * This is a wrapper function that chooses the proper * cropping function based on the protocol specified * * @access public * @return bool */ function crop() { $protocol = 'image_process_'.$this->image_library; if (preg_match('/gd2$/i', $protocol)) { $protocol = 'image_process_gd'; } return $this->$protocol('crop'); } // -------------------------------------------------------------------- /** * Image Rotate * * This is a wrapper function that chooses the proper * rotation function based on the protocol specified * * @access public * @return bool */ function rotate() { // Allowed rotation values $degs = array(90, 180, 270, 'vrt', 'hor'); if ($this->rotation_angle == '' OR ! in_array($this->rotation_angle, $degs)) { $this->set_error('imglib_rotation_angle_required'); return FALSE; } // Reassign the width and height if ($this->rotation_angle == 90 OR $this->rotation_angle == 270) { $this->width = $this->orig_height; $this->height = $this->orig_width; } else { $this->width = $this->orig_width; $this->height = $this->orig_height; } // Choose resizing function if ($this->image_library == 'imagemagick' OR $this->image_library == 'netpbm') { $protocol = 'image_process_'.$this->image_library; return $this->$protocol('rotate'); } if ($this->rotation_angle == 'hor' OR $this->rotation_angle == 'vrt') { return $this->image_mirror_gd(); } else { return $this->image_rotate_gd(); } } // -------------------------------------------------------------------- /** * Image Process Using GD/GD2 * * This function will resize or crop * * @access public * @param string * @return bool */ function image_process_gd($action = 'resize') { $v2_override = FALSE; // If the target width/height match the source, AND if the new file name is not equal to the old file name // we'll simply make a copy of the original with the new name... assuming dynamic rendering is off. if ($this->dynamic_output === FALSE) { if ($this->orig_width == $this->width AND $this->orig_height == $this->height) { if ($this->source_image != $this->new_image) { if (@copy($this->full_src_path, $this->full_dst_path)) { @chmod($this->full_dst_path, FILE_WRITE_MODE); } } return TRUE; } } // Let's set up our values based on the action if ($action == 'crop') { // Reassign the source width/height if cropping $this->orig_width = $this->width; $this->orig_height = $this->height; // GD 2.0 has a cropping bug so we'll test for it if ($this->gd_version() !== FALSE) { $gd_version = str_replace('0', '', $this->gd_version()); $v2_override = ($gd_version == 2) ? TRUE : FALSE; } } else { // If resizing the x/y axis must be zero $this->x_axis = 0; $this->y_axis = 0; } // Create the image handle if ( ! ($src_img = $this->image_create_gd())) { return FALSE; } // Create The Image // // old conditional which users report cause problems with shared GD libs who report themselves as "2.0 or greater" // it appears that this is no longer the issue that it was in 2004, so we've removed it, retaining it in the comment // below should that ever prove inaccurate. // // if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor') AND $v2_override == FALSE) if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor')) { $create = 'imagecreatetruecolor'; $copy = 'imagecopyresampled'; } else { $create = 'imagecreate'; $copy = 'imagecopyresized'; } $dst_img = $create($this->width, $this->height); if ($this->image_type == 3) // png we can actually preserve transparency { imagealphablending($dst_img, FALSE); imagesavealpha($dst_img, TRUE); } $copy($dst_img, $src_img, 0, 0, $this->x_axis, $this->y_axis, $this->width, $this->height, $this->orig_width, $this->orig_height); // Show the image if ($this->dynamic_output == TRUE) { $this->image_display_gd($dst_img); } else { // Or save it if ( ! $this->image_save_gd($dst_img)) { return FALSE; } } // Kill the file handles imagedestroy($dst_img); imagedestroy($src_img); // Set the file to 777 @chmod($this->full_dst_path, FILE_WRITE_MODE); return TRUE; } // -------------------------------------------------------------------- /** * Image Process Using ImageMagick * * This function will resize, crop or rotate * * @access public * @param string * @return bool */ function image_process_imagemagick($action = 'resize') { // Do we have a vaild library path? if ($this->library_path == '') { $this->set_error('imglib_libpath_invalid'); return FALSE; } if ( ! preg_match("/convert$/i", $this->library_path)) { $this->library_path = rtrim($this->library_path, '/').'/'; $this->library_path .= 'convert'; } // Execute the command $cmd = $this->library_path." -quality ".$this->quality; if ($action == 'crop') { $cmd .= " -crop ".$this->width."x".$this->height."+".$this->x_axis."+".$this->y_axis." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1"; } elseif ($action == 'rotate') { switch ($this->rotation_angle) { case 'hor' : $angle = '-flop'; break; case 'vrt' : $angle = '-flip'; break; default : $angle = '-rotate '.$this->rotation_angle; break; } $cmd .= " ".$angle." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1"; } else // Resize { $cmd .= " -resize ".$this->width."x".$this->height." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1"; } $retval = 1; @exec($cmd, $output, $retval); // Did it work? if ($retval > 0) { $this->set_error('imglib_image_process_failed'); return FALSE; } // Set the file to 777 @chmod($this->full_dst_path, FILE_WRITE_MODE); return TRUE; } // -------------------------------------------------------------------- /** * Image Process Using NetPBM * * This function will resize, crop or rotate * * @access public * @param string * @return bool */ function image_process_netpbm($action = 'resize') { if ($this->library_path == '') { $this->set_error('imglib_libpath_invalid'); return FALSE; } // Build the resizing command switch ($this->image_type) { case 1 : $cmd_in = 'giftopnm'; $cmd_out = 'ppmtogif'; break; case 2 : $cmd_in = 'jpegtopnm'; $cmd_out = 'ppmtojpeg'; break; case 3 : $cmd_in = 'pngtopnm'; $cmd_out = 'ppmtopng'; break; } if ($action == 'crop') { $cmd_inner = 'pnmcut -left '.$this->x_axis.' -top '.$this->y_axis.' -width '.$this->width.' -height '.$this->height; } elseif ($action == 'rotate') { switch ($this->rotation_angle) { case 90 : $angle = 'r270'; break; case 180 : $angle = 'r180'; break; case 270 : $angle = 'r90'; break; case 'vrt' : $angle = 'tb'; break; case 'hor' : $angle = 'lr'; break; } $cmd_inner = 'pnmflip -'.$angle.' '; } else // Resize { $cmd_inner = 'pnmscale -xysize '.$this->width.' '.$this->height; } $cmd = $this->library_path.$cmd_in.' '.$this->full_src_path.' | '.$cmd_inner.' | '.$cmd_out.' > '.$this->dest_folder.'netpbm.tmp'; $retval = 1; @exec($cmd, $output, $retval); // Did it work? if ($retval > 0) { $this->set_error('imglib_image_process_failed'); return FALSE; } // With NetPBM we have to create a temporary image. // If you try manipulating the original it fails so // we have to rename the temp file. copy ($this->dest_folder.'netpbm.tmp', $this->full_dst_path); unlink ($this->dest_folder.'netpbm.tmp'); @chmod($this->full_dst_path, FILE_WRITE_MODE); return TRUE; } // -------------------------------------------------------------------- /** * Image Rotate Using GD * * @access public * @return bool */ function image_rotate_gd() { // Create the image handle if ( ! ($src_img = $this->image_create_gd())) { return FALSE; } // Set the background color // This won't work with transparent PNG files so we are // going to have to figure out how to determine the color // of the alpha channel in a future release. $white = imagecolorallocate($src_img, 255, 255, 255); // Rotate it! $dst_img = imagerotate($src_img, $this->rotation_angle, $white); // Save the Image if ($this->dynamic_output == TRUE) { $this->image_display_gd($dst_img); } else { // Or save it if ( ! $this->image_save_gd($dst_img)) { return FALSE; } } // Kill the file handles imagedestroy($dst_img); imagedestroy($src_img); // Set the file to 777 @chmod($this->full_dst_path, FILE_WRITE_MODE); return TRUE; } // -------------------------------------------------------------------- /** * Create Mirror Image using GD * * This function will flip horizontal or vertical * * @access public * @return bool */ function image_mirror_gd() { if ( ! $src_img = $this->image_create_gd()) { return FALSE; } $width = $this->orig_width; $height = $this->orig_height; if ($this->rotation_angle == 'hor') { for ($i = 0; $i < $height; $i++) { $left = 0; $right = $width-1; while ($left < $right) { $cl = imagecolorat($src_img, $left, $i); $cr = imagecolorat($src_img, $right, $i); imagesetpixel($src_img, $left, $i, $cr); imagesetpixel($src_img, $right, $i, $cl); $left++; $right--; } } } else { for ($i = 0; $i < $width; $i++) { $top = 0; $bot = $height-1; while ($top < $bot) { $ct = imagecolorat($src_img, $i, $top); $cb = imagecolorat($src_img, $i, $bot); imagesetpixel($src_img, $i, $top, $cb); imagesetpixel($src_img, $i, $bot, $ct); $top++; $bot--; } } } // Show the image if ($this->dynamic_output == TRUE) { $this->image_display_gd($src_img); } else { // Or save it if ( ! $this->image_save_gd($src_img)) { return FALSE; } } // Kill the file handles imagedestroy($src_img); // Set the file to 777 @chmod($this->full_dst_path, FILE_WRITE_MODE); return TRUE; } // -------------------------------------------------------------------- /** * Image Watermark * * This is a wrapper function that chooses the type * of watermarking based on the specified preference. * * @access public * @param string * @return bool */ function watermark() { if ($this->wm_type == 'overlay') { return $this->overlay_watermark(); } else { return $this->text_watermark(); } } // -------------------------------------------------------------------- /** * Watermark - Graphic Version * * @access public * @return bool */ function overlay_watermark() { if ( ! function_exists('imagecolortransparent')) { $this->set_error('imglib_gd_required'); return FALSE; } // Fetch source image properties $this->get_image_properties(); // Fetch watermark image properties $props = $this->get_image_properties($this->wm_overlay_path, TRUE); $wm_img_type = $props['image_type']; $wm_width = $props['width']; $wm_height = $props['height']; // Create two image resources $wm_img = $this->image_create_gd($this->wm_overlay_path, $wm_img_type); $src_img = $this->image_create_gd($this->full_src_path); // Reverse the offset if necessary // When the image is positioned at the bottom // we don't want the vertical offset to push it // further down. We want the reverse, so we'll // invert the offset. Same with the horizontal // offset when the image is at the right $this->wm_vrt_alignment = strtoupper(substr($this->wm_vrt_alignment, 0, 1)); $this->wm_hor_alignment = strtoupper(substr($this->wm_hor_alignment, 0, 1)); if ($this->wm_vrt_alignment == 'B') $this->wm_vrt_offset = $this->wm_vrt_offset * -1; if ($this->wm_hor_alignment == 'R') $this->wm_hor_offset = $this->wm_hor_offset * -1; // Set the base x and y axis values $x_axis = $this->wm_hor_offset + $this->wm_padding; $y_axis = $this->wm_vrt_offset + $this->wm_padding; // Set the vertical position switch ($this->wm_vrt_alignment) { case 'T': break; case 'M': $y_axis += ($this->orig_height / 2) - ($wm_height / 2); break; case 'B': $y_axis += $this->orig_height - $wm_height; break; } // Set the horizontal position switch ($this->wm_hor_alignment) { case 'L': break; case 'C': $x_axis += ($this->orig_width / 2) - ($wm_width / 2); break; case 'R': $x_axis += $this->orig_width - $wm_width; break; } // Build the finalized image if ($wm_img_type == 3 AND function_exists('imagealphablending')) { @imagealphablending($src_img, TRUE); } // Set RGB values for text and shadow $rgba = imagecolorat($wm_img, $this->wm_x_transp, $this->wm_y_transp); $alpha = ($rgba & 0x7F000000) >> 24; // make a best guess as to whether we're dealing with an image with alpha transparency or no/binary transparency if ($alpha > 0) { // copy the image directly, the image's alpha transparency being the sole determinant of blending imagecopy($src_img, $wm_img, $x_axis, $y_axis, 0, 0, $wm_width, $wm_height); } else { // set our RGB value from above to be transparent and merge the images with the specified opacity imagecolortransparent($wm_img, imagecolorat($wm_img, $this->wm_x_transp, $this->wm_y_transp)); imagecopymerge($src_img, $wm_img, $x_axis, $y_axis, 0, 0, $wm_width, $wm_height, $this->wm_opacity); } // Output the image if ($this->dynamic_output == TRUE) { $this->image_display_gd($src_img); } else { if ( ! $this->image_save_gd($src_img)) { return FALSE; } } imagedestroy($src_img); imagedestroy($wm_img); return TRUE; } // -------------------------------------------------------------------- /** * Watermark - Text Version * * @access public * @return bool */ function text_watermark() { if ( ! ($src_img = $this->image_create_gd())) { return FALSE; } if ($this->wm_use_truetype == TRUE AND ! file_exists($this->wm_font_path)) { $this->set_error('imglib_missing_font'); return FALSE; } // Fetch source image properties $this->get_image_properties(); // Set RGB values for text and shadow $this->wm_font_color = str_replace('#', '', $this->wm_font_color); $this->wm_shadow_color = str_replace('#', '', $this->wm_shadow_color); $R1 = hexdec(substr($this->wm_font_color, 0, 2)); $G1 = hexdec(substr($this->wm_font_color, 2, 2)); $B1 = hexdec(substr($this->wm_font_color, 4, 2)); $R2 = hexdec(substr($this->wm_shadow_color, 0, 2)); $G2 = hexdec(substr($this->wm_shadow_color, 2, 2)); $B2 = hexdec(substr($this->wm_shadow_color, 4, 2)); $txt_color = imagecolorclosest($src_img, $R1, $G1, $B1); $drp_color = imagecolorclosest($src_img, $R2, $G2, $B2); // Reverse the vertical offset // When the image is positioned at the bottom // we don't want the vertical offset to push it // further down. We want the reverse, so we'll // invert the offset. Note: The horizontal // offset flips itself automatically if ($this->wm_vrt_alignment == 'B') $this->wm_vrt_offset = $this->wm_vrt_offset * -1; if ($this->wm_hor_alignment == 'R') $this->wm_hor_offset = $this->wm_hor_offset * -1; // Set font width and height // These are calculated differently depending on // whether we are using the true type font or not if ($this->wm_use_truetype == TRUE) { if ($this->wm_font_size == '') $this->wm_font_size = '17'; $fontwidth = $this->wm_font_size-($this->wm_font_size/4); $fontheight = $this->wm_font_size; $this->wm_vrt_offset += $this->wm_font_size; } else { $fontwidth = imagefontwidth($this->wm_font_size); $fontheight = imagefontheight($this->wm_font_size); } // Set base X and Y axis values $x_axis = $this->wm_hor_offset + $this->wm_padding; $y_axis = $this->wm_vrt_offset + $this->wm_padding; // Set verticle alignment if ($this->wm_use_drop_shadow == FALSE) $this->wm_shadow_distance = 0; $this->wm_vrt_alignment = strtoupper(substr($this->wm_vrt_alignment, 0, 1)); $this->wm_hor_alignment = strtoupper(substr($this->wm_hor_alignment, 0, 1)); switch ($this->wm_vrt_alignment) { case "T" : break; case "M": $y_axis += ($this->orig_height/2)+($fontheight/2); break; case "B": $y_axis += ($this->orig_height - $fontheight - $this->wm_shadow_distance - ($fontheight/2)); break; } $x_shad = $x_axis + $this->wm_shadow_distance; $y_shad = $y_axis + $this->wm_shadow_distance; // Set horizontal alignment switch ($this->wm_hor_alignment) { case "L": break; case "R": if ($this->wm_use_drop_shadow) $x_shad += ($this->orig_width - $fontwidth*strlen($this->wm_text)); $x_axis += ($this->orig_width - $fontwidth*strlen($this->wm_text)); break; case "C": if ($this->wm_use_drop_shadow) $x_shad += floor(($this->orig_width - $fontwidth*strlen($this->wm_text))/2); $x_axis += floor(($this->orig_width -$fontwidth*strlen($this->wm_text))/2); break; } // Add the text to the source image if ($this->wm_use_truetype) { if ($this->wm_use_drop_shadow) imagettftext($src_img, $this->wm_font_size, 0, $x_shad, $y_shad, $drp_color, $this->wm_font_path, $this->wm_text); imagettftext($src_img, $this->wm_font_size, 0, $x_axis, $y_axis, $txt_color, $this->wm_font_path, $this->wm_text); } else { if ($this->wm_use_drop_shadow) imagestring($src_img, $this->wm_font_size, $x_shad, $y_shad, $this->wm_text, $drp_color); imagestring($src_img, $this->wm_font_size, $x_axis, $y_axis, $this->wm_text, $txt_color); } // Output the final image if ($this->dynamic_output == TRUE) { $this->image_display_gd($src_img); } else { $this->image_save_gd($src_img); } imagedestroy($src_img); return TRUE; } // -------------------------------------------------------------------- /** * Create Image - GD * * This simply creates an image resource handle * based on the type of image being processed * * @access public * @param string * @return resource */ function image_create_gd($path = '', $image_type = '') { if ($path == '') $path = $this->full_src_path; if ($image_type == '') $image_type = $this->image_type; switch ($image_type) { case 1 : if ( ! function_exists('imagecreatefromgif')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); return FALSE; } return imagecreatefromgif($path); break; case 2 : if ( ! function_exists('imagecreatefromjpeg')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); return FALSE; } return imagecreatefromjpeg($path); break; case 3 : if ( ! function_exists('imagecreatefrompng')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); return FALSE; } return imagecreatefrompng($path); break; } $this->set_error(array('imglib_unsupported_imagecreate')); return FALSE; } // -------------------------------------------------------------------- /** * Write image file to disk - GD * * Takes an image resource as input and writes the file * to the specified destination * * @access public * @param resource * @return bool */ function image_save_gd($resource) { switch ($this->image_type) { case 1 : if ( ! function_exists('imagegif')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); return FALSE; } if ( ! @imagegif($resource, $this->full_dst_path)) { $this->set_error('imglib_save_failed'); return FALSE; } break; case 2 : if ( ! function_exists('imagejpeg')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); return FALSE; } if ( ! @imagejpeg($resource, $this->full_dst_path, $this->quality)) { $this->set_error('imglib_save_failed'); return FALSE; } break; case 3 : if ( ! function_exists('imagepng')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); return FALSE; } if ( ! @imagepng($resource, $this->full_dst_path)) { $this->set_error('imglib_save_failed'); return FALSE; } break; default : $this->set_error(array('imglib_unsupported_imagecreate')); return FALSE; break; } return TRUE; } // -------------------------------------------------------------------- /** * Dynamically outputs an image * * @access public * @param resource * @return void */ function image_display_gd($resource) { header("Content-Disposition: filename={$this->source_image};"); header("Content-Type: {$this->mime_type}"); header('Content-Transfer-Encoding: binary'); header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT'); switch ($this->image_type) { case 1 : imagegif($resource); break; case 2 : imagejpeg($resource, '', $this->quality); break; case 3 : imagepng($resource); break; default : echo 'Unable to display the image'; break; } } // -------------------------------------------------------------------- /** * Re-proportion Image Width/Height * * When creating thumbs, the desired width/height * can end up warping the image due to an incorrect * ratio between the full-sized image and the thumb. * * This function lets us re-proportion the width/height * if users choose to maintain the aspect ratio when resizing. * * @access public * @return void */ function image_reproportion() { if ( ! is_numeric($this->width) OR ! is_numeric($this->height) OR $this->width == 0 OR $this->height == 0) return; if ( ! is_numeric($this->orig_width) OR ! is_numeric($this->orig_height) OR $this->orig_width == 0 OR $this->orig_height == 0) return; $new_width = ceil($this->orig_width*$this->height/$this->orig_height); $new_height = ceil($this->width*$this->orig_height/$this->orig_width); $ratio = (($this->orig_height/$this->orig_width) - ($this->height/$this->width)); if ($this->master_dim != 'width' AND $this->master_dim != 'height') { $this->master_dim = ($ratio < 0) ? 'width' : 'height'; } if (($this->width != $new_width) AND ($this->height != $new_height)) { if ($this->master_dim == 'height') { $this->width = $new_width; } else
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
true
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Zip.php
system/libraries/Zip.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Zip Compression Class * * This class is based on a library I found at Zend: * http://www.zend.com/codex.php?id=696&single=1 * * The original library is a little rough around the edges so I * refactored it and added several additional methods -- Rick Ellis * * @package CodeIgniter * @subpackage Libraries * @category Encryption * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/zip.html */ class CI_Zip { var $zipdata = ''; var $directory = ''; var $entries = 0; var $file_num = 0; var $offset = 0; var $now; /** * Constructor */ public function __construct() { log_message('debug', "Zip Compression Class Initialized"); $this->now = time(); } // -------------------------------------------------------------------- /** * Add Directory * * Lets you add a virtual directory into which you can place files. * * @access public * @param mixed the directory name. Can be string or array * @return void */ function add_dir($directory) { foreach ((array)$directory as $dir) { if ( ! preg_match("|.+/$|", $dir)) { $dir .= '/'; } $dir_time = $this->_get_mod_time($dir); $this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']); } } // -------------------------------------------------------------------- /** * Get file/directory modification time * * If this is a newly created file/dir, we will set the time to 'now' * * @param string path to file * @return array filemtime/filemdate */ function _get_mod_time($dir) { // filemtime() will return false, but it does raise an error. $date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now); $time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2; $time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday']; return $time; } // -------------------------------------------------------------------- /** * Add Directory * * @access private * @param string the directory name * @return void */ function _add_dir($dir, $file_mtime, $file_mdate) { $dir = str_replace("\\", "/", $dir); $this->zipdata .= "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V', 0) // crc32 .pack('V', 0) // compressed filesize .pack('V', 0) // uncompressed filesize .pack('v', strlen($dir)) // length of pathname .pack('v', 0) // extra field length .$dir // below is "data descriptor" segment .pack('V', 0) // crc32 .pack('V', 0) // compressed filesize .pack('V', 0); // uncompressed filesize $this->directory .= "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V',0) // crc32 .pack('V',0) // compressed filesize .pack('V',0) // uncompressed filesize .pack('v', strlen($dir)) // length of pathname .pack('v', 0) // extra field length .pack('v', 0) // file comment length .pack('v', 0) // disk number start .pack('v', 0) // internal file attributes .pack('V', 16) // external file attributes - 'directory' bit set .pack('V', $this->offset) // relative offset of local header .$dir; $this->offset = strlen($this->zipdata); $this->entries++; } // -------------------------------------------------------------------- /** * Add Data to Zip * * Lets you add files to the archive. If the path is included * in the filename it will be placed within a directory. Make * sure you use add_dir() first to create the folder. * * @access public * @param mixed * @param string * @return void */ function add_data($filepath, $data = NULL) { if (is_array($filepath)) { foreach ($filepath as $path => $data) { $file_data = $this->_get_mod_time($path); $this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']); } } else { $file_data = $this->_get_mod_time($filepath); $this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']); } } // -------------------------------------------------------------------- /** * Add Data to Zip * * @access private * @param string the file name/path * @param string the data to be encoded * @return void */ function _add_data($filepath, $data, $file_mtime, $file_mdate) { $filepath = str_replace("\\", "/", $filepath); $uncompressed_size = strlen($data); $crc32 = crc32($data); $gzdata = gzcompress($data); $gzdata = substr($gzdata, 2, -4); $compressed_size = strlen($gzdata); $this->zipdata .= "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V', $crc32) .pack('V', $compressed_size) .pack('V', $uncompressed_size) .pack('v', strlen($filepath)) // length of filename .pack('v', 0) // extra field length .$filepath .$gzdata; // "file data" segment $this->directory .= "\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V', $crc32) .pack('V', $compressed_size) .pack('V', $uncompressed_size) .pack('v', strlen($filepath)) // length of filename .pack('v', 0) // extra field length .pack('v', 0) // file comment length .pack('v', 0) // disk number start .pack('v', 0) // internal file attributes .pack('V', 32) // external file attributes - 'archive' bit set .pack('V', $this->offset) // relative offset of local header .$filepath; $this->offset = strlen($this->zipdata); $this->entries++; $this->file_num++; } // -------------------------------------------------------------------- /** * Read the contents of a file and add it to the zip * * @access public * @return bool */ function read_file($path, $preserve_filepath = FALSE) { if ( ! file_exists($path)) { return FALSE; } if (FALSE !== ($data = file_get_contents($path))) { $name = str_replace("\\", "/", $path); if ($preserve_filepath === FALSE) { $name = preg_replace("|.*/(.+)|", "\\1", $name); } $this->add_data($name, $data); return TRUE; } return FALSE; } // ------------------------------------------------------------------------ /** * Read a directory and add it to the zip. * * This function recursively reads a folder and everything it contains (including * sub-folders) and creates a zip based on it. Whatever directory structure * is in the original file path will be recreated in the zip file. * * @access public * @param string path to source * @return bool */ function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL) { if ( ! $fp = @opendir($path)) { return FALSE; } // Set the original directory root for child dir's to use as relative if ($root_path === NULL) { $root_path = dirname($path).'/'; } while (FALSE !== ($file = readdir($fp))) { if (substr($file, 0, 1) == '.') { continue; } if (@is_dir($path.$file)) { $this->read_dir($path.$file."/", $preserve_filepath, $root_path); } else { if (FALSE !== ($data = file_get_contents($path.$file))) { $name = str_replace("\\", "/", $path); if ($preserve_filepath === FALSE) { $name = str_replace($root_path, '', $name); } $this->add_data($name.$file, $data); } } } return TRUE; } // -------------------------------------------------------------------- /** * Get the Zip file * * @access public * @return binary string */ function get_zip() { // Is there any data to return? if ($this->entries == 0) { return FALSE; } $zip_data = $this->zipdata; $zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00"; $zip_data .= pack('v', $this->entries); // total # of entries "on this disk" $zip_data .= pack('v', $this->entries); // total # of entries overall $zip_data .= pack('V', strlen($this->directory)); // size of central dir $zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir $zip_data .= "\x00\x00"; // .zip file comment length return $zip_data; } // -------------------------------------------------------------------- /** * Write File to the specified directory * * Lets you write a file * * @access public * @param string the file name * @return bool */ function archive($filepath) { if ( ! ($fp = @fopen($filepath, FOPEN_WRITE_CREATE_DESTRUCTIVE))) { return FALSE; } flock($fp, LOCK_EX); fwrite($fp, $this->get_zip()); flock($fp, LOCK_UN); fclose($fp); return TRUE; } // -------------------------------------------------------------------- /** * Download * * @access public * @param string the file name * @param string the data to be encoded * @return bool */ function download($filename = 'backup.zip') { if ( ! preg_match("|.+?\.zip$|", $filename)) { $filename .= '.zip'; } $CI =& get_instance(); $CI->load->helper('download'); $get_zip = $this->get_zip(); $zip_content =& $get_zip; force_download($filename, $zip_content); } // -------------------------------------------------------------------- /** * Initialize Data * * Lets you clear current zip data. Useful if you need to create * multiple zips with different data. * * @access public * @return void */ function clear_data() { $this->zipdata = ''; $this->directory = ''; $this->entries = 0; $this->file_num = 0; $this->offset = 0; } } /* End of file Zip.php */ /* Location: ./system/libraries/Zip.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Cache/Cache.php
system/libraries/Cache/Cache.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 4.3.2 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author ExpressionEngine Dev Team * @link */ class CI_Cache extends CI_Driver_Library { protected $valid_drivers = array( 'cache_apc', 'cache_file', 'cache_memcached', 'cache_dummy' ); protected $_cache_path = NULL; // Path of cache files (if file-based cache) protected $_adapter = 'dummy'; protected $_backup_driver; // ------------------------------------------------------------------------ /** * Constructor * * @param array */ public function __construct($config = array()) { if ( ! empty($config)) { $this->_initialize($config); } } // ------------------------------------------------------------------------ /** * Get * * Look for a value in the cache. If it exists, return the data * if not, return FALSE * * @param string * @return mixed value that is stored/FALSE on failure */ public function get($id) { return $this->{$this->_adapter}->get($id); } // ------------------------------------------------------------------------ /** * Cache Save * * @param string Unique Key * @param mixed Data to store * @param int Length of time (in seconds) to cache the data * * @return boolean true on success/false on failure */ public function save($id, $data, $ttl = 60) { return $this->{$this->_adapter}->save($id, $data, $ttl); } // ------------------------------------------------------------------------ /** * Delete from Cache * * @param mixed unique identifier of the item in the cache * @return boolean true on success/false on failure */ public function delete($id) { return $this->{$this->_adapter}->delete($id); } // ------------------------------------------------------------------------ /** * Clean the cache * * @return boolean false on failure/true on success */ public function clean() { return $this->{$this->_adapter}->clean(); } // ------------------------------------------------------------------------ /** * Cache Info * * @param string user/filehits * @return mixed array on success, false on failure */ public function cache_info($type = 'user') { return $this->{$this->_adapter}->cache_info($type); } // ------------------------------------------------------------------------ /** * Get Cache Metadata * * @param mixed key to get cache metadata on * @return mixed return value from child method */ public function get_metadata($id) { return $this->{$this->_adapter}->get_metadata($id); } // ------------------------------------------------------------------------ /** * Initialize * * Initialize class properties based on the configuration array. * * @param array * @return void */ private function _initialize($config) { $default_config = array( 'adapter', 'memcached' ); foreach ($default_config as $key) { if (isset($config[$key])) { $param = '_'.$key; $this->{$param} = $config[$key]; } } if (isset($config['backup'])) { if (in_array('cache_'.$config['backup'], $this->valid_drivers)) { $this->_backup_driver = $config['backup']; } } } // ------------------------------------------------------------------------ /** * Is the requested driver supported in this environment? * * @param string The driver to test. * @return array */ public function is_supported($driver) { static $support = array(); if ( ! isset($support[$driver])) { $support[$driver] = $this->{$driver}->is_supported(); } return $support[$driver]; } // ------------------------------------------------------------------------ /** * __get() * * @param child * @return object */ public function __get($child) { $obj = parent::__get($child); if ( ! $this->is_supported($child)) { $this->_adapter = $this->_backup_driver; } return $obj; } // ------------------------------------------------------------------------ } // End Class /* End of file Cache.php */ /* Location: ./system/libraries/Cache/Cache.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Cache/drivers/Cache_dummy.php
system/libraries/Cache/drivers/Cache_dummy.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 4.3.2 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Dummy Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author ExpressionEngine Dev Team * @link */ class CI_Cache_dummy extends CI_Driver { /** * Get * * Since this is the dummy class, it's always going to return FALSE. * * @param string * @return Boolean FALSE */ public function get($id) { return FALSE; } // ------------------------------------------------------------------------ /** * Cache Save * * @param string Unique Key * @param mixed Data to store * @param int Length of time (in seconds) to cache the data * * @return boolean TRUE, Simulating success */ public function save($id, $data, $ttl = 60) { return TRUE; } // ------------------------------------------------------------------------ /** * Delete from Cache * * @param mixed unique identifier of the item in the cache * @param boolean TRUE, simulating success */ public function delete($id) { return TRUE; } // ------------------------------------------------------------------------ /** * Clean the cache * * @return boolean TRUE, simulating success */ public function clean() { return TRUE; } // ------------------------------------------------------------------------ /** * Cache Info * * @param string user/filehits * @return boolean FALSE */ public function cache_info($type = NULL) { return FALSE; } // ------------------------------------------------------------------------ /** * Get Cache Metadata * * @param mixed key to get cache metadata on * @return boolean FALSE */ public function get_metadata($id) { return FALSE; } // ------------------------------------------------------------------------ /** * Is this caching driver supported on the system? * Of course this one is. * * @return TRUE; */ public function is_supported() { return TRUE; } // ------------------------------------------------------------------------ } // End Class /* End of file Cache_dummy.php */ /* Location: ./system/libraries/Cache/drivers/Cache_dummy.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Cache/drivers/Cache_memcached.php
system/libraries/Cache/drivers/Cache_memcached.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 4.3.2 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Memcached Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author ExpressionEngine Dev Team * @link */ class CI_Cache_memcached extends CI_Driver { private $_memcached; // Holds the memcached object protected $_memcache_conf = array( 'default' => array( 'default_host' => '127.0.0.1', 'default_port' => 11211, 'default_weight' => 1 ) ); // ------------------------------------------------------------------------ /** * Fetch from cache * * @param mixed unique key id * @return mixed data on success/false on failure */ public function get($id) { $data = $this->_memcached->get($id); return (is_array($data)) ? $data[0] : FALSE; } // ------------------------------------------------------------------------ /** * Save * * @param string unique identifier * @param mixed data being cached * @param int time to live * @return boolean true on success, false on failure */ public function save($id, $data, $ttl = 60) { if (get_class($this->_memcached) == 'Memcached') { return $this->_memcached->set($id, array($data, time(), $ttl), $ttl); } else if (get_class($this->_memcached) == 'Memcache') { return $this->_memcached->set($id, array($data, time(), $ttl), 0, $ttl); } return FALSE; } // ------------------------------------------------------------------------ /** * Delete from Cache * * @param mixed key to be deleted. * @return boolean true on success, false on failure */ public function delete($id) { return $this->_memcached->delete($id); } // ------------------------------------------------------------------------ /** * Clean the Cache * * @return boolean false on failure/true on success */ public function clean() { return $this->_memcached->flush(); } // ------------------------------------------------------------------------ /** * Cache Info * * @param null type not supported in memcached * @return mixed array on success, false on failure */ public function cache_info($type = NULL) { return $this->_memcached->getStats(); } // ------------------------------------------------------------------------ /** * Get Cache Metadata * * @param mixed key to get cache metadata on * @return mixed FALSE on failure, array on success. */ public function get_metadata($id) { $stored = $this->_memcached->get($id); if (count($stored) !== 3) { return FALSE; } list($data, $time, $ttl) = $stored; return array( 'expire' => $time + $ttl, 'mtime' => $time, 'data' => $data ); } // ------------------------------------------------------------------------ /** * Setup memcached. */ private function _setup_memcached() { // Try to load memcached server info from the config file. $CI =& get_instance(); if ($CI->config->load('memcached', TRUE, TRUE)) { if (is_array($CI->config->config['memcached'])) { $this->_memcache_conf = NULL; foreach ($CI->config->config['memcached'] as $name => $conf) { $this->_memcache_conf[$name] = $conf; } } } $this->_memcached = new Memcached(); foreach ($this->_memcache_conf as $name => $cache_server) { if ( ! array_key_exists('hostname', $cache_server)) { $cache_server['hostname'] = $this->_default_options['default_host']; } if ( ! array_key_exists('port', $cache_server)) { $cache_server['port'] = $this->_default_options['default_port']; } if ( ! array_key_exists('weight', $cache_server)) { $cache_server['weight'] = $this->_default_options['default_weight']; } $this->_memcached->addServer( $cache_server['hostname'], $cache_server['port'], $cache_server['weight'] ); } } // ------------------------------------------------------------------------ /** * Is supported * * Returns FALSE if memcached is not supported on the system. * If it is, we setup the memcached object & return TRUE */ public function is_supported() { if ( ! extension_loaded('memcached')) { log_message('error', 'The Memcached Extension must be loaded to use Memcached Cache.'); return FALSE; } $this->_setup_memcached(); return TRUE; } // ------------------------------------------------------------------------ } // End Class /* End of file Cache_memcached.php */ /* Location: ./system/libraries/Cache/drivers/Cache_memcached.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Cache/drivers/Cache_apc.php
system/libraries/Cache/drivers/Cache_apc.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter APC Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author ExpressionEngine Dev Team * @link */ class CI_Cache_apc extends CI_Driver { /** * Get * * Look for a value in the cache. If it exists, return the data * if not, return FALSE * * @param string * @return mixed value that is stored/FALSE on failure */ public function get($id) { $data = apc_fetch($id); return (is_array($data)) ? $data[0] : FALSE; } // ------------------------------------------------------------------------ /** * Cache Save * * @param string Unique Key * @param mixed Data to store * @param int Length of time (in seconds) to cache the data * * @return boolean true on success/false on failure */ public function save($id, $data, $ttl = 60) { return apc_store($id, array($data, time(), $ttl), $ttl); } // ------------------------------------------------------------------------ /** * Delete from Cache * * @param mixed unique identifier of the item in the cache * @param boolean true on success/false on failure */ public function delete($id) { return apc_delete($id); } // ------------------------------------------------------------------------ /** * Clean the cache * * @return boolean false on failure/true on success */ public function clean() { return apc_clear_cache('user'); } // ------------------------------------------------------------------------ /** * Cache Info * * @param string user/filehits * @return mixed array on success, false on failure */ public function cache_info($type = NULL) { return apc_cache_info($type); } // ------------------------------------------------------------------------ /** * Get Cache Metadata * * @param mixed key to get cache metadata on * @return mixed array on success/false on failure */ public function get_metadata($id) { $stored = apc_fetch($id); if (count($stored) !== 3) { return FALSE; } list($data, $time, $ttl) = $stored; return array( 'expire' => $time + $ttl, 'mtime' => $time, 'data' => $data ); } // ------------------------------------------------------------------------ /** * is_supported() * * Check to see if APC is available on this system, bail if it isn't. */ public function is_supported() { if ( ! extension_loaded('apc') OR ini_get('apc.enabled') != "1") { log_message('error', 'The APC PHP extension must be loaded to use APC Cache.'); return FALSE; } return TRUE; } // ------------------------------------------------------------------------ } // End Class /* End of file Cache_apc.php */ /* Location: ./system/libraries/Cache/drivers/Cache_apc.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Cache/drivers/Cache_file.php
system/libraries/Cache/drivers/Cache_file.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 4.3.2 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Memcached Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author ExpressionEngine Dev Team * @link */ class CI_Cache_file extends CI_Driver { protected $_cache_path; /** * Constructor */ public function __construct() { $CI =& get_instance(); $CI->load->helper('file'); $path = $CI->config->item('cache_path'); $this->_cache_path = ($path == '') ? APPPATH.'cache/' : $path; } // ------------------------------------------------------------------------ /** * Fetch from cache * * @param mixed unique key id * @return mixed data on success/false on failure */ public function get($id) { if ( ! file_exists($this->_cache_path.$id)) { return FALSE; } $data = read_file($this->_cache_path.$id); $data = unserialize($data); if (time() > $data['time'] + $data['ttl']) { unlink($this->_cache_path.$id); return FALSE; } return $data['data']; } // ------------------------------------------------------------------------ /** * Save into cache * * @param string unique key * @param mixed data to store * @param int length of time (in seconds) the cache is valid * - Default is 60 seconds * @return boolean true on success/false on failure */ public function save($id, $data, $ttl = 60) { $contents = array( 'time' => time(), 'ttl' => $ttl, 'data' => $data ); if (write_file($this->_cache_path.$id, serialize($contents))) { @chmod($this->_cache_path.$id, 0777); return TRUE; } return FALSE; } // ------------------------------------------------------------------------ /** * Delete from Cache * * @param mixed unique identifier of item in cache * @return boolean true on success/false on failure */ public function delete($id) { return unlink($this->_cache_path.$id); } // ------------------------------------------------------------------------ /** * Clean the Cache * * @return boolean false on failure/true on success */ public function clean() { return delete_files($this->_cache_path); } // ------------------------------------------------------------------------ /** * Cache Info * * Not supported by file-based caching * * @param string user/filehits * @return mixed FALSE */ public function cache_info($type = NULL) { return get_dir_file_info($this->_cache_path); } // ------------------------------------------------------------------------ /** * Get Cache Metadata * * @param mixed key to get cache metadata on * @return mixed FALSE on failure, array on success. */ public function get_metadata($id) { if ( ! file_exists($this->_cache_path.$id)) { return FALSE; } $data = read_file($this->_cache_path.$id); $data = unserialize($data); if (is_array($data)) { $mtime = filemtime($this->_cache_path.$id); if ( ! isset($data['ttl'])) { return FALSE; } return array( 'expire' => $mtime + $data['ttl'], 'mtime' => $mtime ); } return FALSE; } // ------------------------------------------------------------------------ /** * Is supported * * In the file driver, check to see that the cache directory is indeed writable * * @return boolean */ public function is_supported() { return is_really_writable($this->_cache_path); } // ------------------------------------------------------------------------ } // End Class /* End of file Cache_file.php */ /* Location: ./system/libraries/Cache/drivers/Cache_file.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/javascript/Jquery.php
system/libraries/javascript/Jquery.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 4.3.2 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://www.codeigniter.com/user_guide/license.html * @link http://www.codeigniter.com * @since Version 1.0 * @filesource */ /** * Jquery Class * * @package CodeIgniter * @subpackage Libraries * @author ExpressionEngine Dev Team * @category Loader * @link http://www.codeigniter.com/user_guide/libraries/javascript.html */ class CI_Jquery extends CI_Javascript { var $_javascript_folder = 'js'; var $jquery_code_for_load = array(); var $jquery_code_for_compile = array(); var $jquery_corner_active = FALSE; var $jquery_table_sorter_active = FALSE; var $jquery_table_sorter_pager_active = FALSE; var $jquery_ajax_img = ''; public function __construct($params) { $this->CI =& get_instance(); extract($params); if ($autoload === TRUE) { $this->script(); } log_message('debug', "Jquery Class Initialized"); } // -------------------------------------------------------------------- // Event Code // -------------------------------------------------------------------- /** * Blur * * Outputs a jQuery blur event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _blur($element = 'this', $js = '') { return $this->_add_event($element, $js, 'blur'); } // -------------------------------------------------------------------- /** * Change * * Outputs a jQuery change event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _change($element = 'this', $js = '') { return $this->_add_event($element, $js, 'change'); } // -------------------------------------------------------------------- /** * Click * * Outputs a jQuery click event * * @access private * @param string The element to attach the event to * @param string The code to execute * @param boolean whether or not to return false * @return string */ function _click($element = 'this', $js = '', $ret_false = TRUE) { if ( ! is_array($js)) { $js = array($js); } if ($ret_false) { $js[] = "return false;"; } return $this->_add_event($element, $js, 'click'); } // -------------------------------------------------------------------- /** * Double Click * * Outputs a jQuery dblclick event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _dblclick($element = 'this', $js = '') { return $this->_add_event($element, $js, 'dblclick'); } // -------------------------------------------------------------------- /** * Error * * Outputs a jQuery error event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _error($element = 'this', $js = '') { return $this->_add_event($element, $js, 'error'); } // -------------------------------------------------------------------- /** * Focus * * Outputs a jQuery focus event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _focus($element = 'this', $js = '') { return $this->_add_event($element, $js, 'focus'); } // -------------------------------------------------------------------- /** * Hover * * Outputs a jQuery hover event * * @access private * @param string - element * @param string - Javascript code for mouse over * @param string - Javascript code for mouse out * @return string */ function _hover($element = 'this', $over, $out) { $event = "\n\t$(" . $this->_prep_element($element) . ").hover(\n\t\tfunction()\n\t\t{\n\t\t\t{$over}\n\t\t}, \n\t\tfunction()\n\t\t{\n\t\t\t{$out}\n\t\t});\n"; $this->jquery_code_for_compile[] = $event; return $event; } // -------------------------------------------------------------------- /** * Keydown * * Outputs a jQuery keydown event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _keydown($element = 'this', $js = '') { return $this->_add_event($element, $js, 'keydown'); } // -------------------------------------------------------------------- /** * Keyup * * Outputs a jQuery keydown event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _keyup($element = 'this', $js = '') { return $this->_add_event($element, $js, 'keyup'); } // -------------------------------------------------------------------- /** * Load * * Outputs a jQuery load event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _load($element = 'this', $js = '') { return $this->_add_event($element, $js, 'load'); } // -------------------------------------------------------------------- /** * Mousedown * * Outputs a jQuery mousedown event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _mousedown($element = 'this', $js = '') { return $this->_add_event($element, $js, 'mousedown'); } // -------------------------------------------------------------------- /** * Mouse Out * * Outputs a jQuery mouseout event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _mouseout($element = 'this', $js = '') { return $this->_add_event($element, $js, 'mouseout'); } // -------------------------------------------------------------------- /** * Mouse Over * * Outputs a jQuery mouseover event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _mouseover($element = 'this', $js = '') { return $this->_add_event($element, $js, 'mouseover'); } // -------------------------------------------------------------------- /** * Mouseup * * Outputs a jQuery mouseup event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _mouseup($element = 'this', $js = '') { return $this->_add_event($element, $js, 'mouseup'); } // -------------------------------------------------------------------- /** * Output * * Outputs script directly * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _output($array_js = '') { if ( ! is_array($array_js)) { $array_js = array($array_js); } foreach ($array_js as $js) { $this->jquery_code_for_compile[] = "\t$js\n"; } } // -------------------------------------------------------------------- /** * Resize * * Outputs a jQuery resize event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _resize($element = 'this', $js = '') { return $this->_add_event($element, $js, 'resize'); } // -------------------------------------------------------------------- /** * Scroll * * Outputs a jQuery scroll event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _scroll($element = 'this', $js = '') { return $this->_add_event($element, $js, 'scroll'); } // -------------------------------------------------------------------- /** * Unload * * Outputs a jQuery unload event * * @access private * @param string The element to attach the event to * @param string The code to execute * @return string */ function _unload($element = 'this', $js = '') { return $this->_add_event($element, $js, 'unload'); } // -------------------------------------------------------------------- // Effects // -------------------------------------------------------------------- /** * Add Class * * Outputs a jQuery addClass event * * @access private * @param string - element * @return string */ function _addClass($element = 'this', $class='') { $element = $this->_prep_element($element); $str = "$({$element}).addClass(\"$class\");"; return $str; } // -------------------------------------------------------------------- /** * Animate * * Outputs a jQuery animate event * * @access private * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _animate($element = 'this', $params = array(), $speed = '', $extra = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); $animations = "\t\t\t"; foreach ($params as $param=>$value) { $animations .= $param.': \''.$value.'\', '; } $animations = substr($animations, 0, -2); // remove the last ", " if ($speed != '') { $speed = ', '.$speed; } if ($extra != '') { $extra = ', '.$extra; } $str = "$({$element}).animate({\n$animations\n\t\t}".$speed.$extra.");"; return $str; } // -------------------------------------------------------------------- /** * Fade In * * Outputs a jQuery hide event * * @access private * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _fadeIn($element = 'this', $speed = '', $callback = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); if ($callback != '') { $callback = ", function(){\n{$callback}\n}"; } $str = "$({$element}).fadeIn({$speed}{$callback});"; return $str; } // -------------------------------------------------------------------- /** * Fade Out * * Outputs a jQuery hide event * * @access private * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _fadeOut($element = 'this', $speed = '', $callback = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); if ($callback != '') { $callback = ", function(){\n{$callback}\n}"; } $str = "$({$element}).fadeOut({$speed}{$callback});"; return $str; } // -------------------------------------------------------------------- /** * Hide * * Outputs a jQuery hide action * * @access private * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _hide($element = 'this', $speed = '', $callback = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); if ($callback != '') { $callback = ", function(){\n{$callback}\n}"; } $str = "$({$element}).hide({$speed}{$callback});"; return $str; } // -------------------------------------------------------------------- /** * Remove Class * * Outputs a jQuery remove class event * * @access private * @param string - element * @return string */ function _removeClass($element = 'this', $class='') { $element = $this->_prep_element($element); $str = "$({$element}).removeClass(\"$class\");"; return $str; } // -------------------------------------------------------------------- /** * Slide Up * * Outputs a jQuery slideUp event * * @access private * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _slideUp($element = 'this', $speed = '', $callback = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); if ($callback != '') { $callback = ", function(){\n{$callback}\n}"; } $str = "$({$element}).slideUp({$speed}{$callback});"; return $str; } // -------------------------------------------------------------------- /** * Slide Down * * Outputs a jQuery slideDown event * * @access private * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _slideDown($element = 'this', $speed = '', $callback = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); if ($callback != '') { $callback = ", function(){\n{$callback}\n}"; } $str = "$({$element}).slideDown({$speed}{$callback});"; return $str; } // -------------------------------------------------------------------- /** * Slide Toggle * * Outputs a jQuery slideToggle event * * @access public * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _slideToggle($element = 'this', $speed = '', $callback = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); if ($callback != '') { $callback = ", function(){\n{$callback}\n}"; } $str = "$({$element}).slideToggle({$speed}{$callback});"; return $str; } // -------------------------------------------------------------------- /** * Toggle * * Outputs a jQuery toggle event * * @access private * @param string - element * @return string */ function _toggle($element = 'this') { $element = $this->_prep_element($element); $str = "$({$element}).toggle();"; return $str; } // -------------------------------------------------------------------- /** * Toggle Class * * Outputs a jQuery toggle class event * * @access private * @param string - element * @return string */ function _toggleClass($element = 'this', $class='') { $element = $this->_prep_element($element); $str = "$({$element}).toggleClass(\"$class\");"; return $str; } // -------------------------------------------------------------------- /** * Show * * Outputs a jQuery show event * * @access private * @param string - element * @param string - One of 'slow', 'normal', 'fast', or time in milliseconds * @param string - Javascript callback function * @return string */ function _show($element = 'this', $speed = '', $callback = '') { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); if ($callback != '') { $callback = ", function(){\n{$callback}\n}"; } $str = "$({$element}).show({$speed}{$callback});"; return $str; } // -------------------------------------------------------------------- /** * Updater * * An Ajax call that populates the designated DOM node with * returned content * * @access private * @param string The element to attach the event to * @param string the controller to run the call against * @param string optional parameters * @return string */ function _updater($container = 'this', $controller, $options = '') { $container = $this->_prep_element($container); $controller = (strpos('://', $controller) === FALSE) ? $controller : $this->CI->config->site_url($controller); // ajaxStart and ajaxStop are better choices here... but this is a stop gap if ($this->CI->config->item('javascript_ajax_img') == '') { $loading_notifier = "Loading..."; } else { $loading_notifier = '<img src=\'' . $this->CI->config->slash_item('base_url') . $this->CI->config->item('javascript_ajax_img') . '\' alt=\'Loading\' />'; } $updater = "$($container).empty();\n"; // anything that was in... get it out $updater .= "\t\t$($container).prepend(\"$loading_notifier\");\n"; // to replace with an image $request_options = ''; if ($options != '') { $request_options .= ", {"; $request_options .= (is_array($options)) ? "'".implode("', '", $options)."'" : "'".str_replace(":", "':'", $options)."'"; $request_options .= "}"; } $updater .= "\t\t$($container).load('$controller'$request_options);"; return $updater; } // -------------------------------------------------------------------- // Pre-written handy stuff // -------------------------------------------------------------------- /** * Zebra tables * * @access private * @param string table name * @param string plugin location * @return string */ function _zebraTables($class = '', $odd = 'odd', $hover = '') { $class = ($class != '') ? '.'.$class : ''; $zebra = "\t\$(\"table{$class} tbody tr:nth-child(even)\").addClass(\"{$odd}\");"; $this->jquery_code_for_compile[] = $zebra; if ($hover != '') { $hover = $this->hover("table{$class} tbody tr", "$(this).addClass('hover');", "$(this).removeClass('hover');"); } return $zebra; } // -------------------------------------------------------------------- // Plugins // -------------------------------------------------------------------- /** * Corner Plugin * * http://www.malsup.com/jquery/corner/ * * @access public * @param string target * @return string */ function corner($element = '', $corner_style = '') { // may want to make this configurable down the road $corner_location = '/plugins/jquery.corner.js'; if ($corner_style != '') { $corner_style = '"'.$corner_style.'"'; } return "$(" . $this->_prep_element($element) . ").corner(".$corner_style.");"; } // -------------------------------------------------------------------- /** * modal window * * Load a thickbox modal window * * @access public * @return void */ function modal($src, $relative = FALSE) { $this->jquery_code_for_load[] = $this->external($src, $relative); } // -------------------------------------------------------------------- /** * Effect * * Load an Effect library * * @access public * @return void */ function effect($src, $relative = FALSE) { $this->jquery_code_for_load[] = $this->external($src, $relative); } // -------------------------------------------------------------------- /** * Plugin * * Load a plugin library * * @access public * @return void */ function plugin($src, $relative = FALSE) { $this->jquery_code_for_load[] = $this->external($src, $relative); } // -------------------------------------------------------------------- /** * UI * * Load a user interface library * * @access public * @return void */ function ui($src, $relative = FALSE) { $this->jquery_code_for_load[] = $this->external($src, $relative); } // -------------------------------------------------------------------- /** * Sortable * * Creates a jQuery sortable * * @access public * @return void */ function sortable($element, $options = array()) { if (count($options) > 0) { $sort_options = array(); foreach ($options as $k=>$v) { $sort_options[] = "\n\t\t".$k.': '.$v.""; } $sort_options = implode(",", $sort_options); } else { $sort_options = ''; } return "$(" . $this->_prep_element($element) . ").sortable({".$sort_options."\n\t});"; } // -------------------------------------------------------------------- /** * Table Sorter Plugin * * @access public * @param string table name * @param string plugin location * @return string */ function tablesorter($table = '', $options = '') { $this->jquery_code_for_compile[] = "\t$(" . $this->_prep_element($table) . ").tablesorter($options);\n"; } // -------------------------------------------------------------------- // Class functions // -------------------------------------------------------------------- /** * Add Event * * Constructs the syntax for an event, and adds to into the array for compilation * * @access private * @param string The element to attach the event to * @param string The code to execute * @param string The event to pass * @return string */ function _add_event($element, $js, $event) { if (is_array($js)) { $js = implode("\n\t\t", $js); } $event = "\n\t$(" . $this->_prep_element($element) . ").{$event}(function(){\n\t\t{$js}\n\t});\n"; $this->jquery_code_for_compile[] = $event; return $event; } // -------------------------------------------------------------------- /** * Compile * * As events are specified, they are stored in an array * This funciton compiles them all for output on a page * * @access private * @return string */ function _compile($view_var = 'script_foot', $script_tags = TRUE) { // External references $external_scripts = implode('', $this->jquery_code_for_load); $this->CI->load->vars(array('library_src' => $external_scripts)); if (count($this->jquery_code_for_compile) == 0 ) { // no inline references, let's just return return; } // Inline references $script = '$(document).ready(function() {' . "\n"; $script .= implode('', $this->jquery_code_for_compile); $script .= '});'; $output = ($script_tags === FALSE) ? $script : $this->inline($script); $this->CI->load->vars(array($view_var => $output)); } // -------------------------------------------------------------------- /** * Clear Compile * * Clears the array of script events collected for output * * @access public * @return void */ function _clear_compile() { $this->jquery_code_for_compile = array(); } // -------------------------------------------------------------------- /** * Document Ready * * A wrapper for writing document.ready() * * @access private * @return string */ function _document_ready($js) { if ( ! is_array($js)) { $js = array ($js); } foreach ($js as $script) { $this->jquery_code_for_compile[] = $script; } } // -------------------------------------------------------------------- /** * Script Tag * * Outputs the script tag that loads the jquery.js file into an HTML document * * @access public * @param string * @return string */ function script($library_src = '', $relative = FALSE) { $library_src = $this->external($library_src, $relative); $this->jquery_code_for_load[] = $library_src; return $library_src; } // -------------------------------------------------------------------- /** * Prep Element * * Puts HTML element in quotes for use in jQuery code * unless the supplied element is the Javascript 'this' * object, in which case no quotes are added * * @access public * @param string * @return string */ function _prep_element($element) { if ($element != 'this') { $element = '"'.$element.'"'; } return $element; } // -------------------------------------------------------------------- /** * Validate Speed * * Ensures the speed parameter is valid for jQuery * * @access private * @param string * @return string */ function _validate_speed($speed) { if (in_array($speed, array('slow', 'normal', 'fast'))) { $speed = '"'.$speed.'"'; } elseif (preg_match("/[^0-9]/", $speed)) { $speed = ''; } return $speed; } } /* End of file Jquery.php */ /* Location: ./system/libraries/Jquery.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Input.php
system/core/Input.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Input Class * * Pre-processes global input data for security * * @package CodeIgniter * @subpackage Libraries * @category Input * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/input.html */ class CI_Input { /** * IP address of the current user * * @var string */ var $ip_address = FALSE; /** * user agent (web browser) being used by the current user * * @var string */ var $user_agent = FALSE; /** * If FALSE, then $_GET will be set to an empty array * * @var bool */ var $_allow_get_array = TRUE; /** * If TRUE, then newlines are standardized * * @var bool */ var $_standardize_newlines = TRUE; /** * Determines whether the XSS filter is always active when GET, POST or COOKIE data is encountered * Set automatically based on config setting * * @var bool */ var $_enable_xss = FALSE; /** * Enables a CSRF cookie token to be set. * Set automatically based on config setting * * @var bool */ var $_enable_csrf = FALSE; /** * List of all HTTP request headers * * @var array */ protected $headers = array(); /** * Constructor * * Sets whether to globally enable the XSS processing * and whether to allow the $_GET array * * @return void */ public function __construct() { log_message('debug', "Input Class Initialized"); $this->_allow_get_array = (config_item('allow_get_array') === TRUE); $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); $this->_enable_csrf = (config_item('csrf_protection') === TRUE); global $SEC; $this->security =& $SEC; // Do we need the UTF-8 class? if (UTF8_ENABLED === TRUE) { global $UNI; $this->uni =& $UNI; } // Sanitize global arrays $this->_sanitize_globals(); } // -------------------------------------------------------------------- /** * Fetch from array * * This is a helper function to retrieve values from global arrays * * @access private * @param array * @param string * @param bool * @return string */ function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE) { if ( ! isset($array[$index])) { return FALSE; } if ($xss_clean === TRUE) { return $this->security->xss_clean($array[$index]); } return $array[$index]; } // -------------------------------------------------------------------- /** * Fetch an item from the GET array * * @access public * @param string * @param bool * @return string */ function get($index = NULL, $xss_clean = FALSE) { // Check if a field has been provided if ($index === NULL AND ! empty($_GET)) { $get = array(); // loop through the full _GET array foreach (array_keys($_GET) as $key) { $get[$key] = $this->_fetch_from_array($_GET, $key, $xss_clean); } return $get; } return $this->_fetch_from_array($_GET, $index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch an item from the POST array * * @access public * @param string * @param bool * @return string */ function post($index = NULL, $xss_clean = FALSE) { // Check if a field has been provided if ($index === NULL AND ! empty($_POST)) { $post = array(); // Loop through the full _POST array and return it foreach (array_keys($_POST) as $key) { $post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean); } return $post; } return $this->_fetch_from_array($_POST, $index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch an item from either the GET array or the POST * * @access public * @param string The index key * @param bool XSS cleaning * @return string */ function get_post($index = '', $xss_clean = FALSE) { if ( ! isset($_POST[$index]) ) { return $this->get($index, $xss_clean); } else { return $this->post($index, $xss_clean); } } // -------------------------------------------------------------------- /** * Fetch an item from the COOKIE array * * @access public * @param string * @param bool * @return string */ function cookie($index = '', $xss_clean = FALSE) { return $this->_fetch_from_array($_COOKIE, $index, $xss_clean); } // ------------------------------------------------------------------------ /** * Set cookie * * Accepts six parameter, or you can submit an associative * array in the first parameter containing all the values. * * @access public * @param mixed * @param string the value of the cookie * @param string the number of seconds until expiration * @param string the cookie domain. Usually: .yourdomain.com * @param string the cookie path * @param string the cookie prefix * @param bool true makes the cookie secure * @return void */ function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE) { if (is_array($name)) { // always leave 'name' in last place, as the loop will break otherwise, due to $$item foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'name') as $item) { if (isset($name[$item])) { $$item = $name[$item]; } } } if ($prefix == '' AND config_item('cookie_prefix') != '') { $prefix = config_item('cookie_prefix'); } if ($domain == '' AND config_item('cookie_domain') != '') { $domain = config_item('cookie_domain'); } if ($path == '/' AND config_item('cookie_path') != '/') { $path = config_item('cookie_path'); } if ($secure == FALSE AND config_item('cookie_secure') != FALSE) { $secure = config_item('cookie_secure'); } if ( ! is_numeric($expire)) { $expire = time() - 86500; } else { $expire = ($expire > 0) ? time() + $expire : 0; } setcookie($prefix.$name, $value, $expire, $path, $domain, $secure); } // -------------------------------------------------------------------- /** * Fetch an item from the SERVER array * * @access public * @param string * @param bool * @return string */ function server($index = '', $xss_clean = FALSE) { return $this->_fetch_from_array($_SERVER, $index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch the IP Address * * @return string */ public function ip_address() { if ($this->ip_address !== FALSE) { return $this->ip_address; } $proxy_ips = config_item('proxy_ips'); if ( ! empty($proxy_ips)) { $proxy_ips = explode(',', str_replace(' ', '', $proxy_ips)); foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP') as $header) { if (($spoof = $this->server($header)) !== FALSE) { // Some proxies typically list the whole chain of IP // addresses through which the client has reached us. // e.g. client_ip, proxy_ip1, proxy_ip2, etc. if (strpos($spoof, ',') !== FALSE) { $spoof = explode(',', $spoof, 2); $spoof = $spoof[0]; } if ( ! $this->valid_ip($spoof)) { $spoof = FALSE; } else { break; } } } $this->ip_address = ($spoof !== FALSE && in_array($_SERVER['REMOTE_ADDR'], $proxy_ips, TRUE)) ? $spoof : $_SERVER['REMOTE_ADDR']; } else { $this->ip_address = $_SERVER['REMOTE_ADDR']; } if ( ! $this->valid_ip($this->ip_address)) { $this->ip_address = '0.0.0.0'; } return $this->ip_address; } // -------------------------------------------------------------------- /** * Validate IP Address * * @access public * @param string * @param string ipv4 or ipv6 * @return bool */ public function valid_ip($ip, $which = '') { $which = strtolower($which); // First check if filter_var is available if (is_callable('filter_var')) { switch ($which) { case 'ipv4': $flag = FILTER_FLAG_IPV4; break; case 'ipv6': $flag = FILTER_FLAG_IPV6; break; default: $flag = ''; break; } return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flag); } if ($which !== 'ipv6' && $which !== 'ipv4') { if (strpos($ip, ':') !== FALSE) { $which = 'ipv6'; } elseif (strpos($ip, '.') !== FALSE) { $which = 'ipv4'; } else { return FALSE; } } $func = '_valid_'.$which; return $this->$func($ip); } // -------------------------------------------------------------------- /** * Validate IPv4 Address * * Updated version suggested by Geert De Deckere * * @access protected * @param string * @return bool */ protected function _valid_ipv4($ip) { $ip_segments = explode('.', $ip); // Always 4 segments needed if (count($ip_segments) !== 4) { return FALSE; } // IP can not start with 0 if ($ip_segments[0][0] == '0') { return FALSE; } // Check each segment foreach ($ip_segments as $segment) { // IP segments must be digits and can not be // longer than 3 digits or greater then 255 if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3) { return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * Validate IPv6 Address * * @access protected * @param string * @return bool */ protected function _valid_ipv6($str) { // 8 groups, separated by : // 0-ffff per group // one set of consecutive 0 groups can be collapsed to :: $groups = 8; $collapsed = FALSE; $chunks = array_filter( preg_split('/(:{1,2})/', $str, NULL, PREG_SPLIT_DELIM_CAPTURE) ); // Rule out easy nonsense if (current($chunks) == ':' OR end($chunks) == ':') { return FALSE; } // PHP supports IPv4-mapped IPv6 addresses, so we'll expect those as well if (strpos(end($chunks), '.') !== FALSE) { $ipv4 = array_pop($chunks); if ( ! $this->_valid_ipv4($ipv4)) { return FALSE; } $groups--; } while ($seg = array_pop($chunks)) { if ($seg[0] == ':') { if (--$groups == 0) { return FALSE; // too many groups } if (strlen($seg) > 2) { return FALSE; // long separator } if ($seg == '::') { if ($collapsed) { return FALSE; // multiple collapsed } $collapsed = TRUE; } } elseif (preg_match("/[^0-9a-f]/i", $seg) OR strlen($seg) > 4) { return FALSE; // invalid segment } } return $collapsed OR $groups == 1; } // -------------------------------------------------------------------- /** * User Agent * * @access public * @return string */ function user_agent() { if ($this->user_agent !== FALSE) { return $this->user_agent; } $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT']; return $this->user_agent; } // -------------------------------------------------------------------- /** * Sanitize Globals * * This function does the following: * * Unsets $_GET data (if query strings are not enabled) * * Unsets all globals if register_globals is enabled * * Standardizes newline characters to \n * * @access private * @return void */ function _sanitize_globals() { // It would be "wrong" to unset any of these GLOBALS. $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST', '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA', 'system_folder', 'application_folder', 'BM', 'EXT', 'CFG', 'URI', 'RTR', 'OUT', 'IN'); // Unset globals for securiy. // This is effectively the same as register_globals = off foreach (array($_GET, $_POST, $_COOKIE) as $global) { if ( ! is_array($global)) { if ( ! in_array($global, $protected)) { global $$global; $$global = NULL; } } else { foreach ($global as $key => $val) { if ( ! in_array($key, $protected)) { global $$key; $$key = NULL; } } } } // Is $_GET data allowed? If not we'll set the $_GET to an empty array if ($this->_allow_get_array == FALSE) { $_GET = array(); } else { if (is_array($_GET) AND count($_GET) > 0) { foreach ($_GET as $key => $val) { $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } } // Clean $_POST Data if (is_array($_POST) AND count($_POST) > 0) { foreach ($_POST as $key => $val) { $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } // Clean $_COOKIE Data if (is_array($_COOKIE) AND count($_COOKIE) > 0) { // Also get rid of specially treated cookies that might be set by a server // or silly application, that are of no use to a CI application anyway // but that when present will trip our 'Disallowed Key Characters' alarm // http://www.ietf.org/rfc/rfc2109.txt // note that the key names below are single quoted strings, and are not PHP variables unset($_COOKIE['$Version']); unset($_COOKIE['$Path']); unset($_COOKIE['$Domain']); foreach ($_COOKIE as $key => $val) { $_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } // Sanitize PHP_SELF $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']); // CSRF Protection check on HTTP requests if ($this->_enable_csrf == TRUE && ! $this->is_cli_request()) { $this->security->csrf_verify(); } log_message('debug', "Global POST and COOKIE data sanitized"); } // -------------------------------------------------------------------- /** * Clean Input Data * * This is a helper function. It escapes data and * standardizes newline characters to \n * * @access private * @param string * @return string */ function _clean_input_data($str) { if (is_array($str)) { $new_array = array(); foreach ($str as $key => $val) { $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } return $new_array; } /* We strip slashes if magic quotes is on to keep things consistent NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and it will probably not exist in future versions at all. */ if ( ! is_php('5.4') && get_magic_quotes_gpc()) { $str = stripslashes($str); } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { $str = $this->uni->clean_string($str); } // Remove control characters $str = remove_invisible_characters($str); // Should we filter the input data? if ($this->_enable_xss === TRUE) { $str = $this->security->xss_clean($str); } // Standardize newlines if needed if ($this->_standardize_newlines == TRUE) { if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str); } } return $str; } // -------------------------------------------------------------------- /** * Clean Keys * * This is a helper function. To prevent malicious users * from trying to exploit keys we make sure that keys are * only named with alpha-numeric text and a few other items. * * @access private * @param string * @return string */ function _clean_input_keys($str) { if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str)) { exit('Disallowed Key Characters.'); } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { $str = $this->uni->clean_string($str); } return $str; } // -------------------------------------------------------------------- /** * Request Headers * * In Apache, you can simply call apache_request_headers(), however for * people running other webservers the function is undefined. * * @param bool XSS cleaning * * @return array */ public function request_headers($xss_clean = FALSE) { // Look at Apache go! if (function_exists('apache_request_headers')) { $headers = apache_request_headers(); } else { $headers['Content-Type'] = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE'); foreach ($_SERVER as $key => $val) { if (strncmp($key, 'HTTP_', 5) === 0) { $headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean); } } } // take SOME_HEADER and turn it into Some-Header foreach ($headers as $key => $val) { $key = str_replace('_', ' ', strtolower($key)); $key = str_replace(' ', '-', ucwords($key)); $this->headers[$key] = $val; } return $this->headers; } // -------------------------------------------------------------------- /** * Get Request Header * * Returns the value of a single member of the headers class member * * @param string array key for $this->headers * @param boolean XSS Clean or not * @return mixed FALSE on failure, string on success */ public function get_request_header($index, $xss_clean = FALSE) { if (empty($this->headers)) { $this->request_headers(); } if ( ! isset($this->headers[$index])) { return FALSE; } if ($xss_clean === TRUE) { return $this->security->xss_clean($this->headers[$index]); } return $this->headers[$index]; } // -------------------------------------------------------------------- /** * Is ajax Request? * * Test to see if a request contains the HTTP_X_REQUESTED_WITH header * * @return boolean */ public function is_ajax_request() { return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest'); } // -------------------------------------------------------------------- /** * Is cli Request? * * Test to see if a request was made from the command line * * @return bool */ public function is_cli_request() { return (php_sapi_name() === 'cli' OR defined('STDIN')); } } /* End of file Input.php */ /* Location: ./system/core/Input.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Loader.php
system/core/Loader.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Loader Class * * Loads views and files * * @package CodeIgniter * @subpackage Libraries * @author ExpressionEngine Dev Team * @category Loader * @link http://codeigniter.com/user_guide/libraries/loader.html */ class CI_Loader { // All these are set automatically. Don't mess with them. /** * Nesting level of the output buffering mechanism * * @var int * @access protected */ protected $_ci_ob_level; /** * List of paths to load views from * * @var array * @access protected */ protected $_ci_view_paths = array(); /** * List of paths to load libraries from * * @var array * @access protected */ protected $_ci_library_paths = array(); /** * List of paths to load models from * * @var array * @access protected */ protected $_ci_model_paths = array(); /** * List of paths to load helpers from * * @var array * @access protected */ protected $_ci_helper_paths = array(); /** * List of loaded base classes * Set by the controller class * * @var array * @access protected */ protected $_base_classes = array(); // Set by the controller class /** * List of cached variables * * @var array * @access protected */ protected $_ci_cached_vars = array(); /** * List of loaded classes * * @var array * @access protected */ protected $_ci_classes = array(); /** * List of loaded files * * @var array * @access protected */ protected $_ci_loaded_files = array(); /** * List of loaded models * * @var array * @access protected */ protected $_ci_models = array(); /** * List of loaded helpers * * @var array * @access protected */ protected $_ci_helpers = array(); /** * List of class name mappings * * @var array * @access protected */ protected $_ci_varmap = array('unit_test' => 'unit', 'user_agent' => 'agent'); /** * Constructor * * Sets the path to the view files and gets the initial output buffering level */ public function __construct() { $this->_ci_ob_level = ob_get_level(); $this->_ci_library_paths = array(APPPATH, BASEPATH); $this->_ci_helper_paths = array(APPPATH, BASEPATH); $this->_ci_model_paths = array(APPPATH); $this->_ci_view_paths = array(APPPATH.'views/' => TRUE); log_message('debug', "Loader Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize the Loader * * This method is called once in CI_Controller. * * @param array * @return object */ public function initialize() { $this->_ci_classes = array(); $this->_ci_loaded_files = array(); $this->_ci_models = array(); $this->_base_classes =& is_loaded(); $this->_ci_autoloader(); return $this; } // -------------------------------------------------------------------- /** * Is Loaded * * A utility function to test if a class is in the self::$_ci_classes array. * This function returns the object name if the class tested for is loaded, * and returns FALSE if it isn't. * * It is mainly used in the form_helper -> _get_validation_object() * * @param string class being checked for * @return mixed class object name on the CI SuperObject or FALSE */ public function is_loaded($class) { if (isset($this->_ci_classes[$class])) { return $this->_ci_classes[$class]; } return FALSE; } // -------------------------------------------------------------------- /** * Class Loader * * This function lets users load and instantiate classes. * It is designed to be called from a user's app controllers. * * @param string the name of the class * @param mixed the optional parameters * @param string an optional object name * @return void */ public function library($library = '', $params = NULL, $object_name = NULL) { if (is_array($library)) { foreach ($library as $class) { $this->library($class, $params); } return; } if ($library == '' OR isset($this->_base_classes[$library])) { return FALSE; } if ( ! is_null($params) && ! is_array($params)) { $params = NULL; } $this->_ci_load_class($library, $params, $object_name); } // -------------------------------------------------------------------- /** * Model Loader * * This function lets users load and instantiate models. * * @param string the name of the class * @param string name for the model * @param bool database connection * @return void */ public function model($model, $name = '', $db_conn = FALSE) { if (is_array($model)) { foreach ($model as $babe) { $this->model($babe); } return; } if ($model == '') { return; } $path = ''; // Is the model in a sub-folder? If so, parse out the filename and path. if (($last_slash = strrpos($model, '/')) !== FALSE) { // The path is in front of the last slash $path = substr($model, 0, $last_slash + 1); // And the model name behind it $model = substr($model, $last_slash + 1); } if ($name == '') { $name = $model; } if (in_array($name, $this->_ci_models, TRUE)) { return; } $CI =& get_instance(); if (isset($CI->$name)) { show_error('The model name you are loading is the name of a resource that is already being used: '.$name); } $model = strtolower($model); foreach ($this->_ci_model_paths as $mod_path) { if ( ! file_exists($mod_path.'models/'.$path.$model.'.php')) { continue; } if ($db_conn !== FALSE AND ! class_exists('CI_DB')) { if ($db_conn === TRUE) { $db_conn = ''; } $CI->load->database($db_conn, FALSE, TRUE); } if ( ! class_exists('CI_Model')) { load_class('Model', 'core'); } require_once($mod_path.'models/'.$path.$model.'.php'); $model = ucfirst($model); $CI->$name = new $model(); $this->_ci_models[] = $name; return; } // couldn't find the model show_error('Unable to locate the model you have specified: '.$model); } // -------------------------------------------------------------------- /** * Database Loader * * @param string the DB credentials * @param bool whether to return the DB object * @param bool whether to enable active record (this allows us to override the config setting) * @return object */ public function database($params = '', $return = FALSE, $active_record = NULL) { // Grab the super object $CI =& get_instance(); // Do we even need to load the database class? if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db)) { return FALSE; } require_once(BASEPATH.'database/DB.php'); if ($return === TRUE) { return DB($params, $active_record); } // Initialize the db variable. Needed to prevent // reference errors with some configurations $CI->db = ''; // Load the DB class $CI->db =& DB($params, $active_record); } // -------------------------------------------------------------------- /** * Load the Utilities Class * * @return string */ public function dbutil() { if ( ! class_exists('CI_DB')) { $this->database(); } $CI =& get_instance(); // for backwards compatibility, load dbforge so we can extend dbutils off it // this use is deprecated and strongly discouraged $CI->load->dbforge(); require_once(BASEPATH.'database/DB_utility.php'); require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility.php'); $class = 'CI_DB_'.$CI->db->dbdriver.'_utility'; $CI->dbutil = new $class(); } // -------------------------------------------------------------------- /** * Load the Database Forge Class * * @return string */ public function dbforge() { if ( ! class_exists('CI_DB')) { $this->database(); } $CI =& get_instance(); require_once(BASEPATH.'database/DB_forge.php'); require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_forge.php'); $class = 'CI_DB_'.$CI->db->dbdriver.'_forge'; $CI->dbforge = new $class(); } // -------------------------------------------------------------------- /** * Load View * * This function is used to load a "view" file. It has three parameters: * * 1. The name of the "view" file to be included. * 2. An associative array of data to be extracted for use in the view. * 3. TRUE/FALSE - whether to return the data or load it. In * some cases it's advantageous to be able to return data so that * a developer can process it in some way. * * @param string * @param array * @param bool * @return void */ public function view($view, $vars = array(), $return = FALSE) { return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return)); } // -------------------------------------------------------------------- /** * Load File * * This is a generic file loader * * @param string * @param bool * @return string */ public function file($path, $return = FALSE) { return $this->_ci_load(array('_ci_path' => $path, '_ci_return' => $return)); } // -------------------------------------------------------------------- /** * Set Variables * * Once variables are set they become available within * the controller class and its "view" files. * * @param array * @param string * @return void */ public function vars($vars = array(), $val = '') { if ($val != '' AND is_string($vars)) { $vars = array($vars => $val); } $vars = $this->_ci_object_to_array($vars); if (is_array($vars) AND count($vars) > 0) { foreach ($vars as $key => $val) { $this->_ci_cached_vars[$key] = $val; } } } // -------------------------------------------------------------------- /** * Get Variable * * Check if a variable is set and retrieve it. * * @param array * @return void */ public function get_var($key) { return isset($this->_ci_cached_vars[$key]) ? $this->_ci_cached_vars[$key] : NULL; } // -------------------------------------------------------------------- /** * Load Helper * * This function loads the specified helper file. * * @param mixed * @return void */ public function helper($helpers = array()) { foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) { if (isset($this->_ci_helpers[$helper])) { continue; } $ext_helper = APPPATH.'helpers/'.config_item('subclass_prefix').$helper.'.php'; // Is this a helper extension request? if (file_exists($ext_helper)) { $base_helper = BASEPATH.'helpers/'.$helper.'.php'; if ( ! file_exists($base_helper)) { show_error('Unable to load the requested file: helpers/'.$helper.'.php'); } include_once($ext_helper); include_once($base_helper); $this->_ci_helpers[$helper] = TRUE; log_message('debug', 'Helper loaded: '.$helper); continue; } // Try to load the helper foreach ($this->_ci_helper_paths as $path) { if (file_exists($path.'helpers/'.$helper.'.php')) { include_once($path.'helpers/'.$helper.'.php'); $this->_ci_helpers[$helper] = TRUE; log_message('debug', 'Helper loaded: '.$helper); break; } } // unable to load the helper if ( ! isset($this->_ci_helpers[$helper])) { show_error('Unable to load the requested file: helpers/'.$helper.'.php'); } } } // -------------------------------------------------------------------- /** * Load Helpers * * This is simply an alias to the above function in case the * user has written the plural form of this function. * * @param array * @return void */ public function helpers($helpers = array()) { $this->helper($helpers); } // -------------------------------------------------------------------- /** * Loads a language file * * @param array * @param string * @return void */ public function language($file = array(), $lang = '') { $CI =& get_instance(); if ( ! is_array($file)) { $file = array($file); } foreach ($file as $langfile) { $CI->lang->load($langfile, $lang); } } // -------------------------------------------------------------------- /** * Loads a config file * * @param string * @param bool * @param bool * @return void */ public function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { $CI =& get_instance(); $CI->config->load($file, $use_sections, $fail_gracefully); } // -------------------------------------------------------------------- /** * Driver * * Loads a driver library * * @param string the name of the class * @param mixed the optional parameters * @param string an optional object name * @return void */ public function driver($library = '', $params = NULL, $object_name = NULL) { if ( ! class_exists('CI_Driver_Library')) { // we aren't instantiating an object here, that'll be done by the Library itself require BASEPATH.'libraries/Driver.php'; } if ($library == '') { return FALSE; } // We can save the loader some time since Drivers will *always* be in a subfolder, // and typically identically named to the library if ( ! strpos($library, '/')) { $library = ucfirst($library).'/'.$library; } return $this->library($library, $params, $object_name); } // -------------------------------------------------------------------- /** * Add Package Path * * Prepends a parent path to the library, model, helper, and config path arrays * * @param string * @param boolean * @return void */ public function add_package_path($path, $view_cascade=TRUE) { $path = rtrim($path, '/').'/'; array_unshift($this->_ci_library_paths, $path); array_unshift($this->_ci_model_paths, $path); array_unshift($this->_ci_helper_paths, $path); $this->_ci_view_paths = array($path.'views/' => $view_cascade) + $this->_ci_view_paths; // Add config file path $config =& $this->_ci_get_component('config'); array_unshift($config->_config_paths, $path); } // -------------------------------------------------------------------- /** * Get Package Paths * * Return a list of all package paths, by default it will ignore BASEPATH. * * @param string * @return void */ public function get_package_paths($include_base = FALSE) { return $include_base === TRUE ? $this->_ci_library_paths : $this->_ci_model_paths; } // -------------------------------------------------------------------- /** * Remove Package Path * * Remove a path from the library, model, and helper path arrays if it exists * If no path is provided, the most recently added path is removed. * * @param type * @param bool * @return type */ public function remove_package_path($path = '', $remove_config_path = TRUE) { $config =& $this->_ci_get_component('config'); if ($path == '') { $void = array_shift($this->_ci_library_paths); $void = array_shift($this->_ci_model_paths); $void = array_shift($this->_ci_helper_paths); $void = array_shift($this->_ci_view_paths); $void = array_shift($config->_config_paths); } else { $path = rtrim($path, '/').'/'; foreach (array('_ci_library_paths', '_ci_model_paths', '_ci_helper_paths') as $var) { if (($key = array_search($path, $this->{$var})) !== FALSE) { unset($this->{$var}[$key]); } } if (isset($this->_ci_view_paths[$path.'views/'])) { unset($this->_ci_view_paths[$path.'views/']); } if (($key = array_search($path, $config->_config_paths)) !== FALSE) { unset($config->_config_paths[$key]); } } // make sure the application default paths are still in the array $this->_ci_library_paths = array_unique(array_merge($this->_ci_library_paths, array(APPPATH, BASEPATH))); $this->_ci_helper_paths = array_unique(array_merge($this->_ci_helper_paths, array(APPPATH, BASEPATH))); $this->_ci_model_paths = array_unique(array_merge($this->_ci_model_paths, array(APPPATH))); $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(APPPATH.'views/' => TRUE)); $config->_config_paths = array_unique(array_merge($config->_config_paths, array(APPPATH))); } // -------------------------------------------------------------------- /** * Loader * * This function is used to load views and files. * Variables are prefixed with _ci_ to avoid symbol collision with * variables made available to view files * * @param array * @return void */ protected function _ci_load($_ci_data) { // Set the default data variables foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val) { $$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val]; } $file_exists = FALSE; // Set the path to the requested file if ($_ci_path != '') { $_ci_x = explode('/', $_ci_path); $_ci_file = end($_ci_x); } else { $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION); $_ci_file = ($_ci_ext == '') ? $_ci_view.'.php' : $_ci_view; foreach ($this->_ci_view_paths as $view_file => $cascade) { if (file_exists($view_file.$_ci_file)) { $_ci_path = $view_file.$_ci_file; $file_exists = TRUE; break; } if ( ! $cascade) { break; } } } if ( ! $file_exists && ! file_exists($_ci_path)) { show_error('Unable to load the requested file: '.$_ci_file); } // This allows anything loaded using $this->load (views, files, etc.) // to become accessible from within the Controller and Model functions. $_ci_CI =& get_instance(); foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var) { if ( ! isset($this->$_ci_key)) { $this->$_ci_key =& $_ci_CI->$_ci_key; } } /* * Extract and cache variables * * You can either set variables using the dedicated $this->load_vars() * function or via the second parameter of this function. We'll merge * the two types and cache them so that views that are embedded within * other views can have access to these variables. */ if (is_array($_ci_vars)) { $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); } extract($this->_ci_cached_vars); /* * Buffer the output * * We buffer the output for two reasons: * 1. Speed. You get a significant speed boost. * 2. So that the final rendered template can be * post-processed by the output class. Why do we * need post processing? For one thing, in order to * show the elapsed page load time. Unless we * can intercept the content right before it's sent to * the browser and then stop the timer it won't be accurate. */ ob_start(); // If the PHP installation does not support short tags we'll // do a little string replacement, changing the short tags // to standard PHP echo statements. if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE) { echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($_ci_path)))); } else { include($_ci_path); // include() vs include_once() allows for multiple views with the same name } log_message('debug', 'File loaded: '.$_ci_path); // Return the file data if requested if ($_ci_return === TRUE) { $buffer = ob_get_contents(); @ob_end_clean(); return $buffer; } /* * Flush the buffer... or buff the flusher? * * In order to permit views to be nested within * other views, we need to flush the content back out whenever * we are beyond the first level of output buffering so that * it can be seen and included properly by the first included * template and any subsequent ones. Oy! * */ if (ob_get_level() > $this->_ci_ob_level + 1) { ob_end_flush(); } else { $_ci_CI->output->append_output(ob_get_contents()); @ob_end_clean(); } } // -------------------------------------------------------------------- /** * Load class * * This function loads the requested class. * * @param string the item that is being loaded * @param mixed any additional parameters * @param string an optional object name * @return void */ protected function _ci_load_class($class, $params = NULL, $object_name = NULL) { // Get the class name, and while we're at it trim any slashes. // The directory path can be included as part of the class name, // but we don't want a leading slash $class = str_replace('.php', '', trim($class, '/')); // Was the path included with the class name? // We look for a slash to determine this $subdir = ''; if (($last_slash = strrpos($class, '/')) !== FALSE) { // Extract the path $subdir = substr($class, 0, $last_slash + 1); // Get the filename from the path $class = substr($class, $last_slash + 1); } // We'll test for both lowercase and capitalized versions of the file name foreach (array(ucfirst($class), strtolower($class)) as $class) { $subclass = APPPATH.'libraries/'.$subdir.config_item('subclass_prefix').$class.'.php'; // Is this a class extension request? if (file_exists($subclass)) { $baseclass = BASEPATH.'libraries/'.ucfirst($class).'.php'; if ( ! file_exists($baseclass)) { log_message('error', "Unable to load the requested class: ".$class); show_error("Unable to load the requested class: ".$class); } // Safety: Was the class already loaded by a previous call? if (in_array($subclass, $this->_ci_loaded_files)) { // Before we deem this to be a duplicate request, let's see // if a custom object name is being supplied. If so, we'll // return a new instance of the object if ( ! is_null($object_name)) { $CI =& get_instance(); if ( ! isset($CI->$object_name)) { return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); } } $is_duplicate = TRUE; log_message('debug', $class." class already loaded. Second attempt ignored."); return; } include_once($baseclass); include_once($subclass); $this->_ci_loaded_files[] = $subclass; return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); } // Lets search for the requested library file and load it. $is_duplicate = FALSE; foreach ($this->_ci_library_paths as $path) { $filepath = $path.'libraries/'.$subdir.$class.'.php'; // Does the file exist? No? Bummer... if ( ! file_exists($filepath)) { continue; } // Safety: Was the class already loaded by a previous call? if (in_array($filepath, $this->_ci_loaded_files)) { // Before we deem this to be a duplicate request, let's see // if a custom object name is being supplied. If so, we'll // return a new instance of the object if ( ! is_null($object_name)) { $CI =& get_instance(); if ( ! isset($CI->$object_name)) { return $this->_ci_init_class($class, '', $params, $object_name); } } $is_duplicate = TRUE; log_message('debug', $class." class already loaded. Second attempt ignored."); return; } include_once($filepath); $this->_ci_loaded_files[] = $filepath; return $this->_ci_init_class($class, '', $params, $object_name); } } // END FOREACH // One last attempt. Maybe the library is in a subdirectory, but it wasn't specified? if ($subdir == '') { $path = strtolower($class).'/'.$class; return $this->_ci_load_class($path, $params); } // If we got this far we were unable to find the requested class. // We do not issue errors if the load call failed due to a duplicate request if ($is_duplicate == FALSE) { log_message('error', "Unable to load the requested class: ".$class); show_error("Unable to load the requested class: ".$class); } } // -------------------------------------------------------------------- /** * Instantiates a class * * @param string * @param string * @param bool * @param string an optional object name * @return null */ protected function _ci_init_class($class, $prefix = '', $config = FALSE, $object_name = NULL) { // Is there an associated config file for this class? Note: these should always be lowercase if ($config === NULL) { // Fetch the config paths containing any package paths $config_component = $this->_ci_get_component('config'); if (is_array($config_component->_config_paths)) { // Break on the first found file, thus package files // are not overridden by default paths foreach ($config_component->_config_paths as $path) { // We test for both uppercase and lowercase, for servers that // are case-sensitive with regard to file names. Check for environment // first, global next if (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php')) { include($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'); break; } elseif (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php')) { include($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'); break; } elseif (file_exists($path .'config/'.strtolower($class).'.php')) { include($path .'config/'.strtolower($class).'.php'); break; } elseif (file_exists($path .'config/'.ucfirst(strtolower($class)).'.php')) { include($path .'config/'.ucfirst(strtolower($class)).'.php'); break; } } } } if ($prefix == '') { if (class_exists('CI_'.$class)) { $name = 'CI_'.$class; } elseif (class_exists(config_item('subclass_prefix').$class)) { $name = config_item('subclass_prefix').$class; } else { $name = $class; } } else { $name = $prefix.$class; } // Is the class name valid? if ( ! class_exists($name)) { log_message('error', "Non-existent class: ".$name); show_error("Non-existent class: ".$class); } // Set the variable name we will assign the class to // Was a custom class name supplied? If so we'll use it $class = strtolower($class); if (is_null($object_name)) { $classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class]; } else { $classvar = $object_name; } // Save the class name and object name $this->_ci_classes[$class] = $classvar; // Instantiate the class $CI =& get_instance(); if ($config !== NULL) { $CI->$classvar = new $name($config); } else { $CI->$classvar = new $name; } } // -------------------------------------------------------------------- /** * Autoloader * * The config/autoload.php file contains an array that permits sub-systems, * libraries, and helpers to be loaded automatically. * * @param array * @return void */ private function _ci_autoloader() { if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'); } else { include(APPPATH.'config/autoload.php'); } if ( ! isset($autoload)) { return FALSE; } // Autoload packages if (isset($autoload['packages'])) { foreach ($autoload['packages'] as $package_path) { $this->add_package_path($package_path); } } // Load any custom config file if (count($autoload['config']) > 0) { $CI =& get_instance(); foreach ($autoload['config'] as $key => $val) { $CI->config->load($val); } } // Autoload helpers and languages foreach (array('helper', 'language') as $type) { if (isset($autoload[$type]) AND count($autoload[$type]) > 0) { $this->$type($autoload[$type]); } } // A little tweak to remain backward compatible // The $autoload['core'] item was deprecated if ( ! isset($autoload['libraries']) AND isset($autoload['core'])) { $autoload['libraries'] = $autoload['core']; } // Load libraries if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0) { // Load the database driver. if (in_array('database', $autoload['libraries'])) { $this->database(); $autoload['libraries'] = array_diff($autoload['libraries'], array('database')); } // Load all other libraries foreach ($autoload['libraries'] as $item) { $this->library($item); } } // Autoload models if (isset($autoload['model'])) { $this->model($autoload['model']); } } // -------------------------------------------------------------------- /** * Object to Array * * Takes an object as input and converts the class variables to array key/vals * * @param object * @return array */ protected function _ci_object_to_array($object) { return (is_object($object)) ? get_object_vars($object) : $object; } // -------------------------------------------------------------------- /** * Get a reference to a specific library or model * * @param string * @return bool */ protected function &_ci_get_component($component) { $CI =& get_instance(); return $CI->$component; } // -------------------------------------------------------------------- /** * Prep filename * * This function preps the name of various items to make loading them more reliable. * * @param mixed * @param string * @return array */ protected function _ci_prep_filename($filename, $extension) { if ( ! is_array($filename)) { return array(strtolower(str_replace('.php', '', str_replace($extension, '', $filename)).$extension)); } else { foreach ($filename as $key => $val) { $filename[$key] = strtolower(str_replace('.php', '', str_replace($extension, '', $val)).$extension); } return $filename; } } } /* End of file Loader.php */ /* Location: ./system/core/Loader.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Utf8.php
system/core/Utf8.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0 * @filesource */ // ------------------------------------------------------------------------ /** * Utf8 Class * * Provides support for UTF-8 environments * * @package CodeIgniter * @subpackage Libraries * @category UTF-8 * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/utf8.html */ class CI_Utf8 { /** * Constructor * * Determines if UTF-8 support is to be enabled * */ function __construct() { log_message('debug', "Utf8 Class Initialized"); global $CFG; if ( preg_match('/./u', 'é') === 1 // PCRE must support UTF-8 AND function_exists('iconv') // iconv must be installed AND ini_get('mbstring.func_overload') != 1 // Multibyte string function overloading cannot be enabled AND $CFG->item('charset') == 'UTF-8' // Application charset must be UTF-8 ) { log_message('debug', "UTF-8 Support Enabled"); define('UTF8_ENABLED', TRUE); // set internal encoding for multibyte string functions if necessary // and set a flag so we don't have to repeatedly use extension_loaded() // or function_exists() if (extension_loaded('mbstring')) { define('MB_ENABLED', TRUE); mb_internal_encoding('UTF-8'); } else { define('MB_ENABLED', FALSE); } } else { log_message('debug', "UTF-8 Support Disabled"); define('UTF8_ENABLED', FALSE); } } // -------------------------------------------------------------------- /** * Clean UTF-8 strings * * Ensures strings are UTF-8 * * @access public * @param string * @return string */ function clean_string($str) { if ($this->_is_ascii($str) === FALSE) { $str = @iconv('UTF-8', 'UTF-8//IGNORE', $str); } return $str; } // -------------------------------------------------------------------- /** * Remove ASCII control characters * * Removes all ASCII control characters except horizontal tabs, * line feeds, and carriage returns, as all others can cause * problems in XML * * @access public * @param string * @return string */ function safe_ascii_for_xml($str) { return remove_invisible_characters($str, FALSE); } // -------------------------------------------------------------------- /** * Convert to UTF-8 * * Attempts to convert a string to UTF-8 * * @access public * @param string * @param string - input encoding * @return string */ function convert_to_utf8($str, $encoding) { if (function_exists('iconv')) { $str = @iconv($encoding, 'UTF-8', $str); } elseif (function_exists('mb_convert_encoding')) { $str = @mb_convert_encoding($str, 'UTF-8', $encoding); } else { return FALSE; } return $str; } // -------------------------------------------------------------------- /** * Is ASCII? * * Tests if a string is standard 7-bit ASCII or not * * @access public * @param string * @return bool */ function _is_ascii($str) { return (preg_match('/[^\x00-\x7F]/S', $str) == 0); } // -------------------------------------------------------------------- } // End Utf8 Class /* End of file Utf8.php */ /* Location: ./system/core/Utf8.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/URI.php
system/core/URI.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * URI Class * * Parses URIs and determines routing * * @package CodeIgniter * @subpackage Libraries * @category URI * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/uri.html */ class CI_URI { /** * List of cached uri segments * * @var array * @access public */ var $keyval = array(); /** * Current uri string * * @var string * @access public */ var $uri_string; /** * List of uri segments * * @var array * @access public */ var $segments = array(); /** * Re-indexed list of uri segments * Starts at 1 instead of 0 * * @var array * @access public */ var $rsegments = array(); /** * Constructor * * Simply globalizes the $RTR object. The front * loads the Router class early on so it's not available * normally as other classes are. * * @access public */ function __construct() { $this->config =& load_class('Config', 'core'); log_message('debug', "URI Class Initialized"); } // -------------------------------------------------------------------- /** * Get the URI String * * @access private * @return string */ function _fetch_uri_string() { if (strtoupper($this->config->item('uri_protocol')) == 'AUTO') { // Is the request coming from the command line? if (php_sapi_name() == 'cli' or defined('STDIN')) { $this->_set_uri_string($this->_parse_cli_args()); return; } // Let's try the REQUEST_URI first, this will work in most situations if ($uri = $this->_detect_uri()) { $this->_set_uri_string($uri); return; } // Is there a PATH_INFO variable? // Note: some servers seem to have trouble with getenv() so we'll test it two ways $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO'); if (trim($path, '/') != '' && $path != "/".SELF) { $this->_set_uri_string($path); return; } // No PATH_INFO?... What about QUERY_STRING? $path = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING'); if (trim($path, '/') != '') { $this->_set_uri_string($path); return; } // As a last ditch effort lets try using the $_GET array if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '') { $this->_set_uri_string(key($_GET)); return; } // We've exhausted all our options... $this->uri_string = ''; return; } $uri = strtoupper($this->config->item('uri_protocol')); if ($uri == 'REQUEST_URI') { $this->_set_uri_string($this->_detect_uri()); return; } elseif ($uri == 'CLI') { $this->_set_uri_string($this->_parse_cli_args()); return; } $path = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri); $this->_set_uri_string($path); } // -------------------------------------------------------------------- /** * Set the URI String * * @access public * @param string * @return string */ function _set_uri_string($str) { // Filter out control characters $str = remove_invisible_characters($str, FALSE); // If the URI contains only a slash we'll kill it $this->uri_string = ($str == '/') ? '' : $str; } // -------------------------------------------------------------------- /** * Detects the URI * * This function will detect the URI automatically and fix the query string * if necessary. * * @access private * @return string */ private function _detect_uri() { if ( ! isset($_SERVER['REQUEST_URI']) OR ! isset($_SERVER['SCRIPT_NAME'])) { return ''; } $uri = $_SERVER['REQUEST_URI']; if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0) { $uri = substr($uri, strlen($_SERVER['SCRIPT_NAME'])); } elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0) { $uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME']))); } // This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct // URI is found, and also fixes the QUERY_STRING server var and $_GET array. if (strncmp($uri, '?/', 2) === 0) { $uri = substr($uri, 2); } $parts = preg_split('#\?#i', $uri, 2); $uri = $parts[0]; if (isset($parts[1])) { $_SERVER['QUERY_STRING'] = $parts[1]; parse_str($_SERVER['QUERY_STRING'], $_GET); } else { $_SERVER['QUERY_STRING'] = ''; $_GET = array(); } if ($uri == '/' || empty($uri)) { return '/'; } $uri = parse_url($uri, PHP_URL_PATH); // Do some final cleaning of the URI and return it return str_replace(array('//', '../'), '/', trim($uri, '/')); } // -------------------------------------------------------------------- /** * Parse cli arguments * * Take each command line argument and assume it is a URI segment. * * @access private * @return string */ private function _parse_cli_args() { $args = array_slice($_SERVER['argv'], 1); return $args ? '/' . implode('/', $args) : ''; } // -------------------------------------------------------------------- /** * Filter segments for malicious characters * * @access private * @param string * @return string */ function _filter_uri($str) { if ($str != '' && $this->config->item('permitted_uri_chars') != '' && $this->config->item('enable_query_strings') == FALSE) { // preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards // compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config->item('permitted_uri_chars'), '-'))."]+$|i", $str)) { show_error('The URI you submitted has disallowed characters.', 400); } } // Convert programatic characters to entities $bad = array('$', '(', ')', '%28', '%29'); $good = array('&#36;', '&#40;', '&#41;', '&#40;', '&#41;'); return str_replace($bad, $good, $str); } // -------------------------------------------------------------------- /** * Remove the suffix from the URL if needed * * @access private * @return void */ function _remove_url_suffix() { if ($this->config->item('url_suffix') != "") { $this->uri_string = preg_replace("|".preg_quote($this->config->item('url_suffix'))."$|", "", $this->uri_string); } } // -------------------------------------------------------------------- /** * Explode the URI Segments. The individual segments will * be stored in the $this->segments array. * * @access private * @return void */ function _explode_segments() { foreach (explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val) { // Filter segments for security $val = trim($this->_filter_uri($val)); if ($val != '') { $this->segments[] = $val; } } } // -------------------------------------------------------------------- /** * Re-index Segments * * This function re-indexes the $this->segment array so that it * starts at 1 rather than 0. Doing so makes it simpler to * use functions like $this->uri->segment(n) since there is * a 1:1 relationship between the segment array and the actual segments. * * @access private * @return void */ function _reindex_segments() { array_unshift($this->segments, NULL); array_unshift($this->rsegments, NULL); unset($this->segments[0]); unset($this->rsegments[0]); } // -------------------------------------------------------------------- /** * Fetch a URI Segment * * This function returns the URI segment based on the number provided. * * @access public * @param integer * @param bool * @return string */ function segment($n, $no_result = FALSE) { return ( ! isset($this->segments[$n])) ? $no_result : $this->segments[$n]; } // -------------------------------------------------------------------- /** * Fetch a URI "routed" Segment * * This function returns the re-routed URI segment (assuming routing rules are used) * based on the number provided. If there is no routing this function returns the * same result as $this->segment() * * @access public * @param integer * @param bool * @return string */ function rsegment($n, $no_result = FALSE) { return ( ! isset($this->rsegments[$n])) ? $no_result : $this->rsegments[$n]; } // -------------------------------------------------------------------- /** * Generate a key value pair from the URI string * * This function generates and associative array of URI data starting * at the supplied segment. For example, if this is your URI: * * example.com/user/search/name/joe/location/UK/gender/male * * You can use this function to generate an array with this prototype: * * array ( * name => joe * location => UK * gender => male * ) * * @access public * @param integer the starting segment number * @param array an array of default values * @return array */ function uri_to_assoc($n = 3, $default = array()) { return $this->_uri_to_assoc($n, $default, 'segment'); } /** * Identical to above only it uses the re-routed segment array * * @access public * @param integer the starting segment number * @param array an array of default values * @return array * */ function ruri_to_assoc($n = 3, $default = array()) { return $this->_uri_to_assoc($n, $default, 'rsegment'); } // -------------------------------------------------------------------- /** * Generate a key value pair from the URI string or Re-routed URI string * * @access private * @param integer the starting segment number * @param array an array of default values * @param string which array we should use * @return array */ function _uri_to_assoc($n = 3, $default = array(), $which = 'segment') { if ($which == 'segment') { $total_segments = 'total_segments'; $segment_array = 'segment_array'; } else { $total_segments = 'total_rsegments'; $segment_array = 'rsegment_array'; } if ( ! is_numeric($n)) { return $default; } if (isset($this->keyval[$n])) { return $this->keyval[$n]; } if ($this->$total_segments() < $n) { if (count($default) == 0) { return array(); } $retval = array(); foreach ($default as $val) { $retval[$val] = FALSE; } return $retval; } $segments = array_slice($this->$segment_array(), ($n - 1)); $i = 0; $lastval = ''; $retval = array(); foreach ($segments as $seg) { if ($i % 2) { $retval[$lastval] = $seg; } else { $retval[$seg] = FALSE; $lastval = $seg; } $i++; } if (count($default) > 0) { foreach ($default as $val) { if ( ! array_key_exists($val, $retval)) { $retval[$val] = FALSE; } } } // Cache the array for reuse $this->keyval[$n] = $retval; return $retval; } // -------------------------------------------------------------------- /** * Generate a URI string from an associative array * * * @access public * @param array an associative array of key/values * @return array */ function assoc_to_uri($array) { $temp = array(); foreach ((array)$array as $key => $val) { $temp[] = $key; $temp[] = $val; } return implode('/', $temp); } // -------------------------------------------------------------------- /** * Fetch a URI Segment and add a trailing slash * * @access public * @param integer * @param string * @return string */ function slash_segment($n, $where = 'trailing') { return $this->_slash_segment($n, $where, 'segment'); } // -------------------------------------------------------------------- /** * Fetch a URI Segment and add a trailing slash * * @access public * @param integer * @param string * @return string */ function slash_rsegment($n, $where = 'trailing') { return $this->_slash_segment($n, $where, 'rsegment'); } // -------------------------------------------------------------------- /** * Fetch a URI Segment and add a trailing slash - helper function * * @access private * @param integer * @param string * @param string * @return string */ function _slash_segment($n, $where = 'trailing', $which = 'segment') { $leading = '/'; $trailing = '/'; if ($where == 'trailing') { $leading = ''; } elseif ($where == 'leading') { $trailing = ''; } return $leading.$this->$which($n).$trailing; } // -------------------------------------------------------------------- /** * Segment Array * * @access public * @return array */ function segment_array() { return $this->segments; } // -------------------------------------------------------------------- /** * Routed Segment Array * * @access public * @return array */ function rsegment_array() { return $this->rsegments; } // -------------------------------------------------------------------- /** * Total number of segments * * @access public * @return integer */ function total_segments() { return count($this->segments); } // -------------------------------------------------------------------- /** * Total number of routed segments * * @access public * @return integer */ function total_rsegments() { return count($this->rsegments); } // -------------------------------------------------------------------- /** * Fetch the entire URI string * * @access public * @return string */ function uri_string() { return $this->uri_string; } // -------------------------------------------------------------------- /** * Fetch the entire Re-routed URI string * * @access public * @return string */ function ruri_string() { return '/'.implode('/', $this->rsegment_array()); } } // END URI Class /* End of file URI.php */ /* Location: ./system/core/URI.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Common.php
system/core/Common.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Common Functions * * Loads the base classes and executes the request. * * @package CodeIgniter * @subpackage codeigniter * @category Common Functions * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/ */ // ------------------------------------------------------------------------ /** * Determines if the current version of PHP is greater then the supplied value * * Since there are a few places where we conditionally test for PHP > 5 * we'll set a static variable. * * @access public * @param string * @return bool TRUE if the current version is $version or higher */ if ( ! function_exists('is_php')) { function is_php($version = '5.0.0') { static $_is_php; $version = (string)$version; if ( ! isset($_is_php[$version])) { $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE; } return $_is_php[$version]; } } // ------------------------------------------------------------------------ /** * Tests for file writability * * is_writable() returns TRUE on Windows servers when you really can't write to * the file, based on the read-only attribute. is_writable() is also unreliable * on Unix servers if safe_mode is on. * * @access private * @return void */ if ( ! function_exists('is_really_writable')) { function is_really_writable($file) { // If we're on a Unix server with safe_mode off we call is_writable if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE) { return is_writable($file); } // For windows servers and safe_mode "on" installations we'll actually // write a file then read it. Bah... if (is_dir($file)) { $file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100)); if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) { return FALSE; } fclose($fp); @chmod($file, DIR_WRITE_MODE); @unlink($file); return TRUE; } elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) { return FALSE; } fclose($fp); return TRUE; } } // ------------------------------------------------------------------------ /** * Class registry * * This function acts as a singleton. If the requested class does not * exist it is instantiated and set to a static variable. If it has * previously been instantiated the variable is returned. * * @access public * @param string the class name being requested * @param string the directory where the class should be found * @param string the class name prefix * @return object */ if ( ! function_exists('load_class')) { function &load_class($class, $directory = 'libraries', $prefix = 'CI_') { static $_classes = array(); // Does the class exist? If so, we're done... if (isset($_classes[$class])) { return $_classes[$class]; } $name = FALSE; // Look for the class first in the local application/libraries folder // then in the native system/libraries folder foreach (array(APPPATH, BASEPATH) as $path) { if (file_exists($path.$directory.'/'.$class.'.php')) { $name = $prefix.$class; if (class_exists($name) === FALSE) { require($path.$directory.'/'.$class.'.php'); } break; } } // Is the request a class extension? If so we load it too if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php')) { $name = config_item('subclass_prefix').$class; if (class_exists($name) === FALSE) { require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'); } } // Did we find the class? if ($name === FALSE) { // Note: We use exit() rather then show_error() in order to avoid a // self-referencing loop with the Excptions class exit('Unable to locate the specified class: '.$class.'.php'); } // Keep track of what we just loaded is_loaded($class); $_classes[$class] = new $name(); return $_classes[$class]; } } // -------------------------------------------------------------------- /** * Keeps track of which libraries have been loaded. This function is * called by the load_class() function above * * @access public * @return array */ if ( ! function_exists('is_loaded')) { function &is_loaded($class = '') { static $_is_loaded = array(); if ($class != '') { $_is_loaded[strtolower($class)] = $class; } return $_is_loaded; } } // ------------------------------------------------------------------------ /** * Loads the main config.php file * * This function lets us grab the config file even if the Config class * hasn't been instantiated yet * * @access private * @return array */ if ( ! function_exists('get_config')) { function &get_config($replace = array()) { static $_config; if (isset($_config)) { return $_config[0]; } // Is the config file in the environment folder? if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php')) { $file_path = APPPATH.'config/config.php'; } // Fetch the config file if ( ! file_exists($file_path)) { exit('The configuration file does not exist.'); } require($file_path); // Does the $config array exist in the file? if ( ! isset($config) OR ! is_array($config)) { exit('Your config file does not appear to be formatted correctly.'); } // Are any values being dynamically replaced? if (count($replace) > 0) { foreach ($replace as $key => $val) { if (isset($config[$key])) { $config[$key] = $val; } } } return $_config[0] =& $config; } } // ------------------------------------------------------------------------ /** * Returns the specified config item * * @access public * @return mixed */ if ( ! function_exists('config_item')) { function config_item($item) { static $_config_item = array(); if ( ! isset($_config_item[$item])) { $config =& get_config(); if ( ! isset($config[$item])) { return FALSE; } $_config_item[$item] = $config[$item]; } return $_config_item[$item]; } } // ------------------------------------------------------------------------ /** * Error Handler * * This function lets us invoke the exception class and * display errors using the standard error template located * in application/errors/errors.php * This function will send the error page directly to the * browser and exit. * * @access public * @return void */ if ( ! function_exists('show_error')) { function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered') { $_error =& load_class('Exceptions', 'core'); echo $_error->show_error($heading, $message, 'error_general', $status_code); exit; } } // ------------------------------------------------------------------------ /** * 404 Page Handler * * This function is similar to the show_error() function above * However, instead of the standard error template it displays * 404 errors. * * @access public * @return void */ if ( ! function_exists('show_404')) { function show_404($page = '', $log_error = TRUE) { $_error =& load_class('Exceptions', 'core'); $_error->show_404($page, $log_error); exit; } } // ------------------------------------------------------------------------ /** * Error Logging Interface * * We use this as a simple mechanism to access the logging * class and send messages to be logged. * * @access public * @return void */ if ( ! function_exists('log_message')) { function log_message($level = 'error', $message, $php_error = FALSE) { static $_log; if (config_item('log_threshold') == 0) { return; } $_log =& load_class('Log'); $_log->write_log($level, $message, $php_error); } } // ------------------------------------------------------------------------ /** * Set HTTP Status Header * * @access public * @param int the status code * @param string * @return void */ if ( ! function_exists('set_status_header')) { function set_status_header($code = 200, $text = '') { $stati = array( 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported' ); if ($code == '' OR ! is_numeric($code)) { show_error('Status codes must be numeric', 500); } if (isset($stati[$code]) AND $text == '') { $text = $stati[$code]; } if ($text == '') { show_error('No status text available. Please check your status code number or supply your own message text.', 500); } $server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE; if (substr(php_sapi_name(), 0, 3) == 'cgi') { header("Status: {$code} {$text}", TRUE); } elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0') { header($server_protocol." {$code} {$text}", TRUE, $code); } else { header("HTTP/1.1 {$code} {$text}", TRUE, $code); } } } // -------------------------------------------------------------------- /** * Exception Handler * * This is the custom exception handler that is declaired at the top * of Codeigniter.php. The main reason we use this is to permit * PHP errors to be logged in our own log files since the user may * not have access to server logs. Since this function * effectively intercepts PHP errors, however, we also need * to display errors based on the current error_reporting level. * We do that with the use of a PHP error template. * * @access private * @return void */ if ( ! function_exists('_exception_handler')) { function _exception_handler($severity, $message, $filepath, $line) { // We don't bother with "strict" notices since they tend to fill up // the log file with excess information that isn't normally very helpful. // For example, if you are running PHP 5 and you use version 4 style // class functions (without prefixes like "public", "private", etc.) // you'll get notices telling you that these have been deprecated. if ($severity == E_STRICT) { return; } $_error =& load_class('Exceptions', 'core'); // Should we display the error? We'll get the current error_reporting // level and add its bits with the severity bits to find out. if (($severity & error_reporting()) == $severity) { $_error->show_php_error($severity, $message, $filepath, $line); } // Should we log the error? No? We're done... if (config_item('log_threshold') == 0) { return; } $_error->log_exception($severity, $message, $filepath, $line); } } // -------------------------------------------------------------------- /** * Remove Invisible Characters * * This prevents sandwiching null characters * between ascii characters, like Java\0script. * * @access public * @param string * @return string */ if ( ! function_exists('remove_invisible_characters')) { function remove_invisible_characters($str, $url_encoded = TRUE) { $non_displayables = array(); // every control character except newline (dec 10) // carriage return (dec 13), and horizontal tab (dec 09) if ($url_encoded) { $non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15 $non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31 } $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127 do { $str = preg_replace($non_displayables, '', $str, -1, $count); } while ($count); return $str; } } // ------------------------------------------------------------------------ /** * Returns HTML escaped variable * * @access public * @param mixed * @return mixed */ if ( ! function_exists('html_escape')) { function html_escape($var) { if (is_array($var)) { return array_map('html_escape', $var); } else { return htmlspecialchars($var, ENT_QUOTES, config_item('charset')); } } } /* End of file Common.php */ /* Location: ./system/core/Common.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Controller.php
system/core/Controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Application Controller Class * * This class object is the super class that every library in * CodeIgniter will be assigned to. * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/general/controllers.html */ class CI_Controller { private static $instance; /** * Constructor */ public function __construct() { self::$instance =& $this; // Assign all the class objects that were instantiated by the // bootstrap file (CodeIgniter.php) to local class variables // so that CI can run as one big super object. foreach (is_loaded() as $var => $class) { $this->$var =& load_class($class); } $this->load =& load_class('Loader', 'core'); $this->load->initialize(); log_message('debug', "Controller Class Initialized"); } public static function &get_instance() { return self::$instance; } } // END Controller class /* End of file Controller.php */ /* Location: ./system/core/Controller.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Exceptions.php
system/core/Exceptions.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Exceptions Class * * @package CodeIgniter * @subpackage Libraries * @category Exceptions * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/exceptions.html */ class CI_Exceptions { var $action; var $severity; var $message; var $filename; var $line; /** * Nesting level of the output buffering mechanism * * @var int * @access public */ var $ob_level; /** * List if available error levels * * @var array * @access public */ var $levels = array( E_ERROR => 'Error', E_WARNING => 'Warning', E_PARSE => 'Parsing Error', E_NOTICE => 'Notice', E_CORE_ERROR => 'Core Error', E_CORE_WARNING => 'Core Warning', E_COMPILE_ERROR => 'Compile Error', E_COMPILE_WARNING => 'Compile Warning', E_USER_ERROR => 'User Error', E_USER_WARNING => 'User Warning', E_USER_NOTICE => 'User Notice', E_STRICT => 'Runtime Notice' ); /** * Constructor */ public function __construct() { $this->ob_level = ob_get_level(); // Note: Do not log messages from this constructor. } // -------------------------------------------------------------------- /** * Exception Logger * * This function logs PHP generated error messages * * @access private * @param string the error severity * @param string the error string * @param string the error filepath * @param string the error line number * @return string */ function log_exception($severity, $message, $filepath, $line) { $severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity]; log_message('error', 'Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line, TRUE); } // -------------------------------------------------------------------- /** * 404 Page Not Found Handler * * @access private * @param string the page * @param bool log error yes/no * @return string */ function show_404($page = '', $log_error = TRUE) { $heading = "404 Page Not Found"; $message = "The page you requested was not found."; // By default we log this, but allow a dev to skip it if ($log_error) { log_message('error', '404 Page Not Found --> '.$page); } echo $this->show_error($heading, $message, 'error_404', 404); exit; } // -------------------------------------------------------------------- /** * General Error Page * * This function takes an error message as input * (either as a string or an array) and displays * it using the specified template. * * @access private * @param string the heading * @param string the message * @param string the template name * @param int the status code * @return string */ function show_error($heading, $message, $template = 'error_general', $status_code = 500) { set_status_header($status_code); $message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>'; if (ob_get_level() > $this->ob_level + 1) { ob_end_flush(); } ob_start(); include(APPPATH.'errors/'.$template.'.php'); $buffer = ob_get_contents(); ob_end_clean(); return $buffer; } // -------------------------------------------------------------------- /** * Native PHP error handler * * @access private * @param string the error severity * @param string the error string * @param string the error filepath * @param string the error line number * @return string */ function show_php_error($severity, $message, $filepath, $line) { $severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity]; $filepath = str_replace("\\", "/", $filepath); // For safety reasons we do not show the full file path if (FALSE !== strpos($filepath, '/')) { $x = explode('/', $filepath); $filepath = $x[count($x)-2].'/'.end($x); } if (ob_get_level() > $this->ob_level + 1) { ob_end_flush(); } ob_start(); include(APPPATH.'errors/error_php.php'); $buffer = ob_get_contents(); ob_end_clean(); echo $buffer; } } // END Exceptions Class /* End of file Exceptions.php */ /* Location: ./system/core/Exceptions.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Benchmark.php
system/core/Benchmark.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Benchmark Class * * This class enables you to mark points and calculate the time difference * between them. Memory consumption can also be displayed. * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/benchmark.html */ class CI_Benchmark { /** * List of all benchmark markers and when they were added * * @var array */ var $marker = array(); // -------------------------------------------------------------------- /** * Set a benchmark marker * * Multiple calls to this function can be made so that several * execution points can be timed * * @access public * @param string $name name of the marker * @return void */ function mark($name) { $this->marker[$name] = microtime(); } // -------------------------------------------------------------------- /** * Calculates the time difference between two marked points. * * If the first parameter is empty this function instead returns the * {elapsed_time} pseudo-variable. This permits the full system * execution time to be shown in a template. The output class will * swap the real value for this variable. * * @access public * @param string a particular marked point * @param string a particular marked point * @param integer the number of decimal places * @return mixed */ function elapsed_time($point1 = '', $point2 = '', $decimals = 4) { if ($point1 == '') { return '{elapsed_time}'; } if ( ! isset($this->marker[$point1])) { return ''; } if ( ! isset($this->marker[$point2])) { $this->marker[$point2] = microtime(); } list($sm, $ss) = explode(' ', $this->marker[$point1]); list($em, $es) = explode(' ', $this->marker[$point2]); return number_format(($em + $es) - ($sm + $ss), $decimals); } // -------------------------------------------------------------------- /** * Memory Usage * * This function returns the {memory_usage} pseudo-variable. * This permits it to be put it anywhere in a template * without the memory being calculated until the end. * The output class will swap the real value for this variable. * * @access public * @return string */ function memory_usage() { return '{memory_usage}'; } } // END CI_Benchmark class /* End of file Benchmark.php */ /* Location: ./system/core/Benchmark.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Output.php
system/core/Output.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Output Class * * Responsible for sending final output to browser * * @package CodeIgniter * @subpackage Libraries * @category Output * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/output.html */ class CI_Output { /** * Current output string * * @var string * @access protected */ protected $final_output; /** * Cache expiration time * * @var int * @access protected */ protected $cache_expiration = 0; /** * List of server headers * * @var array * @access protected */ protected $headers = array(); /** * List of mime types * * @var array * @access protected */ protected $mime_types = array(); /** * Determines wether profiler is enabled * * @var book * @access protected */ protected $enable_profiler = FALSE; /** * Determines if output compression is enabled * * @var bool * @access protected */ protected $_zlib_oc = FALSE; /** * List of profiler sections * * @var array * @access protected */ protected $_profiler_sections = array(); /** * Whether or not to parse variables like {elapsed_time} and {memory_usage} * * @var bool * @access protected */ protected $parse_exec_vars = TRUE; /** * Constructor * */ function __construct() { $this->_zlib_oc = @ini_get('zlib.output_compression'); // Get mime types for later if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) { include APPPATH.'config/'.ENVIRONMENT.'/mimes.php'; } else { include APPPATH.'config/mimes.php'; } $this->mime_types = $mimes; log_message('debug', "Output Class Initialized"); } // -------------------------------------------------------------------- /** * Get Output * * Returns the current output string * * @access public * @return string */ function get_output() { return $this->final_output; } // -------------------------------------------------------------------- /** * Set Output * * Sets the output string * * @access public * @param string * @return void */ function set_output($output) { $this->final_output = $output; return $this; } // -------------------------------------------------------------------- /** * Append Output * * Appends data onto the output string * * @access public * @param string * @return void */ function append_output($output) { if ($this->final_output == '') { $this->final_output = $output; } else { $this->final_output .= $output; } return $this; } // -------------------------------------------------------------------- /** * Set Header * * Lets you set a server header which will be outputted with the final display. * * Note: If a file is cached, headers will not be sent. We need to figure out * how to permit header data to be saved with the cache data... * * @access public * @param string * @param bool * @return void */ function set_header($header, $replace = TRUE) { // If zlib.output_compression is enabled it will compress the output, // but it will not modify the content-length header to compensate for // the reduction, causing the browser to hang waiting for more data. // We'll just skip content-length in those cases. if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0) { return; } $this->headers[] = array($header, $replace); return $this; } // -------------------------------------------------------------------- /** * Set Content Type Header * * @access public * @param string extension of the file we're outputting * @return void */ function set_content_type($mime_type) { if (strpos($mime_type, '/') === FALSE) { $extension = ltrim($mime_type, '.'); // Is this extension supported? if (isset($this->mime_types[$extension])) { $mime_type =& $this->mime_types[$extension]; if (is_array($mime_type)) { $mime_type = current($mime_type); } } } $header = 'Content-Type: '.$mime_type; $this->headers[] = array($header, TRUE); return $this; } // -------------------------------------------------------------------- /** * Set HTTP Status Header * moved to Common procedural functions in 1.7.2 * * @access public * @param int the status code * @param string * @return void */ function set_status_header($code = 200, $text = '') { set_status_header($code, $text); return $this; } // -------------------------------------------------------------------- /** * Enable/disable Profiler * * @access public * @param bool * @return void */ function enable_profiler($val = TRUE) { $this->enable_profiler = (is_bool($val)) ? $val : TRUE; return $this; } // -------------------------------------------------------------------- /** * Set Profiler Sections * * Allows override of default / config settings for Profiler section display * * @access public * @param array * @return void */ function set_profiler_sections($sections) { foreach ($sections as $section => $enable) { $this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE; } return $this; } // -------------------------------------------------------------------- /** * Set Cache * * @access public * @param integer * @return void */ function cache($time) { $this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time; return $this; } // -------------------------------------------------------------------- /** * Display Output * * All "view" data is automatically put into this variable by the controller class: * * $this->final_output * * This function sends the finalized output data to the browser along * with any server headers and profile data. It also stops the * benchmark timer so the page rendering speed and memory usage can be shown. * * @access public * @param string * @return mixed */ function _display($output = '') { // Note: We use globals because we can't use $CI =& get_instance() // since this function is sometimes called by the caching mechanism, // which happens before the CI super object is available. global $BM, $CFG; // Grab the super object if we can. if (class_exists('CI_Controller')) { $CI =& get_instance(); } // -------------------------------------------------------------------- // Set the output data if ($output == '') { $output =& $this->final_output; } // -------------------------------------------------------------------- // Do we need to write a cache file? Only if the controller does not have its // own _output() method and we are not dealing with a cache file, which we // can determine by the existence of the $CI object above if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output')) { $this->_write_cache($output); } // -------------------------------------------------------------------- // Parse out the elapsed time and memory usage, // then swap the pseudo-variables with the data $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end'); if ($this->parse_exec_vars === TRUE) { $memory = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB'; $output = str_replace('{elapsed_time}', $elapsed, $output); $output = str_replace('{memory_usage}', $memory, $output); } // -------------------------------------------------------------------- // Is compression requested? if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE) { if (extension_loaded('zlib')) { if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) { ob_start('ob_gzhandler'); } } } // -------------------------------------------------------------------- // Are there any server headers to send? if (count($this->headers) > 0) { foreach ($this->headers as $header) { @header($header[0], $header[1]); } } // -------------------------------------------------------------------- // Does the $CI object exist? // If not we know we are dealing with a cache file so we'll // simply echo out the data and exit. if ( ! isset($CI)) { echo $output; log_message('debug', "Final output sent to browser"); log_message('debug', "Total execution time: ".$elapsed); return TRUE; } // -------------------------------------------------------------------- // Do we need to generate profile data? // If so, load the Profile class and run it. if ($this->enable_profiler == TRUE) { $CI->load->library('profiler'); if ( ! empty($this->_profiler_sections)) { $CI->profiler->set_sections($this->_profiler_sections); } // If the output data contains closing </body> and </html> tags // we will remove them and add them back after we insert the profile data if (preg_match("|</body>.*?</html>|is", $output)) { $output = preg_replace("|</body>.*?</html>|is", '', $output); $output .= $CI->profiler->run(); $output .= '</body></html>'; } else { $output .= $CI->profiler->run(); } } // -------------------------------------------------------------------- // Does the controller contain a function named _output()? // If so send the output there. Otherwise, echo it. if (method_exists($CI, '_output')) { $CI->_output($output); } else { echo $output; // Send it to the browser! } log_message('debug', "Final output sent to browser"); log_message('debug', "Total execution time: ".$elapsed); } // -------------------------------------------------------------------- /** * Write a Cache File * * @access public * @param string * @return void */ function _write_cache($output) { $CI =& get_instance(); $path = $CI->config->item('cache_path'); $cache_path = ($path == '') ? APPPATH.'cache/' : $path; if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path)) { log_message('error', "Unable to write cache file: ".$cache_path); return; } $uri = $CI->config->item('base_url'). $CI->config->item('index_page'). $CI->uri->uri_string(); $cache_path .= md5($uri); if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE)) { log_message('error', "Unable to write cache file: ".$cache_path); return; } $expire = time() + ($this->cache_expiration * 60); if (flock($fp, LOCK_EX)) { fwrite($fp, $expire.'TS--->'.$output); flock($fp, LOCK_UN); } else { log_message('error', "Unable to secure a file lock for file at: ".$cache_path); return; } fclose($fp); @chmod($cache_path, FILE_WRITE_MODE); log_message('debug', "Cache file written: ".$cache_path); } // -------------------------------------------------------------------- /** * Update/serve a cached file * * @access public * @param object config class * @param object uri class * @return void */ function _display_cache(&$CFG, &$URI) { $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path'); // Build the file path. The file name is an MD5 hash of the full URI $uri = $CFG->item('base_url'). $CFG->item('index_page'). $URI->uri_string; $filepath = $cache_path.md5($uri); if ( ! @file_exists($filepath)) { return FALSE; } if ( ! $fp = @fopen($filepath, FOPEN_READ)) { return FALSE; } flock($fp, LOCK_SH); $cache = ''; if (filesize($filepath) > 0) { $cache = fread($fp, filesize($filepath)); } flock($fp, LOCK_UN); fclose($fp); // Strip out the embedded timestamp if ( ! preg_match("/(\d+TS--->)/", $cache, $match)) { return FALSE; } // Has the file expired? If so we'll delete it. if (time() >= trim(str_replace('TS--->', '', $match['1']))) { if (is_really_writable($cache_path)) { @unlink($filepath); log_message('debug', "Cache file has expired. File deleted"); return FALSE; } } // Display the cache $this->_display(str_replace($match['0'], '', $cache)); log_message('debug', "Cache file is current. Sending it to browser."); return TRUE; } } // END Output Class /* End of file Output.php */ /* Location: ./system/core/Output.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/CodeIgniter.php
system/core/CodeIgniter.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * System Initialization File * * Loads the base classes and executes the request. * * @package CodeIgniter * @subpackage codeigniter * @category Front-controller * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/ */ /** * CodeIgniter Version * * @var string * */ define('CI_VERSION', '2.1.3'); /** * CodeIgniter Branch (Core = TRUE, Reactor = FALSE) * * @var boolean * */ define('CI_CORE', FALSE); /* * ------------------------------------------------------ * Load the global functions * ------------------------------------------------------ */ require(BASEPATH.'core/Common.php'); /* * ------------------------------------------------------ * Load the framework constants * ------------------------------------------------------ */ if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/constants.php')) { require(APPPATH.'config/'.ENVIRONMENT.'/constants.php'); } else { require(APPPATH.'config/constants.php'); } /* * ------------------------------------------------------ * Define a custom error handler so we can log PHP errors * ------------------------------------------------------ */ set_error_handler('_exception_handler'); if ( ! is_php('5.3')) { @set_magic_quotes_runtime(0); // Kill magic quotes } /* * ------------------------------------------------------ * Set the subclass_prefix * ------------------------------------------------------ * * Normally the "subclass_prefix" is set in the config file. * The subclass prefix allows CI to know if a core class is * being extended via a library in the local application * "libraries" folder. Since CI allows config items to be * overriden via data set in the main index. php file, * before proceeding we need to know if a subclass_prefix * override exists. If so, we will set this value now, * before any classes are loaded * Note: Since the config file data is cached it doesn't * hurt to load it here. */ if (isset($assign_to_config['subclass_prefix']) AND $assign_to_config['subclass_prefix'] != '') { get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); } /* * ------------------------------------------------------ * Set a liberal script execution time limit * ------------------------------------------------------ */ if (function_exists("set_time_limit") == TRUE AND @ini_get("safe_mode") == 0) { @set_time_limit(300); } /* * ------------------------------------------------------ * Start the timer... tick tock tick tock... * ------------------------------------------------------ */ $BM =& load_class('Benchmark', 'core'); $BM->mark('total_execution_time_start'); $BM->mark('loading_time:_base_classes_start'); /* * ------------------------------------------------------ * Instantiate the hooks class * ------------------------------------------------------ */ $EXT =& load_class('Hooks', 'core'); /* * ------------------------------------------------------ * Is there a "pre_system" hook? * ------------------------------------------------------ */ $EXT->_call_hook('pre_system'); /* * ------------------------------------------------------ * Instantiate the config class * ------------------------------------------------------ */ $CFG =& load_class('Config', 'core'); // Do we have any manually set config items in the index.php file? if (isset($assign_to_config)) { $CFG->_assign_to_config($assign_to_config); } /* * ------------------------------------------------------ * Instantiate the UTF-8 class * ------------------------------------------------------ * * Note: Order here is rather important as the UTF-8 * class needs to be used very early on, but it cannot * properly determine if UTf-8 can be supported until * after the Config class is instantiated. * */ $UNI =& load_class('Utf8', 'core'); /* * ------------------------------------------------------ * Instantiate the URI class * ------------------------------------------------------ */ $URI =& load_class('URI', 'core'); /* * ------------------------------------------------------ * Instantiate the routing class and set the routing * ------------------------------------------------------ */ $RTR =& load_class('Router', 'core'); $RTR->_set_routing(); // Set any routing overrides that may exist in the main index file if (isset($routing)) { $RTR->_set_overrides($routing); } /* * ------------------------------------------------------ * Instantiate the output class * ------------------------------------------------------ */ $OUT =& load_class('Output', 'core'); /* * ------------------------------------------------------ * Is there a valid cache file? If so, we're done... * ------------------------------------------------------ */ if ($EXT->_call_hook('cache_override') === FALSE) { if ($OUT->_display_cache($CFG, $URI) == TRUE) { exit; } } /* * ----------------------------------------------------- * Load the security class for xss and csrf support * ----------------------------------------------------- */ $SEC =& load_class('Security', 'core'); /* * ------------------------------------------------------ * Load the Input class and sanitize globals * ------------------------------------------------------ */ $IN =& load_class('Input', 'core'); /* * ------------------------------------------------------ * Load the Language class * ------------------------------------------------------ */ $LANG =& load_class('Lang', 'core'); /* * ------------------------------------------------------ * Load the app controller and local controller * ------------------------------------------------------ * */ // Load the base controller class require BASEPATH.'core/Controller.php'; function &get_instance() { return CI_Controller::get_instance(); } if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) { require APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; } // Load the local application controller // Note: The Router class automatically validates the controller path using the router->_validate_request(). // If this include fails it means that the default controller in the Routes.php file is not resolving to something valid. if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().'.php')) { show_error('Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.'); } include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().'.php'); // Set a mark point for benchmarking $BM->mark('loading_time:_base_classes_end'); /* * ------------------------------------------------------ * Security check * ------------------------------------------------------ * * None of the functions in the app controller or the * loader class can be called via the URI, nor can * controller functions that begin with an underscore */ $class = $RTR->fetch_class(); $method = $RTR->fetch_method(); if ( ! class_exists($class) OR strncmp($method, '_', 1) == 0 OR in_array(strtolower($method), array_map('strtolower', get_class_methods('CI_Controller'))) ) { if ( ! empty($RTR->routes['404_override'])) { $x = explode('/', $RTR->routes['404_override']); $class = $x[0]; $method = (isset($x[1]) ? $x[1] : 'index'); if ( ! class_exists($class)) { if ( ! file_exists(APPPATH.'controllers/'.$class.'.php')) { show_404("{$class}/{$method}"); } include_once(APPPATH.'controllers/'.$class.'.php'); } } else { show_404("{$class}/{$method}"); } } /* * ------------------------------------------------------ * Is there a "pre_controller" hook? * ------------------------------------------------------ */ $EXT->_call_hook('pre_controller'); /* * ------------------------------------------------------ * Instantiate the requested controller * ------------------------------------------------------ */ // Mark a start point so we can benchmark the controller $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); $CI = new $class(); /* * ------------------------------------------------------ * Is there a "post_controller_constructor" hook? * ------------------------------------------------------ */ $EXT->_call_hook('post_controller_constructor'); /* * ------------------------------------------------------ * Call the requested method * ------------------------------------------------------ */ // Is there a "remap" function? If so, we call it instead if (method_exists($CI, '_remap')) { $CI->_remap($method, array_slice($URI->rsegments, 2)); } else { // is_callable() returns TRUE on some versions of PHP 5 for private and protected // methods, so we'll use this workaround for consistent behavior if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($CI)))) { // Check and see if we are using a 404 override and use it. if ( ! empty($RTR->routes['404_override'])) { $x = explode('/', $RTR->routes['404_override']); $class = $x[0]; $method = (isset($x[1]) ? $x[1] : 'index'); if ( ! class_exists($class)) { if ( ! file_exists(APPPATH.'controllers/'.$class.'.php')) { show_404("{$class}/{$method}"); } include_once(APPPATH.'controllers/'.$class.'.php'); unset($CI); $CI = new $class(); } } else { show_404("{$class}/{$method}"); } } // Call the requested method. // Any URI segments present (besides the class/function) will be passed to the method for convenience call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2)); } // Mark a benchmark end point $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); /* * ------------------------------------------------------ * Is there a "post_controller" hook? * ------------------------------------------------------ */ $EXT->_call_hook('post_controller'); /* * ------------------------------------------------------ * Send the final rendered output to the browser * ------------------------------------------------------ */ if ($EXT->_call_hook('display_override') === FALSE) { $OUT->_display(); } /* * ------------------------------------------------------ * Is there a "post_system" hook? * ------------------------------------------------------ */ $EXT->_call_hook('post_system'); /* * ------------------------------------------------------ * Close the DB connection if one exists * ------------------------------------------------------ */ if (class_exists('CI_DB') AND isset($CI->db)) { $CI->db->close(); } /* End of file CodeIgniter.php */ /* Location: ./system/core/CodeIgniter.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Security.php
system/core/Security.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Security Class * * @package CodeIgniter * @subpackage Libraries * @category Security * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/security.html */ class CI_Security { /** * Random Hash for protecting URLs * * @var string * @access protected */ protected $_xss_hash = ''; /** * Random Hash for Cross Site Request Forgery Protection Cookie * * @var string * @access protected */ protected $_csrf_hash = ''; /** * Expiration time for Cross Site Request Forgery Protection Cookie * Defaults to two hours (in seconds) * * @var int * @access protected */ protected $_csrf_expire = 7200; /** * Token name for Cross Site Request Forgery Protection Cookie * * @var string * @access protected */ protected $_csrf_token_name = 'ci_csrf_token'; /** * Cookie name for Cross Site Request Forgery Protection Cookie * * @var string * @access protected */ protected $_csrf_cookie_name = 'ci_csrf_token'; /** * List of never allowed strings * * @var array * @access protected */ protected $_never_allowed_str = array( 'document.cookie' => '[removed]', 'document.write' => '[removed]', '.parentNode' => '[removed]', '.innerHTML' => '[removed]', 'window.location' => '[removed]', '-moz-binding' => '[removed]', '<!--' => '&lt;!--', '-->' => '--&gt;', '<![CDATA[' => '&lt;![CDATA[', '<comment>' => '&lt;comment&gt;' ); /* never allowed, regex replacement */ /** * List of never allowed regex replacement * * @var array * @access protected */ protected $_never_allowed_regex = array( 'javascript\s*:', 'expression\s*(\(|&\#40;)', // CSS and IE 'vbscript\s*:', // IE, surprise! 'Redirect\s+302', "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?" ); /** * Constructor * * @return void */ public function __construct() { // Is CSRF protection enabled? if (config_item('csrf_protection') === TRUE) { // CSRF config foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key) { if (FALSE !== ($val = config_item($key))) { $this->{'_'.$key} = $val; } } // Append application specific cookie prefix if (config_item('cookie_prefix')) { $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name; } // Set the CSRF hash $this->_csrf_set_hash(); } log_message('debug', "Security Class Initialized"); } // -------------------------------------------------------------------- /** * Verify Cross Site Request Forgery Protection * * @return object */ public function csrf_verify() { // If it's not a POST request we will set the CSRF cookie if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') { return $this->csrf_set_cookie(); } // Do the tokens exist in both the _POST and _COOKIE arrays? if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])) { $this->csrf_show_error(); } // Do the tokens match? if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) { $this->csrf_show_error(); } // We kill this since we're done and we don't want to // polute the _POST array unset($_POST[$this->_csrf_token_name]); // Nothing should last forever unset($_COOKIE[$this->_csrf_cookie_name]); $this->_csrf_set_hash(); $this->csrf_set_cookie(); log_message('debug', 'CSRF token verified'); return $this; } // -------------------------------------------------------------------- /** * Set Cross Site Request Forgery Protection Cookie * * @return object */ public function csrf_set_cookie() { $expire = time() + $this->_csrf_expire; $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0; if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off')) { return FALSE; } setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie); log_message('debug', "CRSF cookie Set"); return $this; } // -------------------------------------------------------------------- /** * Show CSRF Error * * @return void */ public function csrf_show_error() { show_error('The action you have requested is not allowed.'); } // -------------------------------------------------------------------- /** * Get CSRF Hash * * Getter Method * * @return string self::_csrf_hash */ public function get_csrf_hash() { return $this->_csrf_hash; } // -------------------------------------------------------------------- /** * Get CSRF Token Name * * Getter Method * * @return string self::csrf_token_name */ public function get_csrf_token_name() { return $this->_csrf_token_name; } // -------------------------------------------------------------------- /** * XSS Clean * * Sanitizes data so that Cross Site Scripting Hacks can be * prevented. This function does a fair amount of work but * it is extremely thorough, designed to prevent even the * most obscure XSS attempts. Nothing is ever 100% foolproof, * of course, but I haven't been able to get anything passed * the filter. * * Note: This function should only be used to deal with data * upon submission. It's not something that should * be used for general runtime processing. * * This function was based in part on some code and ideas I * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention * * To help develop this script I used this great list of * vulnerabilities along with a few other hacks I've * harvested from examining vulnerabilities in other programs: * http://ha.ckers.org/xss.html * * @param mixed string or array * @param bool * @return string */ public function xss_clean($str, $is_image = FALSE) { /* * Is the string an array? * */ if (is_array($str)) { while (list($key) = each($str)) { $str[$key] = $this->xss_clean($str[$key]); } return $str; } /* * Remove Invisible Characters */ $str = remove_invisible_characters($str); // Validate Entities in URLs $str = $this->_validate_entities($str); /* * URL Decode * * Just in case stuff like this is submitted: * * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a> * * Note: Use rawurldecode() so it does not remove plus signs * */ $str = rawurldecode($str); /* * Convert character entities to ASCII * * This permits our tests below to work reliably. * We only convert entities that are within tags since * these are the ones that will pose security problems. * */ $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str); $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str); /* * Remove Invisible Characters Again! */ $str = remove_invisible_characters($str); /* * Convert all tabs to spaces * * This prevents strings like this: ja vascript * NOTE: we deal with spaces between characters later. * NOTE: preg_replace was found to be amazingly slow here on * large blocks of data, so we use str_replace. */ if (strpos($str, "\t") !== FALSE) { $str = str_replace("\t", ' ', $str); } /* * Capture converted string for later comparison */ $converted_string = $str; // Remove Strings that are never allowed $str = $this->_do_never_allowed($str); /* * Makes PHP tags safe * * Note: XML tags are inadvertently replaced too: * * <?xml * * But it doesn't seem to pose a problem. */ if ($is_image === TRUE) { // Images have a tendency to have the PHP short opening and // closing tags every so often so we skip those and only // do the long opening tags. $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str); } else { $str = str_replace(array('<?', '?'.'>'), array('&lt;?', '?&gt;'), $str); } /* * Compact any exploded words * * This corrects words like: j a v a s c r i p t * These words are compacted back to their correct state. */ $words = array( 'javascript', 'expression', 'vbscript', 'script', 'base64', 'applet', 'alert', 'document', 'write', 'cookie', 'window' ); foreach ($words as $word) { $temp = ''; for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++) { $temp .= substr($word, $i, 1)."\s*"; } // We only want to do this when it is followed by a non-word character // That way valid stuff like "dealer to" does not become "dealerto" $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str); } /* * Remove disallowed Javascript in links or img tags * We used to do some version comparisons and use of stripos for PHP5, * but it is dog slow compared to these simplified non-capturing * preg_match(), especially if the pattern exists in the string */ do { $original = $str; if (preg_match("/<a/i", $str)) { $str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, '_js_link_removal'), $str); } if (preg_match("/<img/i", $str)) { $str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str); } if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str)) { $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str); } } while($original != $str); unset($original); // Remove evil attributes such as style, onclick and xmlns $str = $this->_remove_evil_attributes($str, $is_image); /* * Sanitize naughty HTML elements * * If a tag containing any of the words in the list * below is found, the tag gets converted to entities. * * So this: <blink> * Becomes: &lt;blink&gt; */ $naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss'; $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str); /* * Sanitize naughty scripting elements * * Similar to above, only instead of looking for * tags it looks for PHP and JavaScript commands * that are disallowed. Rather than removing the * code, it simply converts the parenthesis to entities * rendering the code un-executable. * * For example: eval('some code') * Becomes: eval&#40;'some code'&#41; */ $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2&#40;\\3&#41;", $str); // Final clean up // This adds a bit of extra precaution in case // something got through the above filters $str = $this->_do_never_allowed($str); /* * Images are Handled in a Special Way * - Essentially, we want to know that after all of the character * conversion is done whether any unwanted, likely XSS, code was found. * If not, we return TRUE, as the image is clean. * However, if the string post-conversion does not matched the * string post-removal of XSS, then it fails, as there was unwanted XSS * code found and removed/changed during processing. */ if ($is_image === TRUE) { return ($str == $converted_string) ? TRUE: FALSE; } log_message('debug', "XSS Filtering completed"); return $str; } // -------------------------------------------------------------------- /** * Random Hash for protecting URLs * * @return string */ public function xss_hash() { if ($this->_xss_hash == '') { mt_srand(); $this->_xss_hash = md5(time() + mt_rand(0, 1999999999)); } return $this->_xss_hash; } // -------------------------------------------------------------------- /** * HTML Entities Decode * * This function is a replacement for html_entity_decode() * * The reason we are not using html_entity_decode() by itself is because * while it is not technically correct to leave out the semicolon * at the end of an entity most browsers will still interpret the entity * correctly. html_entity_decode() does not convert entities without * semicolons, so we are left with our own little solution here. Bummer. * * @param string * @param string * @return string */ public function entity_decode($str, $charset='UTF-8') { if (stristr($str, '&') === FALSE) { return $str; } $str = html_entity_decode($str, ENT_COMPAT, $charset); $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str); return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str); } // -------------------------------------------------------------------- /** * Filename Security * * @param string * @param bool * @return string */ public function sanitize_filename($str, $relative_path = FALSE) { $bad = array( "../", "<!--", "-->", "<", ">", "'", '"', '&', '$', '#', '{', '}', '[', ']', '=', ';', '?', "%20", "%22", "%3c", // < "%253c", // < "%3e", // > "%0e", // > "%28", // ( "%29", // ) "%2528", // ( "%26", // & "%24", // $ "%3f", // ? "%3b", // ; "%3d" // = ); if ( ! $relative_path) { $bad[] = './'; $bad[] = '/'; } $str = remove_invisible_characters($str, FALSE); return stripslashes(str_replace($bad, '', $str)); } // ---------------------------------------------------------------- /** * Compact Exploded Words * * Callback function for xss_clean() to remove whitespace from * things like j a v a s c r i p t * * @param type * @return type */ protected function _compact_exploded_words($matches) { return preg_replace('/\s+/s', '', $matches[1]).$matches[2]; } // -------------------------------------------------------------------- /* * Remove Evil HTML Attributes (like evenhandlers and style) * * It removes the evil attribute and either: * - Everything up until a space * For example, everything between the pipes: * <a |style=document.write('hello');alert('world');| class=link> * - Everything inside the quotes * For example, everything between the pipes: * <a |style="document.write('hello'); alert('world');"| class="link"> * * @param string $str The string to check * @param boolean $is_image TRUE if this is an image * @return string The string with the evil attributes removed */ protected function _remove_evil_attributes($str, $is_image) { // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction'); if ($is_image === TRUE) { /* * Adobe Photoshop puts XML metadata into JFIF images, * including namespacing, so we have to allow this for images. */ unset($evil_attributes[array_search('xmlns', $evil_attributes)]); } do { $count = 0; $attribs = array(); // find occurrences of illegal attribute strings without quotes preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER); foreach ($matches as $attr) { $attribs[] = preg_quote($attr[0], '/'); } // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes) preg_match_all("/(".implode('|', $evil_attributes).")\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is", $str, $matches, PREG_SET_ORDER); foreach ($matches as $attr) { $attribs[] = preg_quote($attr[0], '/'); } // replace illegal attribute strings that are inside an html tag if (count($attribs) > 0) { $str = preg_replace("/<(\/?[^><]+?)([^A-Za-z<>\-])(.*?)(".implode('|', $attribs).")(.*?)([\s><])([><]*)/i", '<$1 $3$5$6$7', $str, -1, $count); } } while ($count); return $str; } // -------------------------------------------------------------------- /** * Sanitize Naughty HTML * * Callback function for xss_clean() to remove naughty HTML elements * * @param array * @return string */ protected function _sanitize_naughty_html($matches) { // encode opening brace $str = '&lt;'.$matches[1].$matches[2].$matches[3]; // encode captured opening or closing brace to prevent recursive vectors $str .= str_replace(array('>', '<'), array('&gt;', '&lt;'), $matches[4]); return $str; } // -------------------------------------------------------------------- /** * JS Link Removal * * Callback function for xss_clean() to sanitize links * This limits the PCRE backtracks, making it more performance friendly * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in * PHP 5.2+ on link-heavy strings * * @param array * @return string */ protected function _js_link_removal($match) { return str_replace( $match[1], preg_replace( '#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|data\s*:)#si', '', $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1])) ), $match[0] ); } // -------------------------------------------------------------------- /** * JS Image Removal * * Callback function for xss_clean() to sanitize image tags * This limits the PCRE backtracks, making it more performance friendly * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in * PHP 5.2+ on image tag heavy strings * * @param array * @return string */ protected function _js_img_removal($match) { return str_replace( $match[1], preg_replace( '#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si', '', $this->_filter_attributes(str_replace(array('<', '>'), '', $match[1])) ), $match[0] ); } // -------------------------------------------------------------------- /** * Attribute Conversion * * Used as a callback for XSS Clean * * @param array * @return string */ protected function _convert_attribute($match) { return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]); } // -------------------------------------------------------------------- /** * Filter Attributes * * Filters tag attributes for consistency and safety * * @param string * @return string */ protected function _filter_attributes($str) { $out = ''; if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches)) { foreach ($matches[0] as $match) { $out .= preg_replace("#/\*.*?\*/#s", '', $match); } } return $out; } // -------------------------------------------------------------------- /** * HTML Entity Decode Callback * * Used as a callback for XSS Clean * * @param array * @return string */ protected function _decode_entity($match) { return $this->entity_decode($match[0], strtoupper(config_item('charset'))); } // -------------------------------------------------------------------- /** * Validate URL entities * * Called by xss_clean() * * @param string * @return string */ protected function _validate_entities($str) { /* * Protect GET variables in URLs */ // 901119URL5918AMP18930PROTECT8198 $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str); /* * Validate standard character entities * * Add a semicolon if missing. We do this to enable * the conversion of entities to ASCII later. * */ $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str); /* * Validate UTF16 two byte encoding (x00) * * Just as above, adds a semicolon if missing. * */ $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str); /* * Un-Protect GET variables in URLs */ $str = str_replace($this->xss_hash(), '&', $str); return $str; } // ---------------------------------------------------------------------- /** * Do Never Allowed * * A utility function for xss_clean() * * @param string * @return string */ protected function _do_never_allowed($str) { $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str); foreach ($this->_never_allowed_regex as $regex) { $str = preg_replace('#'.$regex.'#is', '[removed]', $str); } return $str; } // -------------------------------------------------------------------- /** * Set Cross Site Request Forgery Protection Cookie * * @return string */ protected function _csrf_set_hash() { if ($this->_csrf_hash == '') { // If the cookie exists we will use it's value. // We don't necessarily want to regenerate it with // each page load since a page could contain embedded // sub-pages causing this feature to fail if (isset($_COOKIE[$this->_csrf_cookie_name]) && preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1) { return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name]; } return $this->_csrf_hash = md5(uniqid(rand(), TRUE)); } return $this->_csrf_hash; } } /* End of file Security.php */ /* Location: ./system/libraries/Security.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Lang.php
system/core/Lang.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Language Class * * @package CodeIgniter * @subpackage Libraries * @category Language * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/language.html */ class CI_Lang { /** * List of translations * * @var array */ var $language = array(); /** * List of loaded language files * * @var array */ var $is_loaded = array(); /** * Constructor * * @access public */ function __construct() { log_message('debug', "Language Class Initialized"); } // -------------------------------------------------------------------- /** * Load a language file * * @access public * @param mixed the name of the language file to be loaded. Can be an array * @param string the language (english, etc.) * @param bool return loaded array of translations * @param bool add suffix to $langfile * @param string alternative path to look for language file * @return mixed */ function load($langfile = '', $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '') { $langfile = str_replace('.php', '', $langfile); if ($add_suffix == TRUE) { $langfile = str_replace('_lang.', '', $langfile).'_lang'; } $langfile .= '.php'; if (in_array($langfile, $this->is_loaded, TRUE)) { return; } $config =& get_config(); if ($idiom == '') { $deft_lang = ( ! isset($config['language'])) ? 'english' : $config['language']; $idiom = ($deft_lang == '') ? 'english' : $deft_lang; } // Determine where the language file is and load it if ($alt_path != '' && file_exists($alt_path.'language/'.$idiom.'/'.$langfile)) { include($alt_path.'language/'.$idiom.'/'.$langfile); } else { $found = FALSE; foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) { if (file_exists($package_path.'language/'.$idiom.'/'.$langfile)) { include($package_path.'language/'.$idiom.'/'.$langfile); $found = TRUE; break; } } if ($found !== TRUE) { show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile); } } if ( ! isset($lang)) { log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile); return; } if ($return == TRUE) { return $lang; } $this->is_loaded[] = $langfile; $this->language = array_merge($this->language, $lang); unset($lang); log_message('debug', 'Language file loaded: language/'.$idiom.'/'.$langfile); return TRUE; } // -------------------------------------------------------------------- /** * Fetch a single line of text from the language array * * @access public * @param string $line the language line * @return string */ function line($line = '') { $value = ($line == '' OR ! isset($this->language[$line])) ? FALSE : $this->language[$line]; // Because killer robots like unicorns! if ($value === FALSE) { log_message('error', 'Could not find the language line "'.$line.'"'); } return $value; } } // END Language Class /* End of file Lang.php */ /* Location: ./system/core/Lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Config.php
system/core/Config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Config Class * * This class contains functions that enable config files to be managed * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/config.html */ class CI_Config { /** * List of all loaded config values * * @var array */ var $config = array(); /** * List of all loaded config files * * @var array */ var $is_loaded = array(); /** * List of paths to search when trying to load a config file * * @var array */ var $_config_paths = array(APPPATH); /** * Constructor * * Sets the $config data from the primary config.php file as a class variable * * @access public * @param string the config file name * @param boolean if configuration values should be loaded into their own section * @param boolean true if errors should just return false, false if an error message should be displayed * @return boolean if the file was successfully loaded or not */ function __construct() { $this->config =& get_config(); log_message('debug', "Config Class Initialized"); // Set the base_url automatically if none was provided if ($this->config['base_url'] == '') { if (isset($_SERVER['HTTP_HOST'])) { $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; $base_url .= '://'. $_SERVER['HTTP_HOST']; $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); } else { $base_url = 'http://localhost/'; } $this->set_item('base_url', $base_url); } } // -------------------------------------------------------------------- /** * Load Config File * * @access public * @param string the config file name * @param boolean if configuration values should be loaded into their own section * @param boolean true if errors should just return false, false if an error message should be displayed * @return boolean if the file was loaded correctly */ function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { $file = ($file == '') ? 'config' : str_replace('.php', '', $file); $found = FALSE; $loaded = FALSE; $check_locations = defined('ENVIRONMENT') ? array(ENVIRONMENT.'/'.$file, $file) : array($file); foreach ($this->_config_paths as $path) { foreach ($check_locations as $location) { $file_path = $path.'config/'.$location.'.php'; if (in_array($file_path, $this->is_loaded, TRUE)) { $loaded = TRUE; continue 2; } if (file_exists($file_path)) { $found = TRUE; break; } } if ($found === FALSE) { continue; } include($file_path); if ( ! isset($config) OR ! is_array($config)) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); } if ($use_sections === TRUE) { if (isset($this->config[$file])) { $this->config[$file] = array_merge($this->config[$file], $config); } else { $this->config[$file] = $config; } } else { $this->config = array_merge($this->config, $config); } $this->is_loaded[] = $file_path; unset($config); $loaded = TRUE; log_message('debug', 'Config file loaded: '.$file_path); break; } if ($loaded === FALSE) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('The configuration file '.$file.'.php does not exist.'); } return TRUE; } // -------------------------------------------------------------------- /** * Fetch a config file item * * * @access public * @param string the config item name * @param string the index name * @param bool * @return string */ function item($item, $index = '') { if ($index == '') { if ( ! isset($this->config[$item])) { return FALSE; } $pref = $this->config[$item]; } else { if ( ! isset($this->config[$index])) { return FALSE; } if ( ! isset($this->config[$index][$item])) { return FALSE; } $pref = $this->config[$index][$item]; } return $pref; } // -------------------------------------------------------------------- /** * Fetch a config file item - adds slash after item (if item is not empty) * * @access public * @param string the config item name * @param bool * @return string */ function slash_item($item) { if ( ! isset($this->config[$item])) { return FALSE; } if( trim($this->config[$item]) == '') { return ''; } return rtrim($this->config[$item], '/').'/'; } // -------------------------------------------------------------------- /** * Site URL * Returns base_url . index_page [. uri_string] * * @access public * @param string the URI string * @return string */ function site_url($uri = '') { if ($uri == '') { return $this->slash_item('base_url').$this->item('index_page'); } if ($this->item('enable_query_strings') == FALSE) { $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix'); return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix; } else { return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri); } } // ------------------------------------------------------------- /** * Base URL * Returns base_url [. uri_string] * * @access public * @param string $uri * @return string */ function base_url($uri = '') { return $this->slash_item('base_url').ltrim($this->_uri_string($uri), '/'); } // ------------------------------------------------------------- /** * Build URI string for use in Config::site_url() and Config::base_url() * * @access protected * @param $uri * @return string */ protected function _uri_string($uri) { if ($this->item('enable_query_strings') == FALSE) { if (is_array($uri)) { $uri = implode('/', $uri); } $uri = trim($uri, '/'); } else { if (is_array($uri)) { $i = 0; $str = ''; foreach ($uri as $key => $val) { $prefix = ($i == 0) ? '' : '&'; $str .= $prefix.$key.'='.$val; $i++; } $uri = $str; } } return $uri; } // -------------------------------------------------------------------- /** * System URL * * @access public * @return string */ function system_url() { $x = explode("/", preg_replace("|/*(.+?)/*$|", "\\1", BASEPATH)); return $this->slash_item('base_url').end($x).'/'; } // -------------------------------------------------------------------- /** * Set a config file item * * @access public * @param string the config item key * @param string the config item value * @return void */ function set_item($item, $value) { $this->config[$item] = $value; } // -------------------------------------------------------------------- /** * Assign to Config * * This function is called by the front controller (CodeIgniter.php) * after the Config class is instantiated. It permits config items * to be assigned or overriden by variables contained in the index.php file * * @access private * @param array * @return void */ function _assign_to_config($items = array()) { if (is_array($items)) { foreach ($items as $key => $val) { $this->set_item($key, $val); } } } } // END CI_Config class /* End of file Config.php */ /* Location: ./system/core/Config.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Router.php
system/core/Router.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Router Class * * Parses URIs and determines routing * * @package CodeIgniter * @subpackage Libraries * @author ExpressionEngine Dev Team * @category Libraries * @link http://codeigniter.com/user_guide/general/routing.html */ class CI_Router { /** * Config class * * @var object * @access public */ var $config; /** * List of routes * * @var array * @access public */ var $routes = array(); /** * List of error routes * * @var array * @access public */ var $error_routes = array(); /** * Current class name * * @var string * @access public */ var $class = ''; /** * Current method name * * @var string * @access public */ var $method = 'index'; /** * Sub-directory that contains the requested controller class * * @var string * @access public */ var $directory = ''; /** * Default controller (and method if specific) * * @var string * @access public */ var $default_controller; /** * Constructor * * Runs the route mapping function. */ function __construct() { $this->config =& load_class('Config', 'core'); $this->uri =& load_class('URI', 'core'); log_message('debug', "Router Class Initialized"); } // -------------------------------------------------------------------- /** * Set the route mapping * * This function determines what should be served based on the URI request, * as well as any "routes" that have been set in the routing config file. * * @access private * @return void */ function _set_routing() { // Are query strings enabled in the config file? Normally CI doesn't utilize query strings // since URI segments are more search-engine friendly, but they can optionally be used. // If this feature is enabled, we will gather the directory/class/method a little differently $segments = array(); if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')])) { if (isset($_GET[$this->config->item('directory_trigger')])) { $this->set_directory(trim($this->uri->_filter_uri($_GET[$this->config->item('directory_trigger')]))); $segments[] = $this->fetch_directory(); } if (isset($_GET[$this->config->item('controller_trigger')])) { $this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')]))); $segments[] = $this->fetch_class(); } if (isset($_GET[$this->config->item('function_trigger')])) { $this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')]))); $segments[] = $this->fetch_method(); } } // Load the routes.php file. if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/routes.php'); } elseif (is_file(APPPATH.'config/routes.php')) { include(APPPATH.'config/routes.php'); } $this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route; unset($route); // Set the default controller so we can display it in the event // the URI doesn't correlated to a valid controller. $this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']); // Were there any query string segments? If so, we'll validate them and bail out since we're done. if (count($segments) > 0) { return $this->_validate_request($segments); } // Fetch the complete URI string $this->uri->_fetch_uri_string(); // Is there a URI string? If not, the default controller specified in the "routes" file will be shown. if ($this->uri->uri_string == '') { return $this->_set_default_controller(); } // Do we need to remove the URL suffix? $this->uri->_remove_url_suffix(); // Compile the segments into an array $this->uri->_explode_segments(); // Parse any custom routing that may exist $this->_parse_routes(); // Re-index the segment array so that it starts with 1 rather than 0 $this->uri->_reindex_segments(); } // -------------------------------------------------------------------- /** * Set the default controller * * @access private * @return void */ function _set_default_controller() { if ($this->default_controller === FALSE) { show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file."); } // Is the method being specified? if (strpos($this->default_controller, '/') !== FALSE) { $x = explode('/', $this->default_controller); $this->set_class($x[0]); $this->set_method($x[1]); $this->_set_request($x); } else { $this->set_class($this->default_controller); $this->set_method('index'); $this->_set_request(array($this->default_controller, 'index')); } // re-index the routed segments array so it starts with 1 rather than 0 $this->uri->_reindex_segments(); log_message('debug', "No URI present. Default controller set."); } // -------------------------------------------------------------------- /** * Set the Route * * This function takes an array of URI segments as * input, and sets the current class/method * * @access private * @param array * @param bool * @return void */ function _set_request($segments = array()) { $segments = $this->_validate_request($segments); if (count($segments) == 0) { return $this->_set_default_controller(); } $this->set_class($segments[0]); if (isset($segments[1])) { // A standard method request $this->set_method($segments[1]); } else { // This lets the "routed" segment array identify that the default // index method is being used. $segments[1] = 'index'; } // Update our "routed" segment array to contain the segments. // Note: If there is no custom routing, this array will be // identical to $this->uri->segments $this->uri->rsegments = $segments; } // -------------------------------------------------------------------- /** * Validates the supplied segments. Attempts to determine the path to * the controller. * * @access private * @param array * @return array */ function _validate_request($segments) { if (count($segments) == 0) { return $segments; } // Does the requested controller exist in the root folder? if (file_exists(APPPATH.'controllers/'.$segments[0].'.php')) { return $segments; } // Is the controller in a sub-folder? if (is_dir(APPPATH.'controllers/'.$segments[0])) { // Set the directory and remove it from the segment array $this->set_directory($segments[0]); $segments = array_slice($segments, 1); if (count($segments) > 0) { // Does the requested controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].'.php')) { if ( ! empty($this->routes['404_override'])) { $x = explode('/', $this->routes['404_override']); $this->set_directory(''); $this->set_class($x[0]); $this->set_method(isset($x[1]) ? $x[1] : 'index'); return $x; } else { show_404($this->fetch_directory().$segments[0]); } } } else { // Is the method being specified in the route? if (strpos($this->default_controller, '/') !== FALSE) { $x = explode('/', $this->default_controller); $this->set_class($x[0]); $this->set_method($x[1]); } else { $this->set_class($this->default_controller); $this->set_method('index'); } // Does the default controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')) { $this->directory = ''; return array(); } } return $segments; } // If we've gotten this far it means that the URI does not correlate to a valid // controller class. We will now see if there is an override if ( ! empty($this->routes['404_override'])) { $x = explode('/', $this->routes['404_override']); $this->set_class($x[0]); $this->set_method(isset($x[1]) ? $x[1] : 'index'); return $x; } // Nothing else to do at this point but show a 404 show_404($segments[0]); } // -------------------------------------------------------------------- /** * Parse Routes * * This function matches any routes that may exist in * the config/routes.php file against the URI to * determine if the class/method need to be remapped. * * @access private * @return void */ function _parse_routes() { // Turn the segment array into a URI string $uri = implode('/', $this->uri->segments); // Is there a literal match? If so we're done if (isset($this->routes[$uri])) { return $this->_set_request(explode('/', $this->routes[$uri])); } // Loop through the route array looking for wild-cards foreach ($this->routes as $key => $val) { // Convert wild-cards to RegEx $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key)); // Does the RegEx match? if (preg_match('#^'.$key.'$#', $uri)) { // Do we have a back-reference? if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE) { $val = preg_replace('#^'.$key.'$#', $val, $uri); } return $this->_set_request(explode('/', $val)); } } // If we got this far it means we didn't encounter a // matching route so we'll set the site default route $this->_set_request($this->uri->segments); } // -------------------------------------------------------------------- /** * Set the class name * * @access public * @param string * @return void */ function set_class($class) { $this->class = str_replace(array('/', '.'), '', $class); } // -------------------------------------------------------------------- /** * Fetch the current class * * @access public * @return string */ function fetch_class() { return $this->class; } // -------------------------------------------------------------------- /** * Set the method name * * @access public * @param string * @return void */ function set_method($method) { $this->method = $method; } // -------------------------------------------------------------------- /** * Fetch the current method * * @access public * @return string */ function fetch_method() { if ($this->method == $this->fetch_class()) { return 'index'; } return $this->method; } // -------------------------------------------------------------------- /** * Set the directory name * * @access public * @param string * @return void */ function set_directory($dir) { $this->directory = str_replace(array('/', '.'), '', $dir).'/'; } // -------------------------------------------------------------------- /** * Fetch the sub-directory (if any) that contains the requested controller class * * @access public * @return string */ function fetch_directory() { return $this->directory; } // -------------------------------------------------------------------- /** * Set the controller overrides * * @access public * @param array * @return null */ function _set_overrides($routing) { if ( ! is_array($routing)) { return; } if (isset($routing['directory'])) { $this->set_directory($routing['directory']); } if (isset($routing['controller']) AND $routing['controller'] != '') { $this->set_class($routing['controller']); } if (isset($routing['function'])) { $routing['function'] = ($routing['function'] == '') ? 'index' : $routing['function']; $this->set_method($routing['function']); } } } // END Router Class /* End of file Router.php */ /* Location: ./system/core/Router.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Model.php
system/core/Model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Model Class * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/config.html */ class CI_Model { /** * Constructor * * @access public */ function __construct() { log_message('debug', "Model Class Initialized"); } /** * __get * * Allows models to access CI's loaded classes using the same * syntax as controllers. * * @param string * @access private */ function __get($key) { $CI =& get_instance(); return $CI->$key; } } // END Model Class /* End of file Model.php */ /* Location: ./system/core/Model.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/core/Hooks.php
system/core/Hooks.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Hooks Class * * Provides a mechanism to extend the base system without hacking. * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/encryption.html */ class CI_Hooks { /** * Determines wether hooks are enabled * * @var bool */ var $enabled = FALSE; /** * List of all hooks set in config/hooks.php * * @var array */ var $hooks = array(); /** * Determines wether hook is in progress, used to prevent infinte loops * * @var bool */ var $in_progress = FALSE; /** * Constructor * */ function __construct() { $this->_initialize(); log_message('debug', "Hooks Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize the Hooks Preferences * * @access private * @return void */ function _initialize() { $CFG =& load_class('Config', 'core'); // If hooks are not enabled in the config file // there is nothing else to do if ($CFG->item('enable_hooks') == FALSE) { return; } // Grab the "hooks" definition file. // If there are no hooks, we're done. if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/hooks.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/hooks.php'); } elseif (is_file(APPPATH.'config/hooks.php')) { include(APPPATH.'config/hooks.php'); } if ( ! isset($hook) OR ! is_array($hook)) { return; } $this->hooks =& $hook; $this->enabled = TRUE; } // -------------------------------------------------------------------- /** * Call Hook * * Calls a particular hook * * @access private * @param string the hook name * @return mixed */ function _call_hook($which = '') { if ( ! $this->enabled OR ! isset($this->hooks[$which])) { return FALSE; } if (isset($this->hooks[$which][0]) AND is_array($this->hooks[$which][0])) { foreach ($this->hooks[$which] as $val) { $this->_run_hook($val); } } else { $this->_run_hook($this->hooks[$which]); } return TRUE; } // -------------------------------------------------------------------- /** * Run Hook * * Runs a particular hook * * @access private * @param array the hook details * @return bool */ function _run_hook($data) { if ( ! is_array($data)) { return FALSE; } // ----------------------------------- // Safety - Prevents run-away loops // ----------------------------------- // If the script being called happens to have the same // hook call within it a loop can happen if ($this->in_progress == TRUE) { return; } // ----------------------------------- // Set file path // ----------------------------------- if ( ! isset($data['filepath']) OR ! isset($data['filename'])) { return FALSE; } $filepath = APPPATH.$data['filepath'].'/'.$data['filename']; if ( ! file_exists($filepath)) { return FALSE; } // ----------------------------------- // Set class/function name // ----------------------------------- $class = FALSE; $function = FALSE; $params = ''; if (isset($data['class']) AND $data['class'] != '') { $class = $data['class']; } if (isset($data['function'])) { $function = $data['function']; } if (isset($data['params'])) { $params = $data['params']; } if ($class === FALSE AND $function === FALSE) { return FALSE; } // ----------------------------------- // Set the in_progress flag // ----------------------------------- $this->in_progress = TRUE; // ----------------------------------- // Call the requested class and/or function // ----------------------------------- if ($class !== FALSE) { if ( ! class_exists($class)) { require($filepath); } $HOOK = new $class; $HOOK->$function($params); } else { if ( ! function_exists($function)) { require($filepath); } $function($params); } $this->in_progress = FALSE; return TRUE; } } // END CI_Hooks class /* End of file Hooks.php */ /* Location: ./system/core/Hooks.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/DB_forge.php
system/database/DB_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Code Igniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Database Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_forge { var $fields = array(); var $keys = array(); var $primary_keys = array(); var $db_char_set = ''; /** * Constructor * * Grabs the CI super object instance so we can access it. * */ function __construct() { // Assign the main database object to $this->db $CI =& get_instance(); $this->db =& $CI->db; log_message('debug', "Database Forge Class Initialized"); } // -------------------------------------------------------------------- /** * Create database * * @access public * @param string the database name * @return bool */ function create_database($db_name) { $sql = $this->_create_database($db_name); if (is_bool($sql)) { return $sql; } return $this->db->query($sql); } // -------------------------------------------------------------------- /** * Drop database * * @access public * @param string the database name * @return bool */ function drop_database($db_name) { $sql = $this->_drop_database($db_name); if (is_bool($sql)) { return $sql; } return $this->db->query($sql); } // -------------------------------------------------------------------- /** * Add Key * * @access public * @param string key * @param string type * @return void */ function add_key($key = '', $primary = FALSE) { if (is_array($key)) { foreach ($key as $one) { $this->add_key($one, $primary); } return; } if ($key == '') { show_error('Key information is required for that operation.'); } if ($primary === TRUE) { $this->primary_keys[] = $key; } else { $this->keys[] = $key; } } // -------------------------------------------------------------------- /** * Add Field * * @access public * @param string collation * @return void */ function add_field($field = '') { if ($field == '') { show_error('Field information is required.'); } if (is_string($field)) { if ($field == 'id') { $this->add_field(array( 'id' => array( 'type' => 'INT', 'constraint' => 9, 'auto_increment' => TRUE ) )); $this->add_key('id', TRUE); } else { if (strpos($field, ' ') === FALSE) { show_error('Field information is required for that operation.'); } $this->fields[] = $field; } } if (is_array($field)) { $this->fields = array_merge($this->fields, $field); } } // -------------------------------------------------------------------- /** * Create Table * * @access public * @param string the table name * @return bool */ function create_table($table = '', $if_not_exists = FALSE) { if ($table == '') { show_error('A table name is required for that operation.'); } if (count($this->fields) == 0) { show_error('Field information is required.'); } $sql = $this->_create_table($this->db->dbprefix.$table, $this->fields, $this->primary_keys, $this->keys, $if_not_exists); $this->_reset(); return $this->db->query($sql); } // -------------------------------------------------------------------- /** * Drop Table * * @access public * @param string the table name * @return bool */ function drop_table($table_name) { $sql = $this->_drop_table($this->db->dbprefix.$table_name); if (is_bool($sql)) { return $sql; } return $this->db->query($sql); } // -------------------------------------------------------------------- /** * Rename Table * * @access public * @param string the old table name * @param string the new table name * @return bool */ function rename_table($table_name, $new_table_name) { if ($table_name == '' OR $new_table_name == '') { show_error('A table name is required for that operation.'); } $sql = $this->_rename_table($this->db->dbprefix.$table_name, $this->db->dbprefix.$new_table_name); return $this->db->query($sql); } // -------------------------------------------------------------------- /** * Column Add * * @access public * @param string the table name * @param string the column name * @param string the column definition * @return bool */ function add_column($table = '', $field = array(), $after_field = '') { if ($table == '') { show_error('A table name is required for that operation.'); } // add field info into field array, but we can only do one at a time // so we cycle through foreach ($field as $k => $v) { $this->add_field(array($k => $field[$k])); if (count($this->fields) == 0) { show_error('Field information is required.'); } $sql = $this->_alter_table('ADD', $this->db->dbprefix.$table, $this->fields, $after_field); $this->_reset(); if ($this->db->query($sql) === FALSE) { return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * Column Drop * * @access public * @param string the table name * @param string the column name * @return bool */ function drop_column($table = '', $column_name = '') { if ($table == '') { show_error('A table name is required for that operation.'); } if ($column_name == '') { show_error('A column name is required for that operation.'); } $sql = $this->_alter_table('DROP', $this->db->dbprefix.$table, $column_name); return $this->db->query($sql); } // -------------------------------------------------------------------- /** * Column Modify * * @access public * @param string the table name * @param string the column name * @param string the column definition * @return bool */ function modify_column($table = '', $field = array()) { if ($table == '') { show_error('A table name is required for that operation.'); } // add field info into field array, but we can only do one at a time // so we cycle through foreach ($field as $k => $v) { // If no name provided, use the current name if ( ! isset($field[$k]['name'])) { $field[$k]['name'] = $k; } $this->add_field(array($k => $field[$k])); if (count($this->fields) == 0) { show_error('Field information is required.'); } $sql = $this->_alter_table('CHANGE', $this->db->dbprefix.$table, $this->fields); $this->_reset(); if ($this->db->query($sql) === FALSE) { return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * Reset * * Resets table creation vars * * @access private * @return void */ function _reset() { $this->fields = array(); $this->keys = array(); $this->primary_keys = array(); } } /* End of file DB_forge.php */ /* Location: ./system/database/DB_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/DB_active_rec.php
system/database/DB_active_rec.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Active Record Class * * This is the platform-independent base Active Record implementation class. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_active_record extends CI_DB_driver { var $ar_select = array(); var $ar_distinct = FALSE; var $ar_from = array(); var $ar_join = array(); var $ar_where = array(); var $ar_like = array(); var $ar_groupby = array(); var $ar_having = array(); var $ar_keys = array(); var $ar_limit = FALSE; var $ar_offset = FALSE; var $ar_order = FALSE; var $ar_orderby = array(); var $ar_set = array(); var $ar_wherein = array(); var $ar_aliased_tables = array(); var $ar_store_array = array(); // Active Record Caching variables var $ar_caching = FALSE; var $ar_cache_exists = array(); var $ar_cache_select = array(); var $ar_cache_from = array(); var $ar_cache_join = array(); var $ar_cache_where = array(); var $ar_cache_like = array(); var $ar_cache_groupby = array(); var $ar_cache_having = array(); var $ar_cache_orderby = array(); var $ar_cache_set = array(); var $ar_no_escape = array(); var $ar_cache_no_escape = array(); // -------------------------------------------------------------------- /** * Select * * Generates the SELECT portion of the query * * @param string * @return object */ public function select($select = '*', $escape = NULL) { if (is_string($select)) { $select = explode(',', $select); } foreach ($select as $val) { $val = trim($val); if ($val != '') { $this->ar_select[] = $val; $this->ar_no_escape[] = $escape; if ($this->ar_caching === TRUE) { $this->ar_cache_select[] = $val; $this->ar_cache_exists[] = 'select'; $this->ar_cache_no_escape[] = $escape; } } } return $this; } // -------------------------------------------------------------------- /** * Select Max * * Generates a SELECT MAX(field) portion of a query * * @param string the field * @param string an alias * @return object */ public function select_max($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'MAX'); } // -------------------------------------------------------------------- /** * Select Min * * Generates a SELECT MIN(field) portion of a query * * @param string the field * @param string an alias * @return object */ public function select_min($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'MIN'); } // -------------------------------------------------------------------- /** * Select Average * * Generates a SELECT AVG(field) portion of a query * * @param string the field * @param string an alias * @return object */ public function select_avg($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'AVG'); } // -------------------------------------------------------------------- /** * Select Sum * * Generates a SELECT SUM(field) portion of a query * * @param string the field * @param string an alias * @return object */ public function select_sum($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'SUM'); } // -------------------------------------------------------------------- /** * Processing Function for the four functions above: * * select_max() * select_min() * select_avg() * select_sum() * * @param string the field * @param string an alias * @return object */ protected function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX') { if ( ! is_string($select) OR $select == '') { $this->display_error('db_invalid_query'); } $type = strtoupper($type); if ( ! in_array($type, array('MAX', 'MIN', 'AVG', 'SUM'))) { show_error('Invalid function type: '.$type); } if ($alias == '') { $alias = $this->_create_alias_from_table(trim($select)); } $sql = $type.'('.$this->_protect_identifiers(trim($select)).') AS '.$alias; $this->ar_select[] = $sql; if ($this->ar_caching === TRUE) { $this->ar_cache_select[] = $sql; $this->ar_cache_exists[] = 'select'; } return $this; } // -------------------------------------------------------------------- /** * Determines the alias name based on the table * * @param string * @return string */ protected function _create_alias_from_table($item) { if (strpos($item, '.') !== FALSE) { return end(explode('.', $item)); } return $item; } // -------------------------------------------------------------------- /** * DISTINCT * * Sets a flag which tells the query string compiler to add DISTINCT * * @param bool * @return object */ public function distinct($val = TRUE) { $this->ar_distinct = (is_bool($val)) ? $val : TRUE; return $this; } // -------------------------------------------------------------------- /** * From * * Generates the FROM portion of the query * * @param mixed can be a string or array * @return object */ public function from($from) { foreach ((array) $from as $val) { if (strpos($val, ',') !== FALSE) { foreach (explode(',', $val) as $v) { $v = trim($v); $this->_track_aliases($v); $this->ar_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE); if ($this->ar_caching === TRUE) { $this->ar_cache_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE); $this->ar_cache_exists[] = 'from'; } } } else { $val = trim($val); // Extract any aliases that might exist. We use this information // in the _protect_identifiers to know whether to add a table prefix $this->_track_aliases($val); $this->ar_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE); if ($this->ar_caching === TRUE) { $this->ar_cache_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE); $this->ar_cache_exists[] = 'from'; } } } return $this; } // -------------------------------------------------------------------- /** * Join * * Generates the JOIN portion of the query * * @param string * @param string the join condition * @param string the type of join * @return object */ public function join($table, $cond, $type = '') { if ($type != '') { $type = strtoupper(trim($type)); if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'))) { $type = ''; } else { $type .= ' '; } } // Extract any aliases that might exist. We use this information // in the _protect_identifiers to know whether to add a table prefix $this->_track_aliases($table); // Strip apart the condition and protect the identifiers if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match)) { $match[1] = $this->_protect_identifiers($match[1]); $match[3] = $this->_protect_identifiers($match[3]); $cond = $match[1].$match[2].$match[3]; } // Assemble the JOIN statement $join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond; $this->ar_join[] = $join; if ($this->ar_caching === TRUE) { $this->ar_cache_join[] = $join; $this->ar_cache_exists[] = 'join'; } return $this; } // -------------------------------------------------------------------- /** * Where * * Generates the WHERE portion of the query. Separates * multiple calls with AND * * @param mixed * @param mixed * @return object */ public function where($key, $value = NULL, $escape = TRUE) { return $this->_where($key, $value, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR Where * * Generates the WHERE portion of the query. Separates * multiple calls with OR * * @param mixed * @param mixed * @return object */ public function or_where($key, $value = NULL, $escape = TRUE) { return $this->_where($key, $value, 'OR ', $escape); } // -------------------------------------------------------------------- /** * Where * * Called by where() or or_where() * * @param mixed * @param mixed * @param string * @return object */ protected function _where($key, $value = NULL, $type = 'AND ', $escape = NULL) { if ( ! is_array($key)) { $key = array($key => $value); } // If the escape value was not set will will base it on the global setting if ( ! is_bool($escape)) { $escape = $this->_protect_identifiers; } foreach ($key as $k => $v) { $prefix = (count($this->ar_where) == 0 AND count($this->ar_cache_where) == 0) ? '' : $type; if (is_null($v) && ! $this->_has_operator($k)) { // value appears not to have been set, assign the test to IS NULL $k .= ' IS NULL'; } if ( ! is_null($v)) { if ($escape === TRUE) { $k = $this->_protect_identifiers($k, FALSE, $escape); $v = ' '.$this->escape($v); } if ( ! $this->_has_operator($k)) { $k .= ' = '; } } else { $k = $this->_protect_identifiers($k, FALSE, $escape); } $this->ar_where[] = $prefix.$k.$v; if ($this->ar_caching === TRUE) { $this->ar_cache_where[] = $prefix.$k.$v; $this->ar_cache_exists[] = 'where'; } } return $this; } // -------------------------------------------------------------------- /** * Where_in * * Generates a WHERE field IN ('item', 'item') SQL query joined with * AND if appropriate * * @param string The field to search * @param array The values searched on * @return object */ public function where_in($key = NULL, $values = NULL) { return $this->_where_in($key, $values); } // -------------------------------------------------------------------- /** * Where_in_or * * Generates a WHERE field IN ('item', 'item') SQL query joined with * OR if appropriate * * @param string The field to search * @param array The values searched on * @return object */ public function or_where_in($key = NULL, $values = NULL) { return $this->_where_in($key, $values, FALSE, 'OR '); } // -------------------------------------------------------------------- /** * Where_not_in * * Generates a WHERE field NOT IN ('item', 'item') SQL query joined * with AND if appropriate * * @param string The field to search * @param array The values searched on * @return object */ public function where_not_in($key = NULL, $values = NULL) { return $this->_where_in($key, $values, TRUE); } // -------------------------------------------------------------------- /** * Where_not_in_or * * Generates a WHERE field NOT IN ('item', 'item') SQL query joined * with OR if appropriate * * @param string The field to search * @param array The values searched on * @return object */ public function or_where_not_in($key = NULL, $values = NULL) { return $this->_where_in($key, $values, TRUE, 'OR '); } // -------------------------------------------------------------------- /** * Where_in * * Called by where_in, where_in_or, where_not_in, where_not_in_or * * @param string The field to search * @param array The values searched on * @param boolean If the statement would be IN or NOT IN * @param string * @return object */ protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ') { if ($key === NULL OR $values === NULL) { return; } if ( ! is_array($values)) { $values = array($values); } $not = ($not) ? ' NOT' : ''; foreach ($values as $value) { $this->ar_wherein[] = $this->escape($value); } $prefix = (count($this->ar_where) == 0) ? '' : $type; $where_in = $prefix . $this->_protect_identifiers($key) . $not . " IN (" . implode(", ", $this->ar_wherein) . ") "; $this->ar_where[] = $where_in; if ($this->ar_caching === TRUE) { $this->ar_cache_where[] = $where_in; $this->ar_cache_exists[] = 'where'; } // reset the array for multiple calls $this->ar_wherein = array(); return $this; } // -------------------------------------------------------------------- /** * Like * * Generates a %LIKE% portion of the query. Separates * multiple calls with AND * * @param mixed * @param mixed * @return object */ public function like($field, $match = '', $side = 'both') { return $this->_like($field, $match, 'AND ', $side); } // -------------------------------------------------------------------- /** * Not Like * * Generates a NOT LIKE portion of the query. Separates * multiple calls with AND * * @param mixed * @param mixed * @return object */ public function not_like($field, $match = '', $side = 'both') { return $this->_like($field, $match, 'AND ', $side, 'NOT'); } // -------------------------------------------------------------------- /** * OR Like * * Generates a %LIKE% portion of the query. Separates * multiple calls with OR * * @param mixed * @param mixed * @return object */ public function or_like($field, $match = '', $side = 'both') { return $this->_like($field, $match, 'OR ', $side); } // -------------------------------------------------------------------- /** * OR Not Like * * Generates a NOT LIKE portion of the query. Separates * multiple calls with OR * * @param mixed * @param mixed * @return object */ public function or_not_like($field, $match = '', $side = 'both') { return $this->_like($field, $match, 'OR ', $side, 'NOT'); } // -------------------------------------------------------------------- /** * Like * * Called by like() or orlike() * * @param mixed * @param mixed * @param string * @return object */ protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '') { if ( ! is_array($field)) { $field = array($field => $match); } foreach ($field as $k => $v) { $k = $this->_protect_identifiers($k); $prefix = (count($this->ar_like) == 0) ? '' : $type; $v = $this->escape_like_str($v); if ($side == 'none') { $like_statement = $prefix." $k $not LIKE '{$v}'"; } elseif ($side == 'before') { $like_statement = $prefix." $k $not LIKE '%{$v}'"; } elseif ($side == 'after') { $like_statement = $prefix." $k $not LIKE '{$v}%'"; } else { $like_statement = $prefix." $k $not LIKE '%{$v}%'"; } // some platforms require an escape sequence definition for LIKE wildcards if ($this->_like_escape_str != '') { $like_statement = $like_statement.sprintf($this->_like_escape_str, $this->_like_escape_chr); } $this->ar_like[] = $like_statement; if ($this->ar_caching === TRUE) { $this->ar_cache_like[] = $like_statement; $this->ar_cache_exists[] = 'like'; } } return $this; } // -------------------------------------------------------------------- /** * GROUP BY * * @param string * @return object */ public function group_by($by) { if (is_string($by)) { $by = explode(',', $by); } foreach ($by as $val) { $val = trim($val); if ($val != '') { $this->ar_groupby[] = $this->_protect_identifiers($val); if ($this->ar_caching === TRUE) { $this->ar_cache_groupby[] = $this->_protect_identifiers($val); $this->ar_cache_exists[] = 'groupby'; } } } return $this; } // -------------------------------------------------------------------- /** * Sets the HAVING value * * Separates multiple calls with AND * * @param string * @param string * @return object */ public function having($key, $value = '', $escape = TRUE) { return $this->_having($key, $value, 'AND ', $escape); } // -------------------------------------------------------------------- /** * Sets the OR HAVING value * * Separates multiple calls with OR * * @param string * @param string * @return object */ public function or_having($key, $value = '', $escape = TRUE) { return $this->_having($key, $value, 'OR ', $escape); } // -------------------------------------------------------------------- /** * Sets the HAVING values * * Called by having() or or_having() * * @param string * @param string * @return object */ protected function _having($key, $value = '', $type = 'AND ', $escape = TRUE) { if ( ! is_array($key)) { $key = array($key => $value); } foreach ($key as $k => $v) { $prefix = (count($this->ar_having) == 0) ? '' : $type; if ($escape === TRUE) { $k = $this->_protect_identifiers($k); } if ( ! $this->_has_operator($k)) { $k .= ' = '; } if ($v != '') { $v = ' '.$this->escape($v); } $this->ar_having[] = $prefix.$k.$v; if ($this->ar_caching === TRUE) { $this->ar_cache_having[] = $prefix.$k.$v; $this->ar_cache_exists[] = 'having'; } } return $this; } // -------------------------------------------------------------------- /** * Sets the ORDER BY value * * @param string * @param string direction: asc or desc * @return object */ public function order_by($orderby, $direction = '') { if (strtolower($direction) == 'random') { $orderby = ''; // Random results want or don't need a field name $direction = $this->_random_keyword; } elseif (trim($direction) != '') { $direction = (in_array(strtoupper(trim($direction)), array('ASC', 'DESC'), TRUE)) ? ' '.$direction : ' ASC'; } if (strpos($orderby, ',') !== FALSE) { $temp = array(); foreach (explode(',', $orderby) as $part) { $part = trim($part); if ( ! in_array($part, $this->ar_aliased_tables)) { $part = $this->_protect_identifiers(trim($part)); } $temp[] = $part; } $orderby = implode(', ', $temp); } else if ($direction != $this->_random_keyword) { $orderby = $this->_protect_identifiers($orderby); } $orderby_statement = $orderby.$direction; $this->ar_orderby[] = $orderby_statement; if ($this->ar_caching === TRUE) { $this->ar_cache_orderby[] = $orderby_statement; $this->ar_cache_exists[] = 'orderby'; } return $this; } // -------------------------------------------------------------------- /** * Sets the LIMIT value * * @param integer the limit value * @param integer the offset value * @return object */ public function limit($value, $offset = '') { $this->ar_limit = (int) $value; if ($offset != '') { $this->ar_offset = (int) $offset; } return $this; } // -------------------------------------------------------------------- /** * Sets the OFFSET value * * @param integer the offset value * @return object */ public function offset($offset) { $this->ar_offset = $offset; return $this; } // -------------------------------------------------------------------- /** * The "set" function. Allows key/value pairs to be set for inserting or updating * * @param mixed * @param string * @param boolean * @return object */ public function set($key, $value = '', $escape = TRUE) { $key = $this->_object_to_array($key); if ( ! is_array($key)) { $key = array($key => $value); } foreach ($key as $k => $v) { if ($escape === FALSE) { $this->ar_set[$this->_protect_identifiers($k)] = $v; } else { $this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v); } } return $this; } // -------------------------------------------------------------------- /** * Get * * Compiles the select statement based on the other functions called * and runs the query * * @param string the table * @param string the limit clause * @param string the offset clause * @return object */ public function get($table = '', $limit = null, $offset = null) { if ($table != '') { $this->_track_aliases($table); $this->from($table); } if ( ! is_null($limit)) { $this->limit($limit, $offset); } $sql = $this->_compile_select(); $result = $this->query($sql); $this->_reset_select(); return $result; } /** * "Count All Results" query * * Generates a platform-specific query string that counts all records * returned by an Active Record query. * * @param string * @return string */ public function count_all_results($table = '') { if ($table != '') { $this->_track_aliases($table); $this->from($table); } $sql = $this->_compile_select($this->_count_string . $this->_protect_identifiers('numrows')); $query = $this->query($sql); $this->_reset_select(); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * Get_Where * * Allows the where clause, limit and offset to be added directly * * @param string the where clause * @param string the limit clause * @param string the offset clause * @return object */ public function get_where($table = '', $where = null, $limit = null, $offset = null) { if ($table != '') { $this->from($table); } if ( ! is_null($where)) { $this->where($where); } if ( ! is_null($limit)) { $this->limit($limit, $offset); } $sql = $this->_compile_select(); $result = $this->query($sql); $this->_reset_select(); return $result; } // -------------------------------------------------------------------- /** * Insert_Batch * * Compiles batch insert strings and runs the queries * * @param string the table to retrieve the results from * @param array an associative array of insert values * @return object */ public function insert_batch($table = '', $set = NULL) { if ( ! is_null($set)) { $this->set_insert_batch($set); } if (count($this->ar_set) == 0) { if ($this->db_debug) { //No valid data array. Folds in cases where keys and values did not match up return $this->display_error('db_must_use_set'); } return FALSE; } if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } // Batch this baby for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100) { $sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100)); //echo $sql; $this->query($sql); } $this->_reset_write(); return TRUE; } // -------------------------------------------------------------------- /** * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts * * @param mixed * @param string * @param boolean * @return object */ public function set_insert_batch($key, $value = '', $escape = TRUE) { $key = $this->_object_to_array_batch($key); if ( ! is_array($key)) { $key = array($key => $value); } $keys = array_keys(current($key)); sort($keys); foreach ($key as $row) { if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0) { // batch function above returns an error on an empty array $this->ar_set[] = array(); return; } ksort($row); // puts $row in the same order as our keys if ($escape === FALSE) { $this->ar_set[] = '('.implode(',', $row).')'; } else { $clean = array(); foreach ($row as $value) { $clean[] = $this->escape($value); } $this->ar_set[] = '('.implode(',', $clean).')'; } } foreach ($keys as $k) { $this->ar_keys[] = $this->_protect_identifiers($k); } return $this; } // -------------------------------------------------------------------- /** * Insert * * Compiles an insert string and runs the query * * @param string the table to insert data into * @param array an associative array of insert values * @return object */ function insert($table = '', $set = NULL) { if ( ! is_null($set)) { $this->set($set); } if (count($this->ar_set) == 0) { if ($this->db_debug) { return $this->display_error('db_must_use_set'); } return FALSE; } if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } $sql = $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set)); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Replace * * Compiles an replace into string and runs the query * * @param string the table to replace data into * @param array an associative array of insert values * @return object */ public function replace($table = '', $set = NULL) { if ( ! is_null($set)) { $this->set($set); } if (count($this->ar_set) == 0) { if ($this->db_debug) { return $this->display_error('db_must_use_set'); } return FALSE; } if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } $sql = $this->_replace($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set)); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Update * * Compiles an update string and runs the query * * @param string the table to retrieve the results from * @param array an associative array of update values * @param mixed the where clause * @return object */ public function update($table = '', $set = NULL, $where = NULL, $limit = NULL) { // Combine any cached components with the current statements $this->_merge_cache(); if ( ! is_null($set)) { $this->set($set); } if (count($this->ar_set) == 0) { if ($this->db_debug) { return $this->display_error('db_must_use_set'); } return FALSE; } if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } if ($where != NULL) { $this->where($where); } if ($limit != NULL) { $this->limit($limit); } $sql = $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Update_Batch * * Compiles an update string and runs the query * * @param string the table to retrieve the results from * @param array an associative array of update values * @param string the where key * @return object */ public function update_batch($table = '', $set = NULL, $index = NULL) { // Combine any cached components with the current statements $this->_merge_cache(); if (is_null($index)) { if ($this->db_debug) { return $this->display_error('db_must_use_index'); } return FALSE; } if ( ! is_null($set)) { $this->set_update_batch($set, $index); } if (count($this->ar_set) == 0) { if ($this->db_debug) { return $this->display_error('db_must_use_set'); } return FALSE; } if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } // Batch this baby for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100) { $sql = $this->_update_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->ar_set, $i, 100), $this->_protect_identifiers($index), $this->ar_where); $this->query($sql); } $this->_reset_write(); } // -------------------------------------------------------------------- /** * The "set_update_batch" function. Allows key/value pairs to be set for batch updating * * @param array * @param string * @param boolean * @return object */ public function set_update_batch($key, $index = '', $escape = TRUE) { $key = $this->_object_to_array_batch($key); if ( ! is_array($key)) { // @todo error } foreach ($key as $k => $v) { $index_set = FALSE; $clean = array(); foreach ($v as $k2 => $v2) { if ($k2 == $index) { $index_set = TRUE; } else { $not[] = $k.'-'.$v; } if ($escape === FALSE) { $clean[$this->_protect_identifiers($k2)] = $v2; } else { $clean[$this->_protect_identifiers($k2)] = $this->escape($v2); } } if ($index_set == FALSE) { return $this->display_error('db_batch_missing_index'); } $this->ar_set[] = $clean; } return $this; } // -------------------------------------------------------------------- /** * Empty Table * * Compiles a delete string and runs "DELETE FROM table" * * @param string the table to empty * @return object */ public function empty_table($table = '') { if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } else { $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE); } $sql = $this->_delete($table); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Truncate * * Compiles a truncate string and runs the query * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @param string the table to truncate * @return object */ public function truncate($table = '') { if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } else { $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE); } $sql = $this->_truncate($table); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Delete * * Compiles a delete string and runs the query * * @param mixed the table(s) to delete from. String or array * @param mixed the where clause * @param mixed the limit clause * @param boolean * @return object */ public function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE) { // Combine any cached components with the current statements $this->_merge_cache(); if ($table == '') { if ( ! isset($this->ar_from[0])) { if ($this->db_debug) { return $this->display_error('db_must_set_table'); } return FALSE; } $table = $this->ar_from[0]; } elseif (is_array($table)) { foreach ($table as $single_table) { $this->delete($single_table, $where, $limit, FALSE); } $this->_reset_write(); return; } else { $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE); } if ($where != '') { $this->where($where); } if ($limit != NULL) { $this->limit($limit); } if (count($this->ar_where) == 0 && count($this->ar_wherein) == 0 && count($this->ar_like) == 0) { if ($this->db_debug) { return $this->display_error('db_del_must_use_where'); } return FALSE; } $sql = $this->_delete($table, $this->ar_where, $this->ar_like, $this->ar_limit);
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
true
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/DB_cache.php
system/database/DB_cache.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Database Cache Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_Cache { var $CI; var $db; // allows passing of db object so that multiple database connections and returned db objects can be supported /** * Constructor * * Grabs the CI super object instance so we can access it. * */ function __construct(&$db) { // Assign the main CI object to $this->CI // and load the file helper since we use it a lot $this->CI =& get_instance(); $this->db =& $db; $this->CI->load->helper('file'); } // -------------------------------------------------------------------- /** * Set Cache Directory Path * * @access public * @param string the path to the cache directory * @return bool */ 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 = preg_replace("/(.+?)\/*$/", "\\1/", $path); if ( ! is_dir($path) OR ! is_really_writable($path)) { // If the path is wrong we'll turn off caching return $this->db->cache_off(); } $this->db->cachedir = $path; return TRUE; } // -------------------------------------------------------------------- /** * 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 * * @access public * @return string */ function read($sql) { if ( ! $this->check_path()) { return $this->db->cache_off(); } $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 = read_file($filepath))) { return FALSE; } return unserialize($cachedata); } // -------------------------------------------------------------------- /** * Write a query to a cache file * * @access public * @return bool */ function write($sql, $object) { if ( ! $this->check_path()) { return $this->db->cache_off(); } $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)) { if ( ! @mkdir($dir_path, DIR_WRITE_MODE)) { return FALSE; } @chmod($dir_path, DIR_WRITE_MODE); } if (write_file($dir_path.$filename, serialize($object)) === FALSE) { return FALSE; } @chmod($dir_path.$filename, FILE_WRITE_MODE); return TRUE; } // -------------------------------------------------------------------- /** * Delete cache files within a particular directory * * @access public * @return bool */ 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 all existing cache files * * @access public * @return bool */ function delete_all() { delete_files($this->db->cachedir, TRUE); } } /* End of file DB_cache.php */ /* Location: ./system/database/DB_cache.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/DB_driver.php
system/database/DB_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Database Driver Class * * This is the platform-independent base DB implementation class. * This class will not be called directly. Rather, the adapter * class for the specific database will extend and instantiate it. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_driver { var $username; var $password; var $hostname; var $database; var $dbdriver = 'mysql'; var $dbprefix = ''; var $char_set = 'utf8'; var $dbcollat = 'utf8_general_ci'; var $autoinit = TRUE; // Whether to automatically initialize the DB var $swap_pre = ''; var $port = ''; var $pconnect = FALSE; var $conn_id = FALSE; var $result_id = FALSE; var $db_debug = FALSE; var $benchmark = 0; var $query_count = 0; var $bind_marker = '?'; var $save_queries = TRUE; var $queries = array(); var $query_times = array(); var $data_cache = array(); var $trans_enabled = TRUE; var $trans_strict = TRUE; var $_trans_depth = 0; var $_trans_status = TRUE; // Used with transactions to determine if a rollback should occur var $cache_on = FALSE; var $cachedir = ''; var $cache_autodel = FALSE; var $CACHE; // The cache class object // Private variables var $_protect_identifiers = TRUE; var $_reserved_identifiers = array('*'); // Identifiers that should NOT be escaped // These are use with Oracle var $stmt_id; var $curs_id; var $limit_used; /** * Constructor. Accepts one parameter containing the database * connection settings. * * @param array */ function __construct($params) { if (is_array($params)) { foreach ($params as $key => $val) { $this->$key = $val; } } log_message('debug', 'Database Driver Class Initialized'); } // -------------------------------------------------------------------- /** * Initialize Database Settings * * @access private Called by the constructor * @param mixed * @return void */ function initialize() { // If an existing connection resource is available // there is no need to connect and select the database if (is_resource($this->conn_id) OR is_object($this->conn_id)) { return TRUE; } // ---------------------------------------------------------------- // Connect to the database and set the connection ID $this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect(); // No connection resource? Throw an error if ( ! $this->conn_id) { log_message('error', 'Unable to connect to the database'); if ($this->db_debug) { $this->display_error('db_unable_to_connect'); } return FALSE; } // ---------------------------------------------------------------- // Select the DB... assuming a database name is specified in the config file if ($this->database != '') { if ( ! $this->db_select()) { log_message('error', 'Unable to select database: '.$this->database); if ($this->db_debug) { $this->display_error('db_unable_to_select', $this->database); } return FALSE; } else { // We've selected the DB. Now we set the character set if ( ! $this->db_set_charset($this->char_set, $this->dbcollat)) { return FALSE; } return TRUE; } } return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { if ( ! $this->_db_set_charset($this->char_set, $this->dbcollat)) { log_message('error', 'Unable to set database connection charset: '.$this->char_set); if ($this->db_debug) { $this->display_error('db_unable_to_set_charset', $this->char_set); } return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * The name of the platform in use (mysql, mssql, etc...) * * @access public * @return string */ function platform() { return $this->dbdriver; } // -------------------------------------------------------------------- /** * Database Version Number. Returns a string containing the * version of the database being used * * @access public * @return string */ function version() { if (FALSE === ($sql = $this->_version())) { if ($this->db_debug) { return $this->display_error('db_unsupported_function'); } return FALSE; } // Some DBs have functions that return the version, and don't run special // SQL queries per se. In these instances, just return the result. $driver_version_exceptions = array('oci8', 'sqlite', 'cubrid'); if (in_array($this->dbdriver, $driver_version_exceptions)) { return $sql; } else { $query = $this->query($sql); return $query->row('ver'); } } // -------------------------------------------------------------------- /** * Execute the query * * Accepts an SQL string as input and returns a result object upon * successful execution of a "read" type query. Returns boolean TRUE * upon successful execution of a "write" type query. Returns boolean * FALSE upon failure, and if the $db_debug variable is set to TRUE * will raise an error. * * @access public * @param string An SQL query string * @param array An array of binding data * @return mixed */ function query($sql, $binds = FALSE, $return_object = TRUE) { if ($sql == '') { if ($this->db_debug) { log_message('error', 'Invalid query: '.$sql); return $this->display_error('db_invalid_query'); } return FALSE; } // Verify table prefix and replace if necessary if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) ) { $sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql); } // Compile binds if needed if ($binds !== FALSE) { $sql = $this->compile_binds($sql, $binds); } // Is query caching enabled? If the query is a "read type" // we will load the caching class and return the previously // cached query if it exists if ($this->cache_on == TRUE AND stristr($sql, 'SELECT')) { if ($this->_cache_init()) { $this->load_rdriver(); if (FALSE !== ($cache = $this->CACHE->read($sql))) { return $cache; } } } // Save the query for debugging if ($this->save_queries == TRUE) { $this->queries[] = $sql; } // Start the Query Timer $time_start = list($sm, $ss) = explode(' ', microtime()); // Run the Query if (FALSE === ($this->result_id = $this->simple_query($sql))) { if ($this->save_queries == TRUE) { $this->query_times[] = 0; } // This will trigger a rollback if transactions are being used $this->_trans_status = FALSE; if ($this->db_debug) { // grab the error number and message now, as we might run some // additional queries before displaying the error $error_no = $this->_error_number(); $error_msg = $this->_error_message(); // We call this function in order to roll-back queries // if transactions are enabled. If we don't call this here // the error message will trigger an exit, causing the // transactions to remain in limbo. $this->trans_complete(); // Log and display errors log_message('error', 'Query error: '.$error_msg); return $this->display_error( array( 'Error Number: '.$error_no, $error_msg, $sql ) ); } return FALSE; } // Stop and aggregate the query time results $time_end = list($em, $es) = explode(' ', microtime()); $this->benchmark += ($em + $es) - ($sm + $ss); if ($this->save_queries == TRUE) { $this->query_times[] = ($em + $es) - ($sm + $ss); } // Increment the query counter $this->query_count++; // Was the query a "write" type? // If so we'll simply return true if ($this->is_write_type($sql) === TRUE) { // If caching is enabled we'll auto-cleanup any // existing files related to this particular URI if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init()) { $this->CACHE->delete(); } return TRUE; } // Return TRUE if we don't need to create a result object // Currently only the Oracle driver uses this when stored // procedures are used if ($return_object !== TRUE) { return TRUE; } // Load and instantiate the result driver $driver = $this->load_rdriver(); $RES = new $driver(); $RES->conn_id = $this->conn_id; $RES->result_id = $this->result_id; if ($this->dbdriver == 'oci8') { $RES->stmt_id = $this->stmt_id; $RES->curs_id = NULL; $RES->limit_used = $this->limit_used; $this->stmt_id = FALSE; } // oci8 vars must be set before calling this $RES->num_rows = $RES->num_rows(); // Is query caching enabled? If so, we'll serialize the // result object and save it to a cache file. if ($this->cache_on == TRUE AND $this->_cache_init()) { // We'll create a new instance of the result object // only without the platform specific driver since // we can't use it with cached data (the query result // resource ID won't be any good once we've cached the // result object, so we'll have to compile the data // and save it) $CR = new CI_DB_result(); $CR->num_rows = $RES->num_rows(); $CR->result_object = $RES->result_object(); $CR->result_array = $RES->result_array(); // Reset these since cached objects can not utilize resource IDs. $CR->conn_id = NULL; $CR->result_id = NULL; $this->CACHE->write($sql, $CR); } return $RES; } // -------------------------------------------------------------------- /** * Load the result drivers * * @access public * @return string the name of the result class */ function load_rdriver() { $driver = 'CI_DB_'.$this->dbdriver.'_result'; if ( ! class_exists($driver)) { include_once(BASEPATH.'database/DB_result.php'); include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php'); } return $driver; } // -------------------------------------------------------------------- /** * Simple Query * This is a simplified version of the query() function. Internally * we only use it when running transaction commands since they do * not require all the features of the main query() function. * * @access public * @param string the sql query * @return mixed */ function simple_query($sql) { if ( ! $this->conn_id) { $this->initialize(); } return $this->_execute($sql); } // -------------------------------------------------------------------- /** * Disable Transactions * This permits transactions to be disabled at run-time. * * @access public * @return void */ function trans_off() { $this->trans_enabled = FALSE; } // -------------------------------------------------------------------- /** * Enable/disable Transaction Strict Mode * When strict mode is enabled, if you are running multiple groups of * transactions, if one group fails all groups will be rolled back. * If strict mode is disabled, each group is treated autonomously, meaning * a failure of one group will not affect any others * * @access public * @return void */ function trans_strict($mode = TRUE) { $this->trans_strict = is_bool($mode) ? $mode : TRUE; } // -------------------------------------------------------------------- /** * Start Transaction * * @access public * @return void */ function trans_start($test_mode = FALSE) { if ( ! $this->trans_enabled) { return FALSE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { $this->_trans_depth += 1; return; } $this->trans_begin($test_mode); } // -------------------------------------------------------------------- /** * Complete Transaction * * @access public * @return bool */ function trans_complete() { if ( ! $this->trans_enabled) { return FALSE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 1) { $this->_trans_depth -= 1; return TRUE; } // The query() function will set this flag to FALSE in the event that a query failed if ($this->_trans_status === FALSE) { $this->trans_rollback(); // If we are NOT running in strict mode, we will reset // the _trans_status flag so that subsequent groups of transactions // will be permitted. if ($this->trans_strict === FALSE) { $this->_trans_status = TRUE; } log_message('debug', 'DB Transaction Failure'); return FALSE; } $this->trans_commit(); return TRUE; } // -------------------------------------------------------------------- /** * Lets you retrieve the transaction flag to determine if it has failed * * @access public * @return bool */ function trans_status() { return $this->_trans_status; } // -------------------------------------------------------------------- /** * Compile Bindings * * @access public * @param string the sql statement * @param array an array of bind data * @return string */ function compile_binds($sql, $binds) { if (strpos($sql, $this->bind_marker) === FALSE) { return $sql; } if ( ! is_array($binds)) { $binds = array($binds); } // Get the sql segments around the bind markers $segments = explode($this->bind_marker, $sql); // The count of bind should be 1 less then the count of segments // If there are more bind arguments trim it down if (count($binds) >= count($segments)) { $binds = array_slice($binds, 0, count($segments)-1); } // Construct the binded query $result = $segments[0]; $i = 0; foreach ($binds as $bind) { $result .= $this->escape($bind); $result .= $segments[++$i]; } return $result; } // -------------------------------------------------------------------- /** * Determines if a query is a "write" type. * * @access public * @param string An SQL query string * @return boolean */ function is_write_type($sql) { if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql)) { return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Calculate the aggregate query elapsed time * * @access public * @param integer The number of decimal places * @return integer */ function elapsed_time($decimals = 6) { return number_format($this->benchmark, $decimals); } // -------------------------------------------------------------------- /** * Returns the total number of queries * * @access public * @return integer */ function total_queries() { return $this->query_count; } // -------------------------------------------------------------------- /** * Returns the last query that was executed * * @access public * @return void */ function last_query() { return end($this->queries); } // -------------------------------------------------------------------- /** * "Smart" Escape String * * Escapes data based on type * Sets boolean and null types * * @access public * @param string * @return mixed */ function escape($str) { if (is_string($str)) { $str = "'".$this->escape_str($str)."'"; } elseif (is_bool($str)) { $str = ($str === FALSE) ? 0 : 1; } elseif (is_null($str)) { $str = 'NULL'; } return $str; } // -------------------------------------------------------------------- /** * Escape LIKE String * * Calls the individual driver for platform * specific escaping for LIKE conditions * * @access public * @param string * @return mixed */ function escape_like_str($str) { return $this->escape_str($str, TRUE); } // -------------------------------------------------------------------- /** * Primary * * Retrieves the primary key. It assumes that the row in the first * position is the primary key * * @access public * @param string the table name * @return string */ function primary($table = '') { $fields = $this->list_fields($table); if ( ! is_array($fields)) { return FALSE; } return current($fields); } // -------------------------------------------------------------------- /** * Returns an array of table names * * @access public * @return array */ function list_tables($constrain_by_prefix = FALSE) { // Is there a cached result? if (isset($this->data_cache['table_names'])) { return $this->data_cache['table_names']; } if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix))) { if ($this->db_debug) { return $this->display_error('db_unsupported_function'); } return FALSE; } $retval = array(); $query = $this->query($sql); if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) { if (isset($row['TABLE_NAME'])) { $retval[] = $row['TABLE_NAME']; } else { $retval[] = array_shift($row); } } } $this->data_cache['table_names'] = $retval; return $this->data_cache['table_names']; } // -------------------------------------------------------------------- /** * Determine if a particular table exists * @access public * @return boolean */ function table_exists($table_name) { return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE; } // -------------------------------------------------------------------- /** * Fetch MySQL Field Names * * @access public * @param string the table name * @return array */ function list_fields($table = '') { // Is there a cached result? if (isset($this->data_cache['field_names'][$table])) { return $this->data_cache['field_names'][$table]; } if ($table == '') { if ($this->db_debug) { return $this->display_error('db_field_param_missing'); } return FALSE; } if (FALSE === ($sql = $this->_list_columns($table))) { if ($this->db_debug) { return $this->display_error('db_unsupported_function'); } return FALSE; } $query = $this->query($sql); $retval = array(); foreach ($query->result_array() as $row) { if (isset($row['COLUMN_NAME'])) { $retval[] = $row['COLUMN_NAME']; } else { $retval[] = current($row); } } $this->data_cache['field_names'][$table] = $retval; return $this->data_cache['field_names'][$table]; } // -------------------------------------------------------------------- /** * Determine if a particular field exists * @access public * @param string * @param string * @return boolean */ function field_exists($field_name, $table_name) { return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE; } // -------------------------------------------------------------------- /** * Returns an object with field data * * @access public * @param string the table name * @return object */ function field_data($table = '') { if ($table == '') { if ($this->db_debug) { return $this->display_error('db_field_param_missing'); } return FALSE; } $query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE))); return $query->field_data(); } // -------------------------------------------------------------------- /** * Generate an insert string * * @access public * @param string the table upon which the query will be performed * @param array an associative array data of key/values * @return string */ function insert_string($table, $data) { $fields = array(); $values = array(); foreach ($data as $key => $val) { $fields[] = $this->_escape_identifiers($key); $values[] = $this->escape($val); } return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values); } // -------------------------------------------------------------------- /** * Generate an update string * * @access public * @param string the table upon which the query will be performed * @param array an associative array data of key/values * @param mixed the "where" statement * @return string */ function update_string($table, $data, $where) { if ($where == '') { return false; } $fields = array(); foreach ($data as $key => $val) { $fields[$this->_protect_identifiers($key)] = $this->escape($val); } if ( ! is_array($where)) { $dest = array($where); } else { $dest = array(); foreach ($where as $key => $val) { $prefix = (count($dest) == 0) ? '' : ' AND '; if ($val !== '') { if ( ! $this->_has_operator($key)) { $key .= ' ='; } $val = ' '.$this->escape($val); } $dest[] = $prefix.$key.$val; } } return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest); } // -------------------------------------------------------------------- /** * Tests whether the string has an SQL operator * * @access private * @param string * @return bool */ function _has_operator($str) { $str = trim($str); if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str)) { return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Enables a native PHP function to be run, using a platform agnostic wrapper. * * @access public * @param string the function name * @param mixed any parameters needed by the function * @return mixed */ function call_function($function) { $driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_'; if (FALSE === strpos($driver, $function)) { $function = $driver.$function; } if ( ! function_exists($function)) { if ($this->db_debug) { return $this->display_error('db_unsupported_function'); } return FALSE; } else { $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null; if (is_null($args)) { return call_user_func($function); } else { return call_user_func_array($function, $args); } } } // -------------------------------------------------------------------- /** * Set Cache Directory Path * * @access public * @param string the path to the cache directory * @return void */ function cache_set_path($path = '') { $this->cachedir = $path; } // -------------------------------------------------------------------- /** * Enable Query Caching * * @access public * @return void */ function cache_on() { $this->cache_on = TRUE; return TRUE; } // -------------------------------------------------------------------- /** * Disable Query Caching * * @access public * @return void */ function cache_off() { $this->cache_on = FALSE; return FALSE; } // -------------------------------------------------------------------- /** * Delete the cache files associated with a particular URI * * @access public * @return void */ function cache_delete($segment_one = '', $segment_two = '') { if ( ! $this->_cache_init()) { return FALSE; } return $this->CACHE->delete($segment_one, $segment_two); } // -------------------------------------------------------------------- /** * Delete All cache files * * @access public * @return void */ function cache_delete_all() { if ( ! $this->_cache_init()) { return FALSE; } return $this->CACHE->delete_all(); } // -------------------------------------------------------------------- /** * Initialize the Cache Class * * @access private * @return void */ function _cache_init() { if (is_object($this->CACHE) AND class_exists('CI_DB_Cache')) { return TRUE; } if ( ! class_exists('CI_DB_Cache')) { if ( ! @include(BASEPATH.'database/DB_cache.php')) { return $this->cache_off(); } } $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects return TRUE; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @return void */ function close() { if (is_resource($this->conn_id) OR is_object($this->conn_id)) { $this->_close($this->conn_id); } $this->conn_id = FALSE; } // -------------------------------------------------------------------- /** * Display an error message * * @access public * @param string the error message * @param string any "swap" values * @param boolean whether to localize the message * @return string sends the application/error_db.php template */ function display_error($error = '', $swap = '', $native = FALSE) { $LANG =& load_class('Lang', 'core'); $LANG->load('db'); $heading = $LANG->line('db_error_heading'); if ($native == TRUE) { $message = $error; } else { $message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error; } // Find the most likely culprit of the error by going through // the backtrace until the source file is no longer in the // database folder. $trace = debug_backtrace(); foreach ($trace as $call) { if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE) { // Found it - use a relative path for safety $message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']); $message[] = 'Line Number: '.$call['line']; break; } } $error =& load_class('Exceptions', 'core'); echo $error->show_error($heading, $message, 'error_db'); exit; } // -------------------------------------------------------------------- /** * Protect Identifiers * * This function adds backticks if appropriate based on db type * * @access private * @param mixed the item to escape * @return mixed the item with backticks */ function protect_identifiers($item, $prefix_single = FALSE) { return $this->_protect_identifiers($item, $prefix_single); } // -------------------------------------------------------------------- /** * Protect Identifiers * * This function is used extensively by the Active Record class, and by * a couple functions in this class. * It takes a column or table name (optionally with an alias) and inserts * the table prefix onto it. Some logic is necessary in order to deal with * column names that include the path. Consider a query like this: * * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table * * Or a query with aliasing: * * SELECT m.member_id, m.member_name FROM members AS m * * Since the column name can include up to four segments (host, DB, table, column) * or also have an alias prefix, we need to do a bit of work to figure this out and * insert the table prefix (if it exists) in the proper position, and escape only * the correct identifiers. * * @access private * @param string * @param bool * @param mixed * @param bool * @return string */ function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE) { if ( ! is_bool($protect_identifiers)) { $protect_identifiers = $this->_protect_identifiers; } if (is_array($item)) { $escaped_array = array(); foreach ($item as $k => $v) { $escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v); } return $escaped_array; } // Convert tabs or multiple spaces into single spaces $item = preg_replace('/[\t ]+/', ' ', $item); // If the item has an alias declaration we remove it and set it aside. // Basically we remove everything to the right of the first space if (strpos($item, ' ') !== FALSE) { $alias = strstr($item, ' '); $item = substr($item, 0, - strlen($alias)); } else { $alias = ''; } // This is basically a bug fix for queries that use MAX, MIN, etc. // If a parenthesis is found we know that we do not need to // escape the data or add a prefix. There's probably a more graceful // way to deal with this, but I'm not thinking of it -- Rick if (strpos($item, '(') !== FALSE) { return $item.$alias; } // Break the string apart if it contains periods, then insert the table prefix // in the correct location, assuming the period doesn't indicate that we're dealing // with an alias. While we're at it, we will escape the components if (strpos($item, '.') !== FALSE) { $parts = explode('.', $item); // Does the first segment of the exploded item match // one of the aliases previously identified? If so, // we have nothing more to do other than escape the item if (in_array($parts[0], $this->ar_aliased_tables)) { if ($protect_identifiers === TRUE) { foreach ($parts as $key => $val) { if ( ! in_array($val, $this->_reserved_identifiers)) { $parts[$key] = $this->_escape_identifiers($val); } } $item = implode('.', $parts); } return $item.$alias; } // Is there a table prefix defined in the config file? If not, no need to do anything if ($this->dbprefix != '') { // We now add the table prefix based on some logic. // Do we have 4 segments (hostname.database.table.column)? // If so, we add the table prefix to the column name in the 3rd segment. if (isset($parts[3])) { $i = 2; } // Do we have 3 segments (database.table.column)? // If so, we add the table prefix to the column name in 2nd position elseif (isset($parts[2])) { $i = 1; } // Do we have 2 segments (table.column)? // If so, we add the table prefix to the column name in 1st segment else { $i = 0; } // This flag is set when the supplied $item does not contain a field name. // This can happen when this function is being called from a JOIN. if ($field_exists == FALSE) { $i++; } // Verify table prefix and replace if necessary if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0) { $parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]); } // We only add the table prefix if it does not already exist if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix) { $parts[$i] = $this->dbprefix.$parts[$i]; } // Put the parts back together $item = implode('.', $parts); } if ($protect_identifiers === TRUE) { $item = $this->_escape_identifiers($item); } return $item.$alias; } // Is there a table prefix? If not, no need to insert it if ($this->dbprefix != '') { // Verify table prefix and replace if necessary if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0) { $item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item); } // Do we prefix an item with no segments? if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix) { $item = $this->dbprefix.$item; } } if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers)) { $item = $this->_escape_identifiers($item); } return $item.$alias; } // -------------------------------------------------------------------- /** * Dummy method that allows Active Record class to be disabled * * This function is used extensively by every db driver. * * @return void */ protected function _reset_select() { } } /* End of file DB_driver.php */ /* Location: ./system/database/DB_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/DB.php
system/database/DB.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Initialize the database * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ * @param string * @param bool Determines if active record should be used or not */ function &DB($params = '', $active_record_override = NULL) { // Load the DB config file if a DSN string wasn't passed if (is_string($params) AND strpos($params, '://') === FALSE) { // Is the config file in the environment folder? if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/database.php')) { if ( ! file_exists($file_path = APPPATH.'config/database.php')) { show_error('The configuration file database.php does not exist.'); } } include($file_path); if ( ! isset($db) OR count($db) == 0) { show_error('No database connection settings were found in the database config file.'); } if ($params != '') { $active_group = $params; } if ( ! isset($active_group) OR ! isset($db[$active_group])) { show_error('You have specified an invalid database connection group.'); } $params = $db[$active_group]; } elseif (is_string($params)) { /* parse the URL from the DSN string * Database settings can be passed as discreet * parameters or as a data source name in the first * parameter. DSNs must have this prototype: * $dsn = 'driver://username:password@hostname/database'; */ if (($dns = @parse_url($params)) === FALSE) { show_error('Invalid DB Connection String'); } $params = array( 'dbdriver' => $dns['scheme'], 'hostname' => (isset($dns['host'])) ? rawurldecode($dns['host']) : '', 'username' => (isset($dns['user'])) ? rawurldecode($dns['user']) : '', 'password' => (isset($dns['pass'])) ? rawurldecode($dns['pass']) : '', 'database' => (isset($dns['path'])) ? rawurldecode(substr($dns['path'], 1)) : '' ); // were additional config items set? if (isset($dns['query'])) { parse_str($dns['query'], $extra); foreach ($extra as $key => $val) { // booleans please if (strtoupper($val) == "TRUE") { $val = TRUE; } elseif (strtoupper($val) == "FALSE") { $val = FALSE; } $params[$key] = $val; } } } // No DB specified yet? Beat them senseless... if ( ! isset($params['dbdriver']) OR $params['dbdriver'] == '') { show_error('You have not selected a database type to connect to.'); } // Load the DB classes. Note: Since the active record class is optional // we need to dynamically create a class that extends proper parent class // based on whether we're using the active record class or not. // Kudos to Paul for discovering this clever use of eval() if ($active_record_override !== NULL) { $active_record = $active_record_override; } require_once(BASEPATH.'database/DB_driver.php'); if ( ! isset($active_record) OR $active_record == TRUE) { require_once(BASEPATH.'database/DB_active_rec.php'); if ( ! class_exists('CI_DB')) { eval('class CI_DB extends CI_DB_active_record { }'); } } else { if ( ! class_exists('CI_DB')) { eval('class CI_DB extends CI_DB_driver { }'); } } require_once(BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php'); // Instantiate the DB adapter $driver = 'CI_DB_'.$params['dbdriver'].'_driver'; $DB = new $driver($params); if ($DB->autoinit == TRUE) { $DB->initialize(); } if (isset($params['stricton']) && $params['stricton'] == TRUE) { $DB->query('SET SESSION sql_mode="STRICT_ALL_TABLES"'); } return $DB; } /* End of file DB.php */ /* Location: ./system/database/DB.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/DB_result.php
system/database/DB_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Database Result Class * * This is the platform-independent result class. * This class will not be called directly. Rather, the adapter * class for the specific database will extend and instantiate it. * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_result { var $conn_id = NULL; var $result_id = NULL; var $result_array = array(); var $result_object = array(); var $custom_result_object = array(); var $current_row = 0; var $num_rows = 0; var $row_data = NULL; /** * Query result. Acts as a wrapper function for the following functions. * * @access public * @param string can be "object" or "array" * @return mixed either a result object or array */ public function result($type = 'object') { if ($type == 'array') return $this->result_array(); else if ($type == 'object') return $this->result_object(); else return $this->custom_result_object($type); } // -------------------------------------------------------------------- /** * Custom query result. * * @param class_name A string that represents the type of object you want back * @return array of objects */ public function custom_result_object($class_name) { if (array_key_exists($class_name, $this->custom_result_object)) { return $this->custom_result_object[$class_name]; } if ($this->result_id === FALSE OR $this->num_rows() == 0) { return array(); } // add the data to the object $this->_data_seek(0); $result_object = array(); while ($row = $this->_fetch_object()) { $object = new $class_name(); foreach ($row as $key => $value) { $object->$key = $value; } $result_object[] = $object; } // return the array return $this->custom_result_object[$class_name] = $result_object; } // -------------------------------------------------------------------- /** * Query result. "object" version. * * @access public * @return object */ public function result_object() { if (count($this->result_object) > 0) { return $this->result_object; } // In the event that query caching is on the result_id variable // will return FALSE since there isn't a valid SQL resource so // we'll simply return an empty array. if ($this->result_id === FALSE OR $this->num_rows() == 0) { return array(); } $this->_data_seek(0); while ($row = $this->_fetch_object()) { $this->result_object[] = $row; } return $this->result_object; } // -------------------------------------------------------------------- /** * Query result. "array" version. * * @access public * @return array */ public function result_array() { if (count($this->result_array) > 0) { return $this->result_array; } // In the event that query caching is on the result_id variable // will return FALSE since there isn't a valid SQL resource so // we'll simply return an empty array. if ($this->result_id === FALSE OR $this->num_rows() == 0) { return array(); } $this->_data_seek(0); while ($row = $this->_fetch_assoc()) { $this->result_array[] = $row; } return $this->result_array; } // -------------------------------------------------------------------- /** * Query result. Acts as a wrapper function for the following functions. * * @access public * @param string * @param string can be "object" or "array" * @return mixed either a result object or array */ public function row($n = 0, $type = 'object') { if ( ! is_numeric($n)) { // We cache the row data for subsequent uses if ( ! is_array($this->row_data)) { $this->row_data = $this->row_array(0); } // array_key_exists() instead of isset() to allow for MySQL NULL values if (array_key_exists($n, $this->row_data)) { return $this->row_data[$n]; } // reset the $n variable if the result was not achieved $n = 0; } if ($type == 'object') return $this->row_object($n); else if ($type == 'array') return $this->row_array($n); else return $this->custom_row_object($n, $type); } // -------------------------------------------------------------------- /** * Assigns an item into a particular column slot * * @access public * @return object */ public function set_row($key, $value = NULL) { // We cache the row data for subsequent uses if ( ! is_array($this->row_data)) { $this->row_data = $this->row_array(0); } if (is_array($key)) { foreach ($key as $k => $v) { $this->row_data[$k] = $v; } return; } if ($key != '' AND ! is_null($value)) { $this->row_data[$key] = $value; } } // -------------------------------------------------------------------- /** * Returns a single result row - custom object version * * @access public * @return object */ public function custom_row_object($n, $type) { $result = $this->custom_result_object($type); if (count($result) == 0) { return $result; } if ($n != $this->current_row AND isset($result[$n])) { $this->current_row = $n; } return $result[$this->current_row]; } /** * Returns a single result row - object version * * @access public * @return object */ public function row_object($n = 0) { $result = $this->result_object(); if (count($result) == 0) { return $result; } if ($n != $this->current_row AND isset($result[$n])) { $this->current_row = $n; } return $result[$this->current_row]; } // -------------------------------------------------------------------- /** * Returns a single result row - array version * * @access public * @return array */ public function row_array($n = 0) { $result = $this->result_array(); if (count($result) == 0) { return $result; } if ($n != $this->current_row AND isset($result[$n])) { $this->current_row = $n; } return $result[$this->current_row]; } // -------------------------------------------------------------------- /** * Returns the "first" row * * @access public * @return object */ public function first_row($type = 'object') { $result = $this->result($type); if (count($result) == 0) { return $result; } return $result[0]; } // -------------------------------------------------------------------- /** * Returns the "last" row * * @access public * @return object */ public function last_row($type = 'object') { $result = $this->result($type); if (count($result) == 0) { return $result; } return $result[count($result) -1]; } // -------------------------------------------------------------------- /** * Returns the "next" row * * @access public * @return object */ public function next_row($type = 'object') { $result = $this->result($type); if (count($result) == 0) { return $result; } if (isset($result[$this->current_row + 1])) { ++$this->current_row; } return $result[$this->current_row]; } // -------------------------------------------------------------------- /** * Returns the "previous" row * * @access public * @return object */ public function previous_row($type = 'object') { $result = $this->result($type); if (count($result) == 0) { return $result; } if (isset($result[$this->current_row - 1])) { --$this->current_row; } return $result[$this->current_row]; } // -------------------------------------------------------------------- /** * The following functions are normally overloaded by the identically named * methods in the platform-specific driver -- except when query caching * is used. When caching is enabled we do not load the other driver. * These functions are primarily here to prevent undefined function errors * when a cached result object is in use. They are not otherwise fully * operational due to the unavailability of the database resource IDs with * cached results. */ public function num_rows() { return $this->num_rows; } public function num_fields() { return 0; } public function list_fields() { return array(); } public function field_data() { return array(); } public function free_result() { return TRUE; } protected function _data_seek() { return TRUE; } protected function _fetch_assoc() { return array(); } protected function _fetch_object() { return array(); } } // END DB_result class /* End of file DB_result.php */ /* Location: ./system/database/DB_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/DB_utility.php
system/database/DB_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Code Igniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Database Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_utility extends CI_DB_forge { var $db; var $data_cache = array(); /** * Constructor * * Grabs the CI super object instance so we can access it. * */ function __construct() { // Assign the main database object to $this->db $CI =& get_instance(); $this->db =& $CI->db; log_message('debug', "Database Utility Class Initialized"); } // -------------------------------------------------------------------- /** * List databases * * @access public * @return bool */ function list_databases() { // Is there a cached result? if (isset($this->data_cache['db_names'])) { return $this->data_cache['db_names']; } $query = $this->db->query($this->_list_databases()); $dbs = array(); if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) { $dbs[] = current($row); } } $this->data_cache['db_names'] = $dbs; return $this->data_cache['db_names']; } // -------------------------------------------------------------------- /** * Determine if a particular database exists * * @access public * @param string * @return boolean */ function database_exists($database_name) { // Some databases won't have access to the list_databases() function, so // this is intended to allow them to override with their own functions as // defined in $driver_utility.php if (method_exists($this, '_database_exists')) { return $this->_database_exists($database_name); } else { return ( ! in_array($database_name, $this->list_databases())) ? FALSE : TRUE; } } // -------------------------------------------------------------------- /** * Optimize Table * * @access public * @param string the table name * @return bool */ function optimize_table($table_name) { $sql = $this->_optimize_table($table_name); if (is_bool($sql)) { show_error('db_must_use_set'); } $query = $this->db->query($sql); $res = $query->result_array(); // Note: Due to a bug in current() that affects some versions // of PHP we can not pass function call directly into it return current($res); } // -------------------------------------------------------------------- /** * Optimize Database * * @access public * @return array */ function optimize_database() { $result = array(); foreach ($this->db->list_tables() as $table_name) { $sql = $this->_optimize_table($table_name); if (is_bool($sql)) { return $sql; } $query = $this->db->query($sql); // Build the result array... // Note: Due to a bug in current() that affects some versions // of PHP we can not pass function call directly into it $res = $query->result_array(); $res = current($res); $key = str_replace($this->db->database.'.', '', current($res)); $keys = array_keys($res); unset($res[$keys[0]]); $result[$key] = $res; } return $result; } // -------------------------------------------------------------------- /** * Repair Table * * @access public * @param string the table name * @return bool */ function repair_table($table_name) { $sql = $this->_repair_table($table_name); if (is_bool($sql)) { return $sql; } $query = $this->db->query($sql); // Note: Due to a bug in current() that affects some versions // of PHP we can not pass function call directly into it $res = $query->result_array(); return current($res); } // -------------------------------------------------------------------- /** * Generate CSV from a query result object * * @access public * @param object The query result object * @param string The delimiter - comma by default * @param string The newline character - \n by default * @param string The enclosure - double quote by default * @return string */ function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"') { if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) { show_error('You must submit a valid result object'); } $out = ''; // First generate the headings from the table column names foreach ($query->list_fields() as $name) { $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim; } $out = rtrim($out); $out .= $newline; // Next blast through the result array and build out the rows foreach ($query->result_array() as $row) { foreach ($row as $item) { $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim; } $out = rtrim($out); $out .= $newline; } return $out; } // -------------------------------------------------------------------- /** * Generate XML data from a query result object * * @access public * @param object The query result object * @param array Any preferences * @return string */ function xml_from_result($query, $params = array()) { if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) { show_error('You must submit a valid result object'); } // Set our default values foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val) { if ( ! isset($params[$key])) { $params[$key] = $val; } } // Create variables for convenience extract($params); // Load the xml helper $CI =& get_instance(); $CI->load->helper('xml'); // Generate the result $xml = "<{$root}>".$newline; foreach ($query->result_array() as $row) { $xml .= $tab."<{$element}>".$newline; foreach ($row as $key => $val) { $xml .= $tab.$tab."<{$key}>".xml_convert($val)."</{$key}>".$newline; } $xml .= $tab."</{$element}>".$newline; } $xml .= "</$root>".$newline; return $xml; } // -------------------------------------------------------------------- /** * Database Backup * * @access public * @return void */ function backup($params = array()) { // If the parameters have not been submitted as an // array then we know that it is simply the table // name, which is a valid short cut. if (is_string($params)) { $params = array('tables' => $params); } // ------------------------------------------------------ // Set up our default preferences $prefs = array( 'tables' => array(), 'ignore' => array(), 'filename' => '', 'format' => 'gzip', // gzip, zip, txt 'add_drop' => TRUE, 'add_insert' => TRUE, 'newline' => "\n" ); // Did the user submit any preferences? If so set them.... if (count($params) > 0) { foreach ($prefs as $key => $val) { if (isset($params[$key])) { $prefs[$key] = $params[$key]; } } } // ------------------------------------------------------ // Are we backing up a complete database or individual tables? // If no table names were submitted we'll fetch the entire table list if (count($prefs['tables']) == 0) { $prefs['tables'] = $this->db->list_tables(); } // ------------------------------------------------------ // Validate the format if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE)) { $prefs['format'] = 'txt'; } // ------------------------------------------------------ // Is the encoder supported? If not, we'll either issue an // error or use plain text depending on the debug settings if (($prefs['format'] == 'gzip' AND ! @function_exists('gzencode')) OR ($prefs['format'] == 'zip' AND ! @function_exists('gzcompress'))) { if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_compression'); } $prefs['format'] = 'txt'; } // ------------------------------------------------------ // Set the filename if not provided - Only needed with Zip files if ($prefs['filename'] == '' AND $prefs['format'] == 'zip') { $prefs['filename'] = (count($prefs['tables']) == 1) ? $prefs['tables'] : $this->db->database; $prefs['filename'] .= '_'.date('Y-m-d_H-i', time()); } // ------------------------------------------------------ // Was a Gzip file requested? if ($prefs['format'] == 'gzip') { return gzencode($this->_backup($prefs)); } // ------------------------------------------------------ // Was a text file requested? if ($prefs['format'] == 'txt') { return $this->_backup($prefs); } // ------------------------------------------------------ // Was a Zip file requested? if ($prefs['format'] == 'zip') { // If they included the .zip file extension we'll remove it if (preg_match("|.+?\.zip$|", $prefs['filename'])) { $prefs['filename'] = str_replace('.zip', '', $prefs['filename']); } // Tack on the ".sql" file extension if needed if ( ! preg_match("|.+?\.sql$|", $prefs['filename'])) { $prefs['filename'] .= '.sql'; } // Load the Zip class and output it $CI =& get_instance(); $CI->load->library('zip'); $CI->zip->add_data($prefs['filename'], $this->_backup($prefs)); return $CI->zip->get_zip(); } } } /* End of file DB_utility.php */ /* Location: ./system/database/DB_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mssql/mssql_driver.php
system/database/drivers/mssql/mssql_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MS SQL Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_driver extends CI_DB { var $dbdriver = 'mssql'; // The character used for escaping var $_escape_char = ''; // clause and character used for LIKE escape sequences var $_like_escape_str = " ESCAPE '%s' "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' ASC'; // not currently supported /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { if ($this->port != '') { $this->hostname .= ','.$this->port; } return @mssql_connect($this->hostname, $this->username, $this->password); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { if ($this->port != '') { $this->hostname .= ','.$this->port; } return @mssql_pconnect($this->hostname, $this->username, $this->password); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { // not implemented in MSSQL } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { // Note: The brackets are required in the event that the DB name // contains reserved characters return @mssql_select_db('['.$this->database.']', $this->conn_id); } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @mssql_query($sql, $this->conn_id); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->simple_query('BEGIN TRAN'); return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('COMMIT TRAN'); return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('ROLLBACK TRAN'); return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } // Escape single quotes $str = str_replace("'", "''", remove_invisible_characters($str)); // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array($this->_like_escape_chr, '%', '_'), array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'), $str ); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @mssql_rows_affected($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * Returns the last id created in the Identity column. * * @access public * @return integer */ function insert_id() { $ver = self::_parse_major_version($this->version()); $sql = ($ver >= 8 ? "SELECT SCOPE_IDENTITY() AS last_id" : "SELECT @@IDENTITY AS last_id"); $query = $this->query($sql); $row = $query->row(); return $row->last_id; } // -------------------------------------------------------------------- /** * Parse major version * * Grabs the major version number from the * database server version string passed in. * * @access private * @param string $version * @return int16 major version number */ function _parse_major_version($version) { preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info); return $ver_info[1]; // return the major version b/c that's all we're interested in. } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT @@VERSION AS ver"; } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name"; // for future compatibility if ($prefix_limit !== FALSE AND $this->dbprefix != '') { //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); return FALSE; // not currently supported } return $sql; } // -------------------------------------------------------------------- /** * List column query * * Generates a platform-specific query string so that the column names can be fetched * * @access private * @param string the table name * @return string */ function _list_columns($table = '') { return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$table."'"; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT TOP 1 * FROM ".$table; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return mssql_get_last_message(); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { // Are error numbers supported? return ''; } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return implode(', ', $tables); } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { $i = $limit + $offset; return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql); } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @mssql_close($conn_id); } } /* End of file mssql_driver.php */ /* Location: ./system/database/drivers/mssql/mssql_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mssql/mssql_forge.php
system/database/drivers/mssql/mssql_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MS SQL Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { return "CREATE DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return "DROP DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return bool */ function _drop_table($table) { return "DROP TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; } } $sql .= "\n)"; return $sql; } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { // I think this syntax will work, but can find little documentation on renaming tables in MSSQL $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file mssql_forge.php */ /* Location: ./system/database/drivers/mssql/mssql_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mssql/mssql_utility.php
system/database/drivers/mssql/mssql_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MS SQL Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return "EXEC sp_helpdb"; // Can also be: EXEC sp_databases } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return FALSE; // Is this supported in MS SQL? } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return FALSE; // Is this supported in MS SQL? } // -------------------------------------------------------------------- /** * MSSQL Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file mssql_utility.php */ /* Location: ./system/database/drivers/mssql/mssql_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mssql/mssql_result.php
system/database/drivers/mssql/mssql_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MS SQL Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @mssql_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @mssql_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); while ($field = mssql_fetch_field($this->result_id)) { $field_names[] = $field->name; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); while ($field = mssql_fetch_field($this->result_id)) { $F = new stdClass(); $F->name = $field->name; $F->type = $field->type; $F->max_length = $field->max_length; $F->primary_key = 0; $F->default = ''; $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { mssql_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return mssql_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return mssql_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return mssql_fetch_object($this->result_id); } } /* End of file mssql_result.php */ /* Location: ./system/database/drivers/mssql/mssql_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/odbc/odbc_forge.php
system/database/drivers/odbc/odbc_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * ODBC Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/database/ */ class CI_DB_odbc_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database() { // ODBC has no "create database" command since it's // designed to connect to an existing database if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { // ODBC has no "drop database" command since it's // designed to connect to an existing database if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; } } $sql .= "\n)"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return bool */ function _drop_table($table) { // Not a supported ODBC feature if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file odbc_forge.php */ /* Location: ./system/database/drivers/odbc/odbc_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/odbc/odbc_result.php
system/database/drivers/odbc/odbc_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * ODBC Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_odbc_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @odbc_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @odbc_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); for ($i = 0; $i < $this->num_fields(); $i++) { $field_names[] = odbc_field_name($this->result_id, $i); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); for ($i = 0; $i < $this->num_fields(); $i++) { $F = new stdClass(); $F->name = odbc_field_name($this->result_id, $i); $F->type = odbc_field_type($this->result_id, $i); $F->max_length = odbc_field_len($this->result_id, $i); $F->primary_key = 0; $F->default = ''; $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { odbc_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return FALSE; } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { if (function_exists('odbc_fetch_object')) { return odbc_fetch_array($this->result_id); } else { return $this->_odbc_fetch_array($this->result_id); } } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { if (function_exists('odbc_fetch_object')) { return odbc_fetch_object($this->result_id); } else { return $this->_odbc_fetch_object($this->result_id); } } /** * Result - object * * subsititutes the odbc_fetch_object function when * not available (odbc_fetch_object requires unixODBC) * * @access private * @return object */ function _odbc_fetch_object(& $odbc_result) { $rs = array(); $rs_obj = FALSE; if (odbc_fetch_into($odbc_result, $rs)) { foreach ($rs as $k=>$v) { $field_name= odbc_field_name($odbc_result, $k+1); $rs_obj->$field_name = $v; } } return $rs_obj; } /** * Result - array * * subsititutes the odbc_fetch_array function when * not available (odbc_fetch_array requires unixODBC) * * @access private * @return array */ function _odbc_fetch_array(& $odbc_result) { $rs = array(); $rs_assoc = FALSE; if (odbc_fetch_into($odbc_result, $rs)) { $rs_assoc=array(); foreach ($rs as $k=>$v) { $field_name= odbc_field_name($odbc_result, $k+1); $rs_assoc[$field_name] = $v; } } return $rs_assoc; } } /* End of file odbc_result.php */ /* Location: ./system/database/drivers/odbc/odbc_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/odbc/odbc_utility.php
system/database/drivers/odbc/odbc_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * ODBC Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/database/ */ class CI_DB_odbc_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { // Not sure if ODBC lets you list all databases... if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { // Not a supported ODBC feature if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { // Not a supported ODBC feature if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * ODBC Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file odbc_utility.php */ /* Location: ./system/database/drivers/odbc/odbc_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/odbc/odbc_driver.php
system/database/drivers/odbc/odbc_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * ODBC Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_odbc_driver extends CI_DB { var $dbdriver = 'odbc'; // the character used to excape - not necessary for ODBC var $_escape_char = ''; // clause and character used for LIKE escape sequences var $_like_escape_str = " {escape '%s'} "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword; function __construct($params) { parent::__construct($params); $this->_random_keyword = ' RND('.time().')'; // database specific random keyword } /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { return @odbc_connect($this->hostname, $this->username, $this->password); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { return @odbc_pconnect($this->hostname, $this->username, $this->password); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { // not implemented in odbc } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { // Not needed for ODBC return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT version() AS ver"; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @odbc_exec($this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; return odbc_autocommit($this->conn_id, FALSE); } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $ret = odbc_commit($this->conn_id); odbc_autocommit($this->conn_id, TRUE); return $ret; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $ret = odbc_rollback($this->conn_id); odbc_autocommit($this->conn_id, TRUE); return $ret; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } // ODBC doesn't require escaping $str = remove_invisible_characters($str); // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array('%', '_', $this->_like_escape_chr), array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @odbc_num_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @odbc_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SHOW TABLES FROM `".$this->database."`"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); return FALSE; // not currently supported } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SHOW COLUMNS FROM ".$table; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT TOP 1 FROM ".$table; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return odbc_errormsg($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return odbc_error($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return $this->_delete($table); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { // Does ODBC doesn't use the LIMIT clause? return $sql; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @odbc_close($conn_id); } } /* End of file odbc_driver.php */ /* Location: ./system/database/drivers/odbc/odbc_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlite/sqlite_driver.php
system/database/drivers/sqlite/sqlite_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLite Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_driver extends CI_DB { var $dbdriver = 'sqlite'; // The character used to escape with - not needed for SQLite var $_escape_char = ''; // clause and character used for LIKE escape sequences var $_like_escape_str = " ESCAPE '%s' "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' Random()'; // database specific random keyword /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { if ( ! $conn_id = @sqlite_open($this->database, FILE_WRITE_MODE, $error)) { log_message('error', $error); if ($this->db_debug) { $this->display_error($error, '', TRUE); } return FALSE; } return $conn_id; } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { if ( ! $conn_id = @sqlite_popen($this->database, FILE_WRITE_MODE, $error)) { log_message('error', $error); if ($this->db_debug) { $this->display_error($error, '', TRUE); } return FALSE; } return $conn_id; } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { // not implemented in SQLite } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return sqlite_libversion(); } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @sqlite_query($this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->simple_query('BEGIN TRANSACTION'); return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('COMMIT'); return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('ROLLBACK'); return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } $str = sqlite_escape_string($str); // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array('%', '_', $this->_like_escape_chr), array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return sqlite_changes($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @sqlite_last_insert_rowid($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SELECT name from sqlite_master WHERE type='table'"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " AND 'name' LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { // Not supported return FALSE; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT * FROM ".$table." LIMIT 1"; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return sqlite_error_string(sqlite_last_error($this->conn_id)); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return sqlite_last_error($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return $this->_delete($table); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { if ($offset == 0) { $offset = ''; } else { $offset .= ", "; } return $sql."LIMIT ".$offset.$limit; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @sqlite_close($conn_id); } } /* End of file sqlite_driver.php */ /* Location: ./system/database/drivers/sqlite/sqlite_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlite/sqlite_result.php
system/database/drivers/sqlite/sqlite_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLite Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @sqlite_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @sqlite_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); for ($i = 0; $i < $this->num_fields(); $i++) { $field_names[] = sqlite_field_name($this->result_id, $i); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); for ($i = 0; $i < $this->num_fields(); $i++) { $F = new stdClass(); $F->name = sqlite_field_name($this->result_id, $i); $F->type = 'varchar'; $F->max_length = 0; $F->primary_key = 0; $F->default = ''; $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { // Not implemented in SQLite } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return sqlite_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return sqlite_fetch_array($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { if (function_exists('sqlite_fetch_object')) { return sqlite_fetch_object($this->result_id); } else { $arr = sqlite_fetch_array($this->result_id, SQLITE_ASSOC); if (is_array($arr)) { $obj = (object) $arr; return $obj; } else { return NULL; } } } } /* End of file sqlite_result.php */ /* Location: ./system/database/drivers/sqlite/sqlite_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlite/sqlite_forge.php
system/database/drivers/sqlite/sqlite_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLite Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_forge extends CI_DB_forge { /** * Create database * * @access public * @param string the database name * @return bool */ function _create_database() { // In SQLite, a database is created when you connect to the database. // We'll return TRUE so that an error isn't generated return TRUE; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { if ( ! @file_exists($this->db->database) OR ! @unlink($this->db->database)) { if ($this->db->db_debug) { return $this->db->display_error('db_unable_to_drop'); } return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; // IF NOT EXISTS added to SQLite in 3.3.0 if ($if_not_exists === TRUE && version_compare($this->db->_version(), '3.3.0', '>=') === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)."("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } $sql .= ",\n\tUNIQUE (" . implode(', ', $key) . ")"; } } $sql .= "\n)"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * Unsupported feature in SQLite * * @access private * @return bool */ function _drop_table($table) { if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return array(); } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { // SQLite does not support dropping columns // http://www.sqlite.org/omitted.html // http://www.sqlite.org/faq.html#q11 return FALSE; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file sqlite_forge.php */ /* Location: ./system/database/drivers/sqlite/sqlite_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlite/sqlite_utility.php
system/database/drivers/sqlite/sqlite_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLite Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_utility extends CI_DB_utility { /** * List databases * * I don't believe you can do a database listing with SQLite * since each database is its own file. I suppose we could * try reading a directory looking for SQLite files, but * that doesn't seem like a terribly good idea * * @access private * @return bool */ function _list_databases() { if ($this->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return array(); } // -------------------------------------------------------------------- /** * Optimize table query * * Is optimization even supported in SQLite? * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return FALSE; } // -------------------------------------------------------------------- /** * Repair table query * * Are table repairs even supported in SQLite? * * @access private * @param string the table name * @return object */ function _repair_table($table) { return FALSE; } // -------------------------------------------------------------------- /** * SQLite Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file sqlite_utility.php */ /* Location: ./system/database/drivers/sqlite/sqlite_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysql/mysql_result.php
system/database/drivers/mysql/mysql_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // -------------------------------------------------------------------- /** * MySQL Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @mysql_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @mysql_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); while ($field = mysql_fetch_field($this->result_id)) { $field_names[] = $field->name; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); while ($field = mysql_fetch_object($this->result_id)) { preg_match('/([a-zA-Z]+)(\(\d+\))?/', $field->Type, $matches); $type = (array_key_exists(1, $matches)) ? $matches[1] : NULL; $length = (array_key_exists(2, $matches)) ? preg_replace('/[^\d]/', '', $matches[2]) : NULL; $F = new stdClass(); $F->name = $field->Field; $F->type = $type; $F->default = $field->Default; $F->max_length = $length; $F->primary_key = ( $field->Key == 'PRI' ? 1 : 0 ); $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { mysql_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return mysql_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return mysql_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return mysql_fetch_object($this->result_id); } } /* End of file mysql_result.php */ /* Location: ./system/database/drivers/mysql/mysql_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysql/mysql_forge.php
system/database/drivers/mysql/mysql_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQL Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { return "CREATE DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return "DROP DATABASE ".$name; } // -------------------------------------------------------------------- /** * Process Fields * * @access private * @param mixed the fields * @return string */ function _process_fields($fields) { $current_field_count = 0; $sql = ''; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); if (array_key_exists('NAME', $attributes)) { $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; } if (array_key_exists('TYPE', $attributes)) { $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { switch ($attributes['TYPE']) { case 'decimal': case 'float': case 'numeric': $sql .= '('.implode(',', $attributes['CONSTRAINT']).')'; break; case 'enum': case 'set': $sql .= '("'.implode('","', $attributes['CONSTRAINT']).'")'; break; default: $sql .= '('.$attributes['CONSTRAINT'].')'; } } } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } return $sql; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param mixed the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $sql .= $this->_process_fields($fields); if (count($primary_keys) > 0) { $key_name = $this->db->_protect_identifiers(implode('_', $primary_keys)); $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY ".$key_name." (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key_name = $this->db->_protect_identifiers(implode('_', $key)); $key = $this->db->_protect_identifiers($key); } else { $key_name = $this->db->_protect_identifiers($key); $key = array($key_name); } $sql .= ",\n\tKEY {$key_name} (" . implode(', ', $key) . ")"; } } $sql .= "\n) DEFAULT CHARACTER SET {$this->db->char_set} COLLATE {$this->db->dbcollat};"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return string */ function _drop_table($table) { return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param array fields * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $fields, $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql.$this->db->_protect_identifiers($fields); } $sql .= $this->_process_fields($fields); if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file mysql_forge.php */ /* Location: ./system/database/drivers/mysql/mysql_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysql/mysql_driver.php
system/database/drivers/mysql/mysql_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQL Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_driver extends CI_DB { var $dbdriver = 'mysql'; // The character used for escaping var $_escape_char = '`'; // clause and character used for LIKE escape sequences - not used in MySQL var $_like_escape_str = ''; var $_like_escape_chr = ''; /** * Whether to use the MySQL "delete hack" which allows the number * of affected rows to be shown. Uses a preg_replace when enabled, * adding a bit more processing to all queries. */ var $delete_hack = TRUE; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = 'SELECT COUNT(*) AS '; var $_random_keyword = ' RAND()'; // database specific random keyword // whether SET NAMES must be used to set the character set var $use_set_names; /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { if ($this->port != '') { $this->hostname .= ':'.$this->port; } return @mysql_connect($this->hostname, $this->username, $this->password, TRUE); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { if ($this->port != '') { $this->hostname .= ':'.$this->port; } return @mysql_pconnect($this->hostname, $this->username, $this->password); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if (mysql_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return @mysql_select_db($this->database, $this->conn_id); } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { if ( ! isset($this->use_set_names)) { // mysql_set_charset() requires PHP >= 5.2.3 and MySQL >= 5.0.7, use SET NAMES as fallback $this->use_set_names = (version_compare(PHP_VERSION, '5.2.3', '>=') && version_compare(mysql_get_server_info(), '5.0.7', '>=')) ? FALSE : TRUE; } if ($this->use_set_names === TRUE) { return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id); } else { return @mysql_set_charset($charset, $this->conn_id); } } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT version() AS ver"; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @mysql_query($sql, $this->conn_id); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { // "DELETE FROM TABLE" returns 0 affected rows This hack modifies // the query so that it returns the number of affected rows if ($this->delete_hack === TRUE) { if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql); } } return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->simple_query('SET AUTOCOMMIT=0'); $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('COMMIT'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('ROLLBACK'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id)) { $str = mysql_real_escape_string($str, $this->conn_id); } elseif (function_exists('mysql_escape_string')) { $str = mysql_escape_string($str); } else { $str = addslashes($str); } // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @mysql_affected_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @mysql_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "DESCRIBE ".$table; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return mysql_error($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return mysql_errno($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _replace($table, $keys, $values) { return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key . ' = ' . $val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @return string */ function _update_batch($table, $values, $index, $where = NULL) { $ids = array(); $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; foreach ($values as $key => $val) { $ids[] = $val[$index]; foreach (array_keys($val) as $field) { if ($field != $index) { $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; } } } $sql = "UPDATE ".$table." SET "; $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = CASE '."\n"; foreach ($v as $row) { $cases .= $row."\n"; } $cases .= 'ELSE '.$k.' END, '; } $sql .= substr($cases, 0, -2); $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { if ($offset == 0) { $offset = ''; } else { $offset .= ", "; } return $sql."LIMIT ".$offset.$limit; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @mysql_close($conn_id); } } /* End of file mysql_driver.php */ /* Location: ./system/database/drivers/mysql/mysql_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysql/mysql_utility.php
system/database/drivers/mysql/mysql_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQL Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return "SHOW DATABASES"; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return "OPTIMIZE TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return "REPAIR TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * MySQL Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { if (count($params) == 0) { return FALSE; } // Extract the prefs for simplicity extract($params); // Build the output $output = ''; 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->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 '.$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 $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) ) ? TRUE : FALSE; // Create a string of field names $field_str .= '`'.$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 if ($is_int[$i] == FALSE) { $val_str .= $this->db->escape($v); } else { $val_str .= $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 '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline; } $output .= $newline.$newline; } return $output; } } /* End of file mysql_utility.php */ /* Location: ./system/database/drivers/mysql/mysql_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysqli/mysqli_driver.php
system/database/drivers/mysqli/mysqli_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Database Adapter Class - MySQLi only works with PHP 5 * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_driver extends CI_DB { var $dbdriver = 'mysqli'; // The character used for escaping var $_escape_char = '`'; // clause and character used for LIKE escape sequences - not used in MySQL var $_like_escape_str = ''; var $_like_escape_chr = ''; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' RAND()'; // database specific random keyword /** * Whether to use the MySQL "delete hack" which allows the number * of affected rows to be shown. Uses a preg_replace when enabled, * adding a bit more processing to all queries. */ var $delete_hack = TRUE; // whether SET NAMES must be used to set the character set var $use_set_names; // -------------------------------------------------------------------- /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { if ($this->port != '') { return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database, $this->port); } else { return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database); } } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { return $this->db_connect(); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if (mysqli_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return @mysqli_select_db($this->conn_id, $this->database); } // -------------------------------------------------------------------- /** * Set client character set * * @access private * @param string * @param string * @return resource */ function _db_set_charset($charset, $collation) { if ( ! isset($this->use_set_names)) { // mysqli_set_charset() requires MySQL >= 5.0.7, use SET NAMES as fallback $this->use_set_names = (version_compare(mysqli_get_server_info($this->conn_id), '5.0.7', '>=')) ? FALSE : TRUE; } if ($this->use_set_names === TRUE) { return @mysqli_query($this->conn_id, "SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'"); } else { return @mysqli_set_charset($this->conn_id, $charset); } } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT version() AS ver"; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); $result = @mysqli_query($this->conn_id, $sql); return $result; } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { // "DELETE FROM TABLE" returns 0 affected rows This hack modifies // the query so that it returns the number of affected rows if ($this->delete_hack === TRUE) { if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql); } } return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->simple_query('SET AUTOCOMMIT=0'); $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('COMMIT'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('ROLLBACK'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } if (function_exists('mysqli_real_escape_string') AND is_object($this->conn_id)) { $str = mysqli_real_escape_string($this->conn_id, $str); } elseif (function_exists('mysql_escape_string')) { $str = mysql_escape_string($str); } else { $str = addslashes($str); } // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @mysqli_affected_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @mysqli_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "DESCRIBE ".$table; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return mysqli_error($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return mysqli_errno($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _replace($table, $keys, $values) { return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @return string */ function _update_batch($table, $values, $index, $where = NULL) { $ids = array(); $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; foreach ($values as $key => $val) { $ids[] = $val[$index]; foreach (array_keys($val) as $field) { if ($field != $index) { $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; } } } $sql = "UPDATE ".$table." SET "; $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = CASE '."\n"; foreach ($v as $row) { $cases .= $row."\n"; } $cases .= 'ELSE '.$k.' END, '; } $sql .= substr($cases, 0, -2); $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { $sql .= "LIMIT ".$limit; if ($offset > 0) { $sql .= " OFFSET ".$offset; } return $sql; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @mysqli_close($conn_id); } } /* End of file mysqli_driver.php */ /* Location: ./system/database/drivers/mysqli/mysqli_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysqli/mysqli_utility.php
system/database/drivers/mysqli/mysqli_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return "SHOW DATABASES"; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return "OPTIMIZE TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return "REPAIR TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * MySQLi Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file mysqli_utility.php */ /* Location: ./system/database/drivers/mysqli/mysqli_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysqli/mysqli_result.php
system/database/drivers/mysqli/mysqli_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @mysqli_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @mysqli_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); while ($field = mysqli_fetch_field($this->result_id)) { $field_names[] = $field->name; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); while ($field = mysqli_fetch_object($this->result_id)) { preg_match('/([a-zA-Z]+)(\(\d+\))?/', $field->Type, $matches); $type = (array_key_exists(1, $matches)) ? $matches[1] : NULL; $length = (array_key_exists(2, $matches)) ? preg_replace('/[^\d]/', '', $matches[2]) : NULL; $F = new stdClass(); $F->name = $field->Field; $F->type = $type; $F->default = $field->Default; $F->max_length = $length; $F->primary_key = ( $field->Key == 'PRI' ? 1 : 0 ); $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_object($this->result_id)) { mysqli_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return mysqli_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return mysqli_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return mysqli_fetch_object($this->result_id); } } /* End of file mysqli_result.php */ /* Location: ./system/database/drivers/mysqli/mysqli_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/mysqli/mysqli_forge.php
system/database/drivers/mysqli/mysqli_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { return "CREATE DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return "DROP DATABASE ".$name; } // -------------------------------------------------------------------- /** * Process Fields * * @access private * @param mixed the fields * @return string */ function _process_fields($fields) { $current_field_count = 0; $sql = ''; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); if (array_key_exists('NAME', $attributes)) { $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; } if (array_key_exists('TYPE', $attributes)) { $sql .= ' '.$attributes['TYPE']; } if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } return $sql; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param mixed the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $sql .= $this->_process_fields($fields); if (count($primary_keys) > 0) { $key_name = $this->db->_protect_identifiers(implode('_', $primary_keys)); $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY ".$key_name." (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key_name = $this->db->_protect_identifiers(implode('_', $key)); $key = $this->db->_protect_identifiers($key); } else { $key_name = $this->db->_protect_identifiers($key); $key = array($key_name); } $sql .= ",\n\tKEY {$key_name} (" . implode(', ', $key) . ")"; } } $sql .= "\n) DEFAULT CHARACTER SET {$this->db->char_set} COLLATE {$this->db->dbcollat};"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return string */ function _drop_table($table) { return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param array fields * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $fields, $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql.$this->db->_protect_identifiers($fields); } $sql .= $this->_process_fields($fields); if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file mysqli_forge.php */ /* Location: ./system/database/drivers/mysqli/mysqli_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlsrv/sqlsrv_result.php
system/database/drivers/sqlsrv/sqlsrv_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLSRV Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @sqlsrv_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @sqlsrv_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); foreach(sqlsrv_field_metadata($this->result_id) as $offset => $field) { $field_names[] = $field['Name']; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); foreach(sqlsrv_field_metadata($this->result_id) as $offset => $field) { $F = new stdClass(); $F->name = $field['Name']; $F->type = $field['Type']; $F->max_length = $field['Size']; $F->primary_key = 0; $F->default = ''; $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { sqlsrv_free_stmt($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { // Not implemented } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return sqlsrv_fetch_array($this->result_id, SQLSRV_FETCH_ASSOC); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return sqlsrv_fetch_object($this->result_id); } } /* End of file mssql_result.php */ /* Location: ./system/database/drivers/mssql/mssql_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlsrv/sqlsrv_forge.php
system/database/drivers/sqlsrv/sqlsrv_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLSRV Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { return "CREATE DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return "DROP DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return bool */ function _drop_table($table) { return "DROP TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; } } $sql .= "\n)"; return $sql; } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { // I think this syntax will work, but can find little documentation on renaming tables in MSSQL $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file mssql_forge.php */ /* Location: ./system/database/drivers/mssql/mssql_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlsrv/sqlsrv_utility.php
system/database/drivers/sqlsrv/sqlsrv_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLSRV Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return "EXEC sp_helpdb"; // Can also be: EXEC sp_databases } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return FALSE; // Is this supported in MS SQL? } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return FALSE; // Is this supported in MS SQL? } // -------------------------------------------------------------------- /** * MSSQL Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file mssql_utility.php */ /* Location: ./system/database/drivers/mssql/mssql_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/sqlsrv/sqlsrv_driver.php
system/database/drivers/sqlsrv/sqlsrv_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLSRV Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_driver extends CI_DB { var $dbdriver = 'sqlsrv'; // The character used for escaping var $_escape_char = ''; // clause and character used for LIKE escape sequences var $_like_escape_str = " ESCAPE '%s' "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' ASC'; // not currently supported /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect($pooling = false) { // Check for a UTF-8 charset being passed as CI's default 'utf8'. $character_set = (0 === strcasecmp('utf8', $this->char_set)) ? 'UTF-8' : $this->char_set; $connection = array( 'UID' => empty($this->username) ? '' : $this->username, 'PWD' => empty($this->password) ? '' : $this->password, 'Database' => $this->database, 'ConnectionPooling' => $pooling ? 1 : 0, 'CharacterSet' => $character_set, 'ReturnDatesAsStrings' => 1 ); // If the username and password are both empty, assume this is a // 'Windows Authentication Mode' connection. if(empty($connection['UID']) && empty($connection['PWD'])) { unset($connection['UID'], $connection['PWD']); } return sqlsrv_connect($this->hostname, $connection); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { $this->db_connect(TRUE); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { // not implemented in MSSQL } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return $this->_execute('USE ' . $this->database); } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return sqlsrv_query($this->conn_id, $sql, null, array( 'Scrollable' => SQLSRV_CURSOR_STATIC, 'SendStreamParamsAtExec' => true )); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; return sqlsrv_begin_transaction($this->conn_id); } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } return sqlsrv_commit($this->conn_id); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } return sqlsrv_rollback($this->conn_id); } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { // Escape single quotes return str_replace("'", "''", $str); } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @sqlrv_rows_affected($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * Returns the last id created in the Identity column. * * @access public * @return integer */ function insert_id() { return $this->query('select @@IDENTITY as insert_id')->row('insert_id'); } // -------------------------------------------------------------------- /** * Parse major version * * Grabs the major version number from the * database server version string passed in. * * @access private * @param string $version * @return int16 major version number */ function _parse_major_version($version) { preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info); return $ver_info[1]; // return the major version b/c that's all we're interested in. } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { $info = sqlsrv_server_info($this->conn_id); return sprintf("select '%s' as ver", $info['SQLServerVersion']); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') return '0'; $query = $this->query("SELECT COUNT(*) AS numrows FROM " . $this->dbprefix . $table); if ($query->num_rows() == 0) return '0'; $row = $query->row(); $this->_reset_select(); return $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { return "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name"; } // -------------------------------------------------------------------- /** * List column query * * Generates a platform-specific query string so that the column names can be fetched * * @access private * @param string the table name * @return string */ function _list_columns($table = '') { return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$this->_escape_table($table)."'"; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT TOP 1 * FROM " . $this->_escape_table($table); } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { $error = array_shift(sqlsrv_errors()); return !empty($error['message']) ? $error['message'] : null; } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { $error = array_shift(sqlsrv_errors()); return isset($error['SQLSTATE']) ? $error['SQLSTATE'] : null; } // -------------------------------------------------------------------- /** * Escape Table Name * * This function adds backticks if the table name has a period * in it. Some DBs will get cranky unless periods are escaped * * @access private * @param string the table name * @return string */ function _escape_table($table) { return $table; } /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { return $item; } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return implode(', ', $tables); } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$this->_escape_table($table)." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where) { foreach($values as $key => $val) { $valstr[] = $key." = ".$val; } return "UPDATE ".$this->_escape_table($table)." SET ".implode(', ', $valstr)." WHERE ".implode(" ", $where); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where) { return "DELETE FROM ".$this->_escape_table($table)." WHERE ".implode(" ", $where); } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { $i = $limit + $offset; return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql); } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @sqlsrv_close($conn_id); } } /* End of file mssql_driver.php */ /* Location: ./system/database/drivers/mssql/mssql_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/cubrid/cubrid_forge.php
system/database/drivers/cubrid/cubrid_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author Esen Sagynov * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CUBRID Forge Class * * @category Database * @author Esen Sagynov * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { // CUBRID does not allow to create a database in SQL. The GUI tools // have to be used for this purpose. return FALSE; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { // CUBRID does not allow to drop a database in SQL. The GUI tools // have to be used for this purpose. return FALSE; } // -------------------------------------------------------------------- /** * Process Fields * * @access private * @param mixed the fields * @return string */ function _process_fields($fields) { $current_field_count = 0; $sql = ''; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t\"" . $this->db->_protect_identifiers($field) . "\""; if (array_key_exists('NAME', $attributes)) { $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; } if (array_key_exists('TYPE', $attributes)) { $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { switch ($attributes['TYPE']) { case 'decimal': case 'float': case 'numeric': $sql .= '('.implode(',', $attributes['CONSTRAINT']).')'; break; case 'enum': // As of version 8.4.0 CUBRID does not support // enum data type. break; case 'set': $sql .= '("'.implode('","', $attributes['CONSTRAINT']).'")'; break; default: $sql .= '('.$attributes['CONSTRAINT'].')'; } } } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { //$sql .= ' UNSIGNED'; // As of version 8.4.0 CUBRID does not support UNSIGNED INTEGER data type. // Will be supported in the next release as a part of MySQL Compatibility. } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } if (array_key_exists('UNIQUE', $attributes) && $attributes['UNIQUE'] === TRUE) { $sql .= ' UNIQUE'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } return $sql; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param mixed the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { //$sql .= 'IF NOT EXISTS '; // As of version 8.4.0 CUBRID does not support this SQL syntax. } $sql .= $this->db->_escape_identifiers($table)." ("; $sql .= $this->_process_fields($fields); // If there is a PK defined if (count($primary_keys) > 0) { $key_name = "pk_" . $table . "_" . $this->db->_protect_identifiers(implode('_', $primary_keys)); $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tCONSTRAINT " . $key_name . " PRIMARY KEY(" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key_name = $this->db->_protect_identifiers(implode('_', $key)); $key = $this->db->_protect_identifiers($key); } else { $key_name = $this->db->_protect_identifiers($key); $key = array($key_name); } $sql .= ",\n\tKEY \"{$key_name}\" (" . implode(', ', $key) . ")"; } } $sql .= "\n);"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return string */ function _drop_table($table) { return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param array fields * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $fields, $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql.$this->db->_protect_identifiers($fields); } $sql .= $this->_process_fields($fields); if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'RENAME TABLE '.$this->db->_protect_identifiers($table_name)." AS ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file cubrid_forge.php */ /* Location: ./system/database/drivers/cubrid/cubrid_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/cubrid/cubrid_result.php
system/database/drivers/cubrid/cubrid_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author Esen Sagynov * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0.2 * @filesource */ // -------------------------------------------------------------------- /** * CUBRID Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author Esen Sagynov * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @cubrid_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @cubrid_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { return cubrid_column_names($this->result_id); } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); $tablePrimaryKeys = array(); while ($field = cubrid_fetch_field($this->result_id)) { $F = new stdClass(); $F->name = $field->name; $F->type = $field->type; $F->default = $field->def; $F->max_length = $field->max_length; // At this moment primary_key property is not returned when // cubrid_fetch_field is called. The following code will // provide a patch for it. primary_key property will be added // in the next release. // TODO: later version of CUBRID will provide primary_key // property. // When PK is defined in CUBRID, an index is automatically // created in the db_index system table in the form of // pk_tblname_fieldname. So the following will count how many // columns are there which satisfy this format. // The query will search for exact single columns, thus // compound PK is not supported. $res = cubrid_query($this->conn_id, "SELECT COUNT(*) FROM db_index WHERE class_name = '" . $field->table . "' AND is_primary_key = 'YES' AND index_name = 'pk_" . $field->table . "_" . $field->name . "'" ); if ($res) { $row = cubrid_fetch_array($res, CUBRID_NUM); $F->primary_key = ($row[0] > 0 ? 1 : null); } else { $F->primary_key = null; } if (is_resource($res)) { cubrid_close_request($res); $this->result_id = FALSE; } $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if(is_resource($this->result_id) || 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; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return cubrid_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return cubrid_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return cubrid_fetch_object($this->result_id); } } /* End of file cubrid_result.php */ /* Location: ./system/database/drivers/cubrid/cubrid_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/cubrid/cubrid_utility.php
system/database/drivers/cubrid/cubrid_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author Esen Sagynov * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CUBRID Utility Class * * @category Database * @author Esen Sagynov * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_utility extends CI_DB_utility { /** * List databases * * @access private * @return array */ function _list_databases() { // CUBRID does not allow to see the list of all databases on the // server. It is the way its architecture is designed. Every // database is independent and isolated. // For this reason we can return only the name of the currect // connected database. if ($this->conn_id) { return "SELECT '" . $this->database . "'"; } else { return FALSE; } } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object * @link http://www.cubrid.org/manual/840/en/Optimize%20Database */ function _optimize_table($table) { // No SQL based support in CUBRID as of version 8.4.0. Database or // table optimization can be performed using CUBRID Manager // database administration tool. See the link above for more info. return FALSE; } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object * @link http://www.cubrid.org/manual/840/en/Checking%20Database%20Consistency */ function _repair_table($table) { // Not supported in CUBRID as of version 8.4.0. Database or // table consistency can be checked using CUBRID Manager // database administration tool. See the link above for more info. return FALSE; } // -------------------------------------------------------------------- /** * CUBRID Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // No SQL based support in CUBRID as of version 8.4.0. Database or // table backup can be performed using CUBRID Manager // database administration tool. return $this->db->display_error('db_unsuported_feature'); } } /* End of file cubrid_utility.php */ /* Location: ./system/database/drivers/cubrid/cubrid_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/cubrid/cubrid_driver.php
system/database/drivers/cubrid/cubrid_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author Esen Sagynov * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 2.0.2 * @filesource */ // ------------------------------------------------------------------------ /** * CUBRID Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author Esen Sagynov * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_driver extends CI_DB { // Default CUBRID Broker port. Will be used unless user // explicitly specifies another one. const DEFAULT_PORT = 33000; var $dbdriver = 'cubrid'; // The character used for escaping - no need in CUBRID var $_escape_char = ''; // clause and character used for LIKE escape sequences - not used in CUBRID var $_like_escape_str = ''; var $_like_escape_chr = ''; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = 'SELECT COUNT(*) AS '; var $_random_keyword = ' RAND()'; // database specific random keyword /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { // If no port is defined by the user, use the default value if ($this->port == '') { $this->port = self::DEFAULT_PORT; } $conn = cubrid_connect($this->hostname, $this->port, $this->database, $this->username, $this->password); if ($conn) { // Check if a user wants to run queries in dry, i.e. run the // queries but not commit them. if (isset($this->auto_commit) && ! $this->auto_commit) { cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_FALSE); } else { cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_TRUE); $this->auto_commit = TRUE; } } return $conn; } // -------------------------------------------------------------------- /** * Persistent database connection * In CUBRID persistent DB connection is supported natively in CUBRID * engine which can be configured in the CUBRID Broker configuration * file by setting the CCI_PCONNECT parameter to ON. In that case, all * connections established between the client application and the * server will become persistent. This is calling the same * @cubrid_connect function will establish persisten connection * considering that the CCI_PCONNECT is ON. * * @access private called by the base class * @return resource */ function db_pconnect() { return $this->db_connect(); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if (cubrid_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { // In CUBRID there is no need to select a database as the database // is chosen at the connection time. // So, to determine if the database is "selected", all we have to // do is ping the server and return that value. return cubrid_ping($this->conn_id); } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // In CUBRID, there is no need to set charset or collation. // This is why returning true will allow the application continue // its normal process. return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { // To obtain the CUBRID Server version, no need to run the SQL query. // CUBRID PHP API provides a function to determin this value. // This is why we also need to add 'cubrid' value to the list of // $driver_version_exceptions array in DB_driver class in // version() function. return cubrid_get_server_info($this->conn_id); } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @cubrid_query($sql, $this->conn_id); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { // No need to prepare return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; if (cubrid_get_autocommit($this->conn_id)) { cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_FALSE); } return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } cubrid_commit($this->conn_id); if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) { cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); } return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } cubrid_rollback($this->conn_id); if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) { cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); } return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } if (function_exists('cubrid_real_escape_string') AND is_resource($this->conn_id)) { $str = cubrid_real_escape_string($str, $this->conn_id); } else { $str = addslashes($str); } // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @cubrid_affected_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @cubrid_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified table * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SHOW TABLES"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT * FROM ".$table." LIMIT 1"; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return cubrid_error($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return cubrid_errno($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _replace($table, $keys, $values) { return "REPLACE INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = sprintf('"%s" = %s', $key, $val); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @return string */ function _update_batch($table, $values, $index, $where = NULL) { $ids = array(); $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; foreach ($values as $key => $val) { $ids[] = $val[$index]; foreach (array_keys($val) as $field) { if ($field != $index) { $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; } } } $sql = "UPDATE ".$table." SET "; $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = CASE '."\n"; foreach ($v as $row) { $cases .= $row."\n"; } $cases .= 'ELSE '.$k.' END, '; } $sql .= substr($cases, 0, -2); $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { if ($offset == 0) { $offset = ''; } else { $offset .= ", "; } return $sql."LIMIT ".$offset.$limit; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @cubrid_close($conn_id); } } /* End of file cubrid_driver.php */ /* Location: ./system/database/drivers/cubrid/cubrid_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/pdo/pdo_result.php
system/database/drivers/pdo/pdo_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @author EllisLab Dev Team * @link http://codeigniter.com * @since Version 2.1.2 * @filesource */ // ------------------------------------------------------------------------ /** * PDO Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_result extends CI_DB_result { public $num_rows; /** * Number of rows in the result set * * @return int */ public function num_rows() { if (is_int($this->num_rows)) { return $this->num_rows; } elseif (($this->num_rows = $this->result_id->rowCount()) > 0) { return $this->num_rows; } $this->num_rows = count($this->result_id->fetchAll()); $this->result_id->execute(); return $this->num_rows; } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return $this->result_id->columnCount(); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $data = array(); try { for($i = 0; $i < $this->num_fields(); $i++) { $data[] = $this->result_id->getColumnMeta($i); } return $data; } catch (Exception $e) { if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_object($this->result_id)) { $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return FALSE; } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return $this->result_id->fetch(PDO::FETCH_ASSOC); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return $this->result_id->fetchObject(); } } /* End of file pdo_result.php */ /* Location: ./system/database/drivers/pdo/pdo_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/pdo/pdo_driver.php
system/database/drivers/pdo/pdo_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @author EllisLab Dev Team * @link http://codeigniter.com * @since Version 2.1.2 * @filesource */ // ------------------------------------------------------------------------ /** * PDO Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_driver extends CI_DB { var $dbdriver = 'pdo'; // the character used to excape - not necessary for PDO var $_escape_char = ''; var $_like_escape_str; var $_like_escape_chr; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword; var $options = array(); function __construct($params) { parent::__construct($params); // clause and character used for LIKE escape sequences if (strpos($this->hostname, 'mysql') !== FALSE) { $this->_like_escape_str = ''; $this->_like_escape_chr = ''; //Prior to this version, the charset can't be set in the dsn if(is_php('5.3.6')) { $this->hostname .= ";charset={$this->char_set}"; } //Set the charset with the connection options $this->options['PDO::MYSQL_ATTR_INIT_COMMAND'] = "SET NAMES {$this->char_set}"; } elseif (strpos($this->hostname, 'odbc') !== FALSE) { $this->_like_escape_str = " {escape '%s'} "; $this->_like_escape_chr = '!'; } else { $this->_like_escape_str = " ESCAPE '%s' "; $this->_like_escape_chr = '!'; } empty($this->database) OR $this->hostname .= ';dbname='.$this->database; $this->trans_enabled = FALSE; $this->_random_keyword = ' RND('.time().')'; // database specific random keyword } /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { $this->options['PDO::ATTR_ERRMODE'] = PDO::ERRMODE_SILENT; return new PDO($this->hostname, $this->username, $this->password, $this->options); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { $this->options['PDO::ATTR_ERRMODE'] = PDO::ERRMODE_SILENT; $this->options['PDO::ATTR_PERSISTENT'] = TRUE; return new PDO($this->hostname, $this->username, $this->password, $this->options); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { // Not needed for PDO return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return $this->conn_id->getAttribute(PDO::ATTR_CLIENT_VERSION); } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return object */ function _execute($sql) { $sql = $this->_prep_query($sql); $result_id = $this->conn_id->prepare($sql); $result_id->execute(); if (is_object($result_id)) { if (is_numeric(stripos($sql, 'SELECT'))) { $this->affect_rows = count($result_id->fetchAll()); $result_id->execute(); } else { $this->affect_rows = $result_id->rowCount(); } } else { $this->affect_rows = 0; } return $result_id; } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = (bool) ($test_mode === TRUE); return $this->conn_id->beginTransaction(); } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $ret = $this->conn->commit(); return $ret; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $ret = $this->conn_id->rollBack(); return $ret; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } //Escape the string $str = $this->conn_id->quote($str); //If there are duplicated quotes, trim them away if (strpos($str, "'") === 0) { $str = substr($str, 1, -1); } // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array('%', '_', $this->_like_escape_chr), array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return $this->affect_rows; } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id($name=NULL) { //Convenience method for postgres insertid if (strpos($this->hostname, 'pgsql') !== FALSE) { $v = $this->_version(); $table = func_num_args() > 0 ? func_get_arg(0) : NULL; if ($table == NULL && $v >= '8.1') { $sql='SELECT LASTVAL() as ins_id'; } $query = $this->query($sql); $row = $query->row(); return $row->ins_id; } else { return $this->conn_id->lastInsertId($name); } } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SHOW TABLES FROM `".$this->database."`"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); return FALSE; // not currently supported } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SHOW COLUMNS FROM ".$table; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT TOP 1 FROM ".$table; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { $error_array = $this->conn_id->errorInfo(); return $error_array[2]; } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return $this->conn_id->errorCode(); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return (count($tables) == 1) ? $tables[0] : '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @return string */ function _update_batch($table, $values, $index, $where = NULL) { $ids = array(); $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; foreach ($values as $key => $val) { $ids[] = $val[$index]; foreach (array_keys($val) as $field) { if ($field != $index) { $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; } } } $sql = "UPDATE ".$table." SET "; $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = CASE '."\n"; foreach ($v as $row) { $cases .= $row."\n"; } $cases .= 'ELSE '.$k.' END, '; } $sql .= substr($cases, 0, -2); $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return $this->_delete($table); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { if (strpos($this->hostname, 'cubrid') !== FALSE || strpos($this->hostname, 'sqlite') !== FALSE) { if ($offset == 0) { $offset = ''; } else { $offset .= ", "; } return $sql."LIMIT ".$offset.$limit; } else { $sql .= "LIMIT ".$limit; if ($offset > 0) { $sql .= " OFFSET ".$offset; } return $sql; } } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { $this->conn_id = null; } } /* End of file pdo_driver.php */ /* Location: ./system/database/drivers/pdo/pdo_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/pdo/pdo_utility.php
system/database/drivers/pdo/pdo_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @author EllisLab Dev Team * @link http://codeigniter.com * @since Version 2.1.2 * @filesource */ // ------------------------------------------------------------------------ /** * PDO Utility Class * * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/database/ */ class CI_DB_pdo_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { // Not sure if PDO lets you list all databases... if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { // Not a supported PDO feature if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { // Not a supported PDO feature if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * PDO Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file pdo_utility.php */ /* Location: ./system/database/drivers/pdo/pdo_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/pdo/pdo_forge.php
system/database/drivers/pdo/pdo_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @author EllisLab Dev Team * @link http://codeigniter.com * @since Version 2.1.2 * @filesource */ // ------------------------------------------------------------------------ /** * PDO Forge Class * * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/database/ */ class CI_DB_pdo_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database() { // PDO has no "create database" command since it's // designed to connect to an existing database if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { // PDO has no "drop database" command since it's // designed to connect to an existing database if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; } } $sql .= "\n)"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return bool */ function _drop_table($table) { // Not a supported PDO feature if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return FALSE; } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file pdo_forge.php */ /* Location: ./system/database/drivers/pdo/pdo_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/oci8/oci8_result.php
system/database/drivers/oci8/oci8_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * oci8 Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_result extends CI_DB_result { public $stmt_id; public $curs_id; public $limit_used; /** * Number of rows in the result set. * * Oracle doesn't have a graceful way to retun the number of rows * so we have to use what amounts to a hack. * * @return integer */ public function num_rows() { if ($this->num_rows === 0 && count($this->result_array()) > 0) { $this->num_rows = count($this->result_array()); @oci_execute($this->stmt_id); if ($this->curs_id) { @oci_execute($this->curs_id); } } return $this->num_rows; } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ public function num_fields() { $count = @oci_num_fields($this->stmt_id); // if we used a limit we subtract it if ($this->limit_used) { $count = $count - 1; } return $count; } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ public function list_fields() { $field_names = array(); for ($c = 1, $fieldCount = $this->num_fields(); $c <= $fieldCount; $c++) { $field_names[] = oci_field_name($this->stmt_id, $c); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ public function field_data() { $retval = array(); for ($c = 1, $fieldCount = $this->num_fields(); $c <= $fieldCount; $c++) { $F = new stdClass(); $F->name = oci_field_name($this->stmt_id, $c); $F->type = oci_field_type($this->stmt_id, $c); $F->max_length = oci_field_size($this->stmt_id, $c); $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ public function free_result() { if (is_resource($this->result_id)) { oci_free_statement($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access protected * @return array */ protected function _fetch_assoc() { $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; return oci_fetch_assoc($id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access protected * @return object */ protected function _fetch_object() { $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; return @oci_fetch_object($id); } // -------------------------------------------------------------------- /** * Query result. "array" version. * * @access public * @return array */ public function result_array() { if (count($this->result_array) > 0) { return $this->result_array; } $row = NULL; while ($row = $this->_fetch_assoc()) { $this->result_array[] = $row; } return $this->result_array; } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access protected * @return array */ protected function _data_seek($n = 0) { return FALSE; // Not needed } } /* End of file oci8_result.php */ /* Location: ./system/database/drivers/oci8/oci8_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/oci8/oci8_forge.php
system/database/drivers/oci8/oci8_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Oracle Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_forge extends CI_DB_forge { /** * Create database * * @access public * @param string the database name * @return bool */ function _create_database($name) { return FALSE; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return FALSE; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } $sql .= ",\n\tUNIQUE COLUMNS (" . implode(', ', $key) . ")"; } } $sql .= "\n)"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return bool */ function _drop_table($table) { return FALSE; } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file oci8_forge.php */ /* Location: ./system/database/drivers/oci8/oci8_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/oci8/oci8_driver.php
system/database/drivers/oci8/oci8_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * oci8 Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ /** * oci8 Database Adapter Class * * This is a modification of the DB_driver class to * permit access to oracle databases * * @author Kelly McArdle * */ class CI_DB_oci8_driver extends CI_DB { var $dbdriver = 'oci8'; // The character used for excaping var $_escape_char = '"'; // clause and character used for LIKE escape sequences var $_like_escape_str = " escape '%s' "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(1) AS "; var $_random_keyword = ' ASC'; // not currently supported // Set "auto commit" by default var $_commit = OCI_COMMIT_ON_SUCCESS; // need to track statement id and cursor id var $stmt_id; var $curs_id; // if we use a limit, we will add a field that will // throw off num_fields later var $limit_used; /** * Non-persistent database connection * * @access private called by the base class * @return resource */ public function db_connect() { return @oci_connect($this->username, $this->password, $this->hostname, $this->char_set); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ public function db_pconnect() { return @oci_pconnect($this->username, $this->password, $this->hostname, $this->char_set); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ public function reconnect() { // not implemented in oracle return; } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ public function db_select() { // Not in Oracle - schemas are actually usernames return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ public function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access protected * @return string */ protected function _version() { return oci_server_version($this->conn_id); } // -------------------------------------------------------------------- /** * Execute the query * * @access protected called by the base class * @param string an SQL query * @return resource */ protected function _execute($sql) { // oracle must parse the query before it is run. All of the actions with // the query are based on the statement id returned by ociparse $this->stmt_id = FALSE; $this->_set_stmt_id($sql); oci_set_prefetch($this->stmt_id, 1000); return @oci_execute($this->stmt_id, $this->_commit); } /** * Generate a statement ID * * @access private * @param string an SQL query * @return none */ private function _set_stmt_id($sql) { if ( ! is_resource($this->stmt_id)) { $this->stmt_id = oci_parse($this->conn_id, $this->_prep_query($sql)); } } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ private function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * getCursor. Returns a cursor from the datbase * * @access public * @return cursor id */ public function get_cursor() { $this->curs_id = oci_new_cursor($this->conn_id); return $this->curs_id; } // -------------------------------------------------------------------- /** * Stored Procedure. Executes a stored procedure * * @access public * @param package package stored procedure is in * @param procedure stored procedure to execute * @param params array of parameters * @return array * * params array keys * * KEY OPTIONAL NOTES * name no the name of the parameter should be in :<param_name> format * value no the value of the parameter. If this is an OUT or IN OUT parameter, * this should be a reference to a variable * type yes the type of the parameter * length yes the max size of the parameter */ public function stored_procedure($package, $procedure, $params) { if ($package == '' OR $procedure == '' OR ! is_array($params)) { if ($this->db_debug) { log_message('error', 'Invalid query: '.$package.'.'.$procedure); return $this->display_error('db_invalid_query'); } return FALSE; } // build the query string $sql = "begin $package.$procedure("; $have_cursor = FALSE; foreach ($params as $param) { $sql .= $param['name'] . ","; if (array_key_exists('type', $param) && ($param['type'] === OCI_B_CURSOR)) { $have_cursor = TRUE; } } $sql = trim($sql, ",") . "); end;"; $this->stmt_id = FALSE; $this->_set_stmt_id($sql); $this->_bind_params($params); $this->query($sql, FALSE, $have_cursor); } // -------------------------------------------------------------------- /** * Bind parameters * * @access private * @return none */ private function _bind_params($params) { if ( ! is_array($params) OR ! is_resource($this->stmt_id)) { return; } foreach ($params as $param) { foreach (array('name', 'value', 'type', 'length') as $val) { if ( ! isset($param[$val])) { $param[$val] = ''; } } oci_bind_by_name($this->stmt_id, $param['name'], $param['value'], $param['length'], $param['type']); } } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ public function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->_commit = OCI_DEFAULT; return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ public function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $ret = oci_commit($this->conn_id); $this->_commit = OCI_COMMIT_ON_SUCCESS; return $ret; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ public function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $ret = oci_rollback($this->conn_id); $this->_commit = OCI_COMMIT_ON_SUCCESS; return $ret; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ public function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } $str = remove_invisible_characters($str); // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array('%', '_', $this->_like_escape_chr), array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ public function affected_rows() { return @oci_num_rows($this->stmt_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ public function insert_id() { // not supported in oracle return $this->display_error('db_unsupported_function'); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ public function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query == FALSE) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @access protected * @param boolean * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = "SELECT TABLE_NAME FROM ALL_TABLES"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " WHERE TABLE_NAME LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access protected * @param string the table name * @return string */ protected function _list_columns($table = '') { return "SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = '$table'"; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ protected function _field_data($table) { return "SELECT * FROM ".$table." where rownum = 1"; } // -------------------------------------------------------------------- /** * The error message string * * @access protected * @return string */ protected function _error_message() { // If the error was during connection, no conn_id should be passed $error = is_resource($this->conn_id) ? oci_error($this->conn_id) : oci_error(); return $error['message']; } // -------------------------------------------------------------------- /** * The error message number * * @access protected * @return integer */ protected function _error_number() { // Same as _error_message() $error = is_resource($this->conn_id) ? oci_error($this->conn_id) : oci_error(); return $error['code']; } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access protected * @param string * @return string */ protected function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access protected * @param type * @return type */ protected function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return implode(', ', $tables); } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ protected function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access protected * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ protected function _insert_batch($table, $keys, $values) { $keys = implode(', ', $keys); $sql = "INSERT ALL\n"; for ($i = 0, $c = count($values); $i < $c; $i++) { $sql .= ' INTO ' . $table . ' (' . $keys . ') VALUES ' . $values[$i] . "\n"; } $sql .= 'SELECT * FROM dual'; return $sql; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access protected * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access protected * @param string the table name * @return string */ protected function _truncate($table) { return "TRUNCATE TABLE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access protected * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ protected function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access protected * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ protected function _limit($sql, $limit, $offset) { $limit = $offset + $limit; $newsql = "SELECT * FROM (select inner_query.*, rownum rnum FROM ($sql) inner_query WHERE rownum < $limit)"; if ($offset != 0) { $newsql .= " WHERE rnum >= $offset"; } // remember that we used limits $this->limit_used = TRUE; return $newsql; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access protected * @param resource * @return void */ protected function _close($conn_id) { @oci_close($conn_id); } } /* End of file oci8_driver.php */ /* Location: ./system/database/drivers/oci8/oci8_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/oci8/oci8_utility.php
system/database/drivers/oci8/oci8_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Oracle Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return FALSE; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return FALSE; // Is this supported in Oracle? } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return FALSE; // Is this supported in Oracle? } // -------------------------------------------------------------------- /** * Oracle Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file oci8_utility.php */ /* Location: ./system/database/drivers/oci8/oci8_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/postgre/postgre_driver.php
system/database/drivers/postgre/postgre_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Postgre Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_driver extends CI_DB { var $dbdriver = 'postgre'; var $_escape_char = '"'; // clause and character used for LIKE escape sequences var $_like_escape_str = " ESCAPE '%s' "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' RANDOM()'; // database specific random keyword /** * Connection String * * @access private * @return string */ function _connect_string() { $components = array( 'hostname' => 'host', 'port' => 'port', 'database' => 'dbname', 'username' => 'user', 'password' => 'password' ); $connect_string = ""; foreach ($components as $key => $val) { if (isset($this->$key) && $this->$key != '') { $connect_string .= " $val=".$this->$key; } } return trim($connect_string); } // -------------------------------------------------------------------- /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { return @pg_connect($this->_connect_string()); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { return @pg_pconnect($this->_connect_string()); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if (pg_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { // Not needed for Postgre so we'll return TRUE return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT version() AS ver"; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @pg_query($this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; return @pg_exec($this->conn_id, "begin"); } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } return @pg_exec($this->conn_id, "commit"); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } return @pg_exec($this->conn_id, "rollback"); } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } $str = pg_escape_string($str); // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array('%', '_', $this->_like_escape_chr), array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @pg_affected_rows($this->result_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { $v = $this->_version(); $v = $v['server']; $table = func_num_args() > 0 ? func_get_arg(0) : NULL; $column = func_num_args() > 1 ? func_get_arg(1) : NULL; if ($table == NULL && $v >= '8.1') { $sql='SELECT LASTVAL() as ins_id'; } elseif ($table != NULL && $column != NULL && $v >= '8.0') { $sql = sprintf("SELECT pg_get_serial_sequence('%s','%s') as seq", $table, $column); $query = $this->query($sql); $row = $query->row(); $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $row->seq); } elseif ($table != NULL) { // seq_name passed in table parameter $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table); } else { return pg_last_oid($this->result_id); } $query = $this->query($sql); $row = $query->row(); return $row->ins_id; } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SELECT column_name FROM information_schema.columns WHERE table_name ='".$table."'"; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT * FROM ".$table." LIMIT 1"; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return pg_last_error($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return ''; } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return implode(', ', $tables); } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { $sql .= "LIMIT ".$limit; if ($offset > 0) { $sql .= " OFFSET ".$offset; } return $sql; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @pg_close($conn_id); } } /* End of file postgre_driver.php */ /* Location: ./system/database/drivers/postgre/postgre_driver.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/postgre/postgre_result.php
system/database/drivers/postgre/postgre_result.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Postgres Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @pg_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @pg_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); for ($i = 0; $i < $this->num_fields(); $i++) { $field_names[] = pg_field_name($this->result_id, $i); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); for ($i = 0; $i < $this->num_fields(); $i++) { $F = new stdClass(); $F->name = pg_field_name($this->result_id, $i); $F->type = pg_field_type($this->result_id, $i); $F->max_length = pg_field_size($this->result_id, $i); $F->primary_key = 0; $F->default = ''; $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { pg_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return pg_result_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return pg_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return pg_fetch_object($this->result_id); } } /* End of file postgre_result.php */ /* Location: ./system/database/drivers/postgre/postgre_result.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/postgre/postgre_utility.php
system/database/drivers/postgre/postgre_utility.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Postgre Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return "SELECT datname FROM pg_database"; } // -------------------------------------------------------------------- /** * Optimize table query * * Is table optimization supported in Postgre? * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return FALSE; } // -------------------------------------------------------------------- /** * Repair table query * * Are table repairs supported in Postgre? * * @access private * @param string the table name * @return object */ function _repair_table($table) { return FALSE; } // -------------------------------------------------------------------- /** * Postgre Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file postgre_utility.php */ /* Location: ./system/database/drivers/postgre/postgre_utility.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/database/drivers/postgre/postgre_forge.php
system/database/drivers/postgre/postgre_forge.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Postgre Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { return "CREATE DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return "DROP DATABASE ".$name; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { if ($this->db->table_exists($table)) { return "SELECT * FROM $table"; // Needs to return innocous but valid SQL statement } } $sql .= $this->db->_escape_identifiers($table)." ("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $is_unsigned = (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE); // Convert datatypes to be PostgreSQL-compatible switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; break; case 'SMALLINT': $attributes['TYPE'] = ($is_unsigned) ? 'INTEGER' : 'SMALLINT'; break; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; break; case 'INT': $attributes['TYPE'] = ($is_unsigned) ? 'BIGINT' : 'INTEGER'; break; case 'BIGINT': $attributes['TYPE'] = ($is_unsigned) ? 'NUMERIC' : 'BIGINT'; break; case 'DOUBLE': $attributes['TYPE'] = 'DOUBLE PRECISION'; break; case 'DATETIME': $attributes['TYPE'] = 'TIMESTAMP'; break; case 'LONGTEXT': $attributes['TYPE'] = 'TEXT'; break; case 'BLOB': $attributes['TYPE'] = 'BYTEA'; break; } // If this is an auto-incrementing primary key, use the serial data type instead if (in_array($field, $primary_keys) && array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' SERIAL'; } else { $sql .= ' '.$attributes['TYPE']; } // Modified to prevent constraints with integer data types if (array_key_exists('CONSTRAINT', $attributes) && strpos($attributes['TYPE'], 'INT') === false) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } // Added new attribute to create unqite fields. Also works with MySQL if (array_key_exists('UNIQUE', $attributes) && $attributes['UNIQUE'] === TRUE) { $sql .= ' UNIQUE'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { // Something seems to break when passing an array to _protect_identifiers() foreach ($primary_keys as $index => $key) { $primary_keys[$index] = $this->db->_protect_identifiers($key); } $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } $sql .= "\n);"; if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } foreach ($key as $field) { $sql .= "CREATE INDEX " . $table . "_" . str_replace(array('"', "'"), '', $field) . "_index ON $table ($field); "; } } } return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return bool */ function _drop_table($table) { return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table)." CASCADE"; } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file postgre_forge.php */ /* Location: ./system/database/drivers/postgre/postgre_forge.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/migration_lang.php
system/language/english/migration_lang.php
<?php $lang['migration_none_found'] = "No migrations were found."; $lang['migration_not_found'] = "This migration could not be found."; $lang['migration_multiple_version'] = "This are multiple migrations with the same version number: %d."; $lang['migration_class_doesnt_exist'] = "The migration class \"%s\" could not be found."; $lang['migration_missing_up_method'] = "The migration class \"%s\" is missing an 'up' method."; $lang['migration_missing_down_method'] = "The migration class \"%s\" is missing an 'down' method."; $lang['migration_invalid_filename'] = "Migration \"%s\" has an invalid filename."; /* End of file migration_lang.php */ /* Location: ./system/language/english/migration_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/profiler_lang.php
system/language/english/profiler_lang.php
<?php $lang['profiler_database'] = 'DATABASE'; $lang['profiler_controller_info'] = 'CLASS/METHOD'; $lang['profiler_benchmarks'] = 'BENCHMARKS'; $lang['profiler_queries'] = 'QUERIES'; $lang['profiler_get_data'] = 'GET DATA'; $lang['profiler_post_data'] = 'POST DATA'; $lang['profiler_uri_string'] = 'URI STRING'; $lang['profiler_memory_usage'] = 'MEMORY USAGE'; $lang['profiler_config'] = 'CONFIG VARIABLES'; $lang['profiler_session_data'] = 'SESSION DATA'; $lang['profiler_headers'] = 'HTTP HEADERS'; $lang['profiler_no_db'] = 'Database driver is not currently loaded'; $lang['profiler_no_queries'] = 'No queries were run'; $lang['profiler_no_post'] = 'No POST data exists'; $lang['profiler_no_get'] = 'No GET data exists'; $lang['profiler_no_uri'] = 'No URI data exists'; $lang['profiler_no_memory'] = 'Memory Usage Unavailable'; $lang['profiler_no_profiles'] = 'No Profile data - all Profiler sections have been disabled.'; $lang['profiler_section_hide'] = 'Hide'; $lang['profiler_section_show'] = 'Show'; /* End of file profiler_lang.php */ /* Location: ./system/language/english/profiler_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/email_lang.php
system/language/english/email_lang.php
<?php $lang['email_must_be_array'] = "The email validation method must be passed an array."; $lang['email_invalid_address'] = "Invalid email address: %s"; $lang['email_attachment_missing'] = "Unable to locate the following email attachment: %s"; $lang['email_attachment_unreadable'] = "Unable to open this attachment: %s"; $lang['email_no_recipients'] = "You must include recipients: To, Cc, or Bcc"; $lang['email_send_failure_phpmail'] = "Unable to send email using PHP mail(). Your server might not be configured to send mail using this method."; $lang['email_send_failure_sendmail'] = "Unable to send email using PHP Sendmail. Your server might not be configured to send mail using this method."; $lang['email_send_failure_smtp'] = "Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method."; $lang['email_sent'] = "Your message has been successfully sent using the following protocol: %s"; $lang['email_no_socket'] = "Unable to open a socket to Sendmail. Please check settings."; $lang['email_no_hostname'] = "You did not specify a SMTP hostname."; $lang['email_smtp_error'] = "The following SMTP error was encountered: %s"; $lang['email_no_smtp_unpw'] = "Error: You must assign a SMTP username and password."; $lang['email_failed_smtp_login'] = "Failed to send AUTH LOGIN command. Error: %s"; $lang['email_smtp_auth_un'] = "Failed to authenticate username. Error: %s"; $lang['email_smtp_auth_pw'] = "Failed to authenticate password. Error: %s"; $lang['email_smtp_data_failure'] = "Unable to send data: %s"; $lang['email_exit_status'] = "Exit status code: %s"; /* End of file email_lang.php */ /* Location: ./system/language/english/email_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/imglib_lang.php
system/language/english/imglib_lang.php
<?php $lang['imglib_source_image_required'] = "You must specify a source image in your preferences."; $lang['imglib_gd_required'] = "The GD image library is required for this feature."; $lang['imglib_gd_required_for_props'] = "Your server must support the GD image library in order to determine the image properties."; $lang['imglib_unsupported_imagecreate'] = "Your server does not support the GD function required to process this type of image."; $lang['imglib_gif_not_supported'] = "GIF images are often not supported due to licensing restrictions. You may have to use JPG or PNG images instead."; $lang['imglib_jpg_not_supported'] = "JPG images are not supported."; $lang['imglib_png_not_supported'] = "PNG images are not supported."; $lang['imglib_jpg_or_png_required'] = "The image resize protocol specified in your preferences only works with JPEG or PNG image types."; $lang['imglib_copy_error'] = "An error was encountered while attempting to replace the file. Please make sure your file directory is writable."; $lang['imglib_rotate_unsupported'] = "Image rotation does not appear to be supported by your server."; $lang['imglib_libpath_invalid'] = "The path to your image library is not correct. Please set the correct path in your image preferences."; $lang['imglib_image_process_failed'] = "Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct."; $lang['imglib_rotation_angle_required'] = "An angle of rotation is required to rotate the image."; $lang['imglib_writing_failed_gif'] = "GIF image."; $lang['imglib_invalid_path'] = "The path to the image is not correct."; $lang['imglib_copy_failed'] = "The image copy routine failed."; $lang['imglib_missing_font'] = "Unable to find a font to use."; $lang['imglib_save_failed'] = "Unable to save the image. Please make sure the image and file directory are writable."; /* End of file imglib_lang.php */ /* Location: ./system/language/english/imglib_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/unit_test_lang.php
system/language/english/unit_test_lang.php
<?php $lang['ut_test_name'] = 'Test Name'; $lang['ut_test_datatype'] = 'Test Datatype'; $lang['ut_res_datatype'] = 'Expected Datatype'; $lang['ut_result'] = 'Result'; $lang['ut_undefined'] = 'Undefined Test Name'; $lang['ut_file'] = 'File Name'; $lang['ut_line'] = 'Line Number'; $lang['ut_passed'] = 'Passed'; $lang['ut_failed'] = 'Failed'; $lang['ut_boolean'] = 'Boolean'; $lang['ut_integer'] = 'Integer'; $lang['ut_float'] = 'Float'; $lang['ut_double'] = 'Float'; // can be the same as float $lang['ut_string'] = 'String'; $lang['ut_array'] = 'Array'; $lang['ut_object'] = 'Object'; $lang['ut_resource'] = 'Resource'; $lang['ut_null'] = 'Null'; $lang['ut_notes'] = 'Notes'; /* End of file unit_test_lang.php */ /* Location: ./system/language/english/unit_test_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/ftp_lang.php
system/language/english/ftp_lang.php
<?php $lang['ftp_no_connection'] = "Unable to locate a valid connection ID. Please make sure you are connected before peforming any file routines."; $lang['ftp_unable_to_connect'] = "Unable to connect to your FTP server using the supplied hostname."; $lang['ftp_unable_to_login'] = "Unable to login to your FTP server. Please check your username and password."; $lang['ftp_unable_to_makdir'] = "Unable to create the directory you have specified."; $lang['ftp_unable_to_changedir'] = "Unable to change directories."; $lang['ftp_unable_to_chmod'] = "Unable to set file permissions. Please check your path. Note: This feature is only available in PHP 5 or higher."; $lang['ftp_unable_to_upload'] = "Unable to upload the specified file. Please check your path."; $lang['ftp_unable_to_download'] = "Unable to download the specified file. Please check your path."; $lang['ftp_no_source_file'] = "Unable to locate the source file. Please check your path."; $lang['ftp_unable_to_rename'] = "Unable to rename the file."; $lang['ftp_unable_to_delete'] = "Unable to delete the file."; $lang['ftp_unable_to_move'] = "Unable to move the file. Please make sure the destination directory exists."; /* End of file ftp_lang.php */ /* Location: ./system/language/english/ftp_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/date_lang.php
system/language/english/date_lang.php
<?php $lang['date_year'] = "Year"; $lang['date_years'] = "Years"; $lang['date_month'] = "Month"; $lang['date_months'] = "Months"; $lang['date_week'] = "Week"; $lang['date_weeks'] = "Weeks"; $lang['date_day'] = "Day"; $lang['date_days'] = "Days"; $lang['date_hour'] = "Hour"; $lang['date_hours'] = "Hours"; $lang['date_minute'] = "Minute"; $lang['date_minutes'] = "Minutes"; $lang['date_second'] = "Second"; $lang['date_seconds'] = "Seconds"; $lang['UM12'] = '(UTC -12:00) Baker/Howland Island'; $lang['UM11'] = '(UTC -11:00) Samoa Time Zone, Niue'; $lang['UM10'] = '(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti'; $lang['UM95'] = '(UTC -9:30) Marquesas Islands'; $lang['UM9'] = '(UTC -9:00) Alaska Standard Time, Gambier Islands'; $lang['UM8'] = '(UTC -8:00) Pacific Standard Time, Clipperton Island'; $lang['UM7'] = '(UTC -7:00) Mountain Standard Time'; $lang['UM6'] = '(UTC -6:00) Central Standard Time'; $lang['UM5'] = '(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time'; $lang['UM45'] = '(UTC -4:30) Venezuelan Standard Time'; $lang['UM4'] = '(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time'; $lang['UM35'] = '(UTC -3:30) Newfoundland Standard Time'; $lang['UM3'] = '(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay'; $lang['UM2'] = '(UTC -2:00) South Georgia/South Sandwich Islands'; $lang['UM1'] = '(UTC -1:00) Azores, Cape Verde Islands'; $lang['UTC'] = '(UTC) Greenwich Mean Time, Western European Time'; $lang['UP1'] = '(UTC +1:00) Central European Time, West Africa Time'; $lang['UP2'] = '(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time'; $lang['UP3'] = '(UTC +3:00) Moscow Time, East Africa Time'; $lang['UP35'] = '(UTC +3:30) Iran Standard Time'; $lang['UP4'] = '(UTC +4:00) Azerbaijan Standard Time, Samara Time'; $lang['UP45'] = '(UTC +4:30) Afghanistan'; $lang['UP5'] = '(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time'; $lang['UP55'] = '(UTC +5:30) Indian Standard Time, Sri Lanka Time'; $lang['UP575'] = '(UTC +5:45) Nepal Time'; $lang['UP6'] = '(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time'; $lang['UP65'] = '(UTC +6:30) Cocos Islands, Myanmar'; $lang['UP7'] = '(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam'; $lang['UP8'] = '(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time'; $lang['UP875'] = '(UTC +8:45) Australian Central Western Standard Time'; $lang['UP9'] = '(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time'; $lang['UP95'] = '(UTC +9:30) Australian Central Standard Time'; $lang['UP10'] = '(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time'; $lang['UP105'] = '(UTC +10:30) Lord Howe Island'; $lang['UP11'] = '(UTC +11:00) Magadan Time, Solomon Islands, Vanuatu'; $lang['UP115'] = '(UTC +11:30) Norfolk Island'; $lang['UP12'] = '(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time'; $lang['UP1275'] = '(UTC +12:45) Chatham Islands Standard Time'; $lang['UP13'] = '(UTC +13:00) Phoenix Islands Time, Tonga'; $lang['UP14'] = '(UTC +14:00) Line Islands'; /* End of file date_lang.php */ /* Location: ./system/language/english/date_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/calendar_lang.php
system/language/english/calendar_lang.php
<?php $lang['cal_su'] = "Su"; $lang['cal_mo'] = "Mo"; $lang['cal_tu'] = "Tu"; $lang['cal_we'] = "We"; $lang['cal_th'] = "Th"; $lang['cal_fr'] = "Fr"; $lang['cal_sa'] = "Sa"; $lang['cal_sun'] = "Sun"; $lang['cal_mon'] = "Mon"; $lang['cal_tue'] = "Tue"; $lang['cal_wed'] = "Wed"; $lang['cal_thu'] = "Thu"; $lang['cal_fri'] = "Fri"; $lang['cal_sat'] = "Sat"; $lang['cal_sunday'] = "Sunday"; $lang['cal_monday'] = "Monday"; $lang['cal_tuesday'] = "Tuesday"; $lang['cal_wednesday'] = "Wednesday"; $lang['cal_thursday'] = "Thursday"; $lang['cal_friday'] = "Friday"; $lang['cal_saturday'] = "Saturday"; $lang['cal_jan'] = "Jan"; $lang['cal_feb'] = "Feb"; $lang['cal_mar'] = "Mar"; $lang['cal_apr'] = "Apr"; $lang['cal_may'] = "May"; $lang['cal_jun'] = "Jun"; $lang['cal_jul'] = "Jul"; $lang['cal_aug'] = "Aug"; $lang['cal_sep'] = "Sep"; $lang['cal_oct'] = "Oct"; $lang['cal_nov'] = "Nov"; $lang['cal_dec'] = "Dec"; $lang['cal_january'] = "January"; $lang['cal_february'] = "February"; $lang['cal_march'] = "March"; $lang['cal_april'] = "April"; $lang['cal_mayl'] = "May"; $lang['cal_june'] = "June"; $lang['cal_july'] = "July"; $lang['cal_august'] = "August"; $lang['cal_september'] = "September"; $lang['cal_october'] = "October"; $lang['cal_november'] = "November"; $lang['cal_december'] = "December"; /* End of file calendar_lang.php */ /* Location: ./system/language/english/calendar_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/upload_lang.php
system/language/english/upload_lang.php
<?php $lang['upload_userfile_not_set'] = "Unable to find a post variable called userfile."; $lang['upload_file_exceeds_limit'] = "The uploaded file exceeds the maximum allowed size in your PHP configuration file."; $lang['upload_file_exceeds_form_limit'] = "The uploaded file exceeds the maximum size allowed by the submission form."; $lang['upload_file_partial'] = "The file was only partially uploaded."; $lang['upload_no_temp_directory'] = "The temporary folder is missing."; $lang['upload_unable_to_write_file'] = "The file could not be written to disk."; $lang['upload_stopped_by_extension'] = "The file upload was stopped by extension."; $lang['upload_no_file_selected'] = "You did not select a file to upload."; $lang['upload_invalid_filetype'] = "The filetype you are attempting to upload is not allowed."; $lang['upload_invalid_filesize'] = "The file you are attempting to upload is larger than the permitted size."; $lang['upload_invalid_dimensions'] = "The image you are attempting to upload exceedes the maximum height or width."; $lang['upload_destination_error'] = "A problem was encountered while attempting to move the uploaded file to the final destination."; $lang['upload_no_filepath'] = "The upload path does not appear to be valid."; $lang['upload_no_file_types'] = "You have not specified any allowed file types."; $lang['upload_bad_filename'] = "The file name you submitted already exists on the server."; $lang['upload_not_writable'] = "The upload destination folder does not appear to be writable."; /* End of file upload_lang.php */ /* Location: ./system/language/english/upload_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/form_validation_lang.php
system/language/english/form_validation_lang.php
<?php $lang['required'] = "The %s field is required."; $lang['isset'] = "The %s field must have a value."; $lang['valid_email'] = "The %s field must contain a valid email address."; $lang['valid_emails'] = "The %s field must contain all valid email addresses."; $lang['valid_url'] = "The %s field must contain a valid URL."; $lang['valid_ip'] = "The %s field must contain a valid IP."; $lang['min_length'] = "The %s field must be at least %s characters in length."; $lang['max_length'] = "The %s field can not exceed %s characters in length."; $lang['exact_length'] = "The %s field must be exactly %s characters in length."; $lang['alpha'] = "The %s field may only contain alphabetical characters."; $lang['alpha_numeric'] = "The %s field may only contain alpha-numeric characters."; $lang['alpha_dash'] = "The %s field may only contain alpha-numeric characters, underscores, and dashes."; $lang['numeric'] = "The %s field must contain only numbers."; $lang['is_numeric'] = "The %s field must contain only numeric characters."; $lang['integer'] = "The %s field must contain an integer."; $lang['regex_match'] = "The %s field is not in the correct format."; $lang['matches'] = "The %s field does not match the %s field."; $lang['is_unique'] = "The %s field must contain a unique value."; $lang['is_natural'] = "The %s field must contain only positive numbers."; $lang['is_natural_no_zero'] = "The %s field must contain a number greater than zero."; $lang['decimal'] = "The %s field must contain a decimal number."; $lang['less_than'] = "The %s field must contain a number less than %s."; $lang['greater_than'] = "The %s field must contain a number greater than %s."; /* End of file form_validation_lang.php */ /* Location: ./system/language/english/form_validation_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/db_lang.php
system/language/english/db_lang.php
<?php $lang['db_invalid_connection_str'] = 'Unable to determine the database settings based on the connection string you submitted.'; $lang['db_unable_to_connect'] = 'Unable to connect to your database server using the provided settings.'; $lang['db_unable_to_select'] = 'Unable to select the specified database: %s'; $lang['db_unable_to_create'] = 'Unable to create the specified database: %s'; $lang['db_invalid_query'] = 'The query you submitted is not valid.'; $lang['db_must_set_table'] = 'You must set the database table to be used with your query.'; $lang['db_must_use_set'] = 'You must use the "set" method to update an entry.'; $lang['db_must_use_index'] = 'You must specify an index to match on for batch updates.'; $lang['db_batch_missing_index'] = 'One or more rows submitted for batch updating is missing the specified index.'; $lang['db_must_use_where'] = 'Updates are not allowed unless they contain a "where" clause.'; $lang['db_del_must_use_where'] = 'Deletes are not allowed unless they contain a "where" or "like" clause.'; $lang['db_field_param_missing'] = 'To fetch fields requires the name of the table as a parameter.'; $lang['db_unsupported_function'] = 'This feature is not available for the database you are using.'; $lang['db_transaction_failure'] = 'Transaction failure: Rollback performed.'; $lang['db_unable_to_drop'] = 'Unable to drop the specified database.'; $lang['db_unsuported_feature'] = 'Unsupported feature of the database platform you are using.'; $lang['db_unsuported_compression'] = 'The file compression format you chose is not supported by your server.'; $lang['db_filepath_error'] = 'Unable to write data to the file path you have submitted.'; $lang['db_invalid_cache_path'] = 'The cache path you submitted is not valid or writable.'; $lang['db_table_name_required'] = 'A table name is required for that operation.'; $lang['db_column_name_required'] = 'A column name is required for that operation.'; $lang['db_column_definition_required'] = 'A column definition is required for that operation.'; $lang['db_unable_to_set_charset'] = 'Unable to set client connection character set: %s'; $lang['db_error_heading'] = 'A Database Error Occurred'; /* End of file db_lang.php */ /* Location: ./system/language/english/db_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/language/english/number_lang.php
system/language/english/number_lang.php
<?php $lang['terabyte_abbr'] = "TB"; $lang['gigabyte_abbr'] = "GB"; $lang['megabyte_abbr'] = "MB"; $lang['kilobyte_abbr'] = "KB"; $lang['bytes'] = "Bytes"; /* End of file number_lang.php */ /* Location: ./system/language/english/number_lang.php */
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false
bilalq/Tranquillity-Editor
https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/test/version_test.php
tools/test/version_test.php
<?php class Version_test extends Spark_test_case { function test_version() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('version'); }); $this->assertEquals(array(SPARK_VERSION), $clines); } function test_sources() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('sources'); }); $this->assertEquals($this->source_names, $clines); } function test_bad_command() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('fake'); }); $this->assertEquals(array(chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Uh-oh!', chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Unknown action: fake'), $clines); } function test_search_empty() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('search', array('nothing_found_here')); }); $this->assertEquals(array(), $clines); } }
php
MIT
6e936d7bef75e50d0f056bf0c4bbdaef9210f340
2026-01-05T04:46:50.686838Z
false