idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
47,600
|
public function exec ( $ query , $ params = array ( ) ) { $ this -> openConnection ( ) ; $ this -> query = $ query ; try { $ stat = $ this -> handler -> prepare ( $ this -> query ) ; $ stat -> execute ( ( array ) $ params ) ; $ affected = $ stat -> rowCount ( ) ; } catch ( \ PDOException $ e ) { $ this -> logParamQuery ( $ this -> query , 0 , $ params ) ; switch ( $ e -> getCode ( ) ) { default : $ message = $ e -> getMessage ( ) ; break ; } $ this -> addError ( $ message ) ; $ affected = 0 ; } catch ( \ Exception $ e ) { $ this -> logParamQuery ( $ this -> query , 0 , $ params ) ; $ this -> addError ( $ e -> getMessage ( ) ) ; $ affected = 0 ; } $ stat -> closeCursor ( ) ; $ this -> logParamQuery ( $ this -> query , $ affected , $ params ) ; return $ affected ; }
|
Executes a query and returns TRUE if success .
|
47,601
|
public static function load ( string $ query , ? array $ params = array ( ) , $ option = NULL ) { $ self = static :: getInstance ( ) ; $ self -> openConnection ( ) ; $ res = NULL ; try { $ stat = $ self -> handler -> prepare ( $ query ) ; $ stat -> execute ( ( array ) $ params ) ; switch ( strtolower ( $ option ) ) { default : case PAIR_DB_OBJECT_LIST : case 'objectlist' : $ res = $ stat -> fetchAll ( \ PDO :: FETCH_OBJ ) ; $ count = count ( $ res ) ; break ; case PAIR_DB_OBJECT : case 'object' : $ res = $ stat -> fetch ( \ PDO :: FETCH_OBJ ) ; $ count = ( bool ) $ res ; break ; case PAIR_DB_RESULT_LIST : case 'resultlist' : $ res = $ stat -> fetchAll ( \ PDO :: FETCH_COLUMN ) ; $ count = count ( $ res ) ; break ; case PAIR_DB_RESULT : case 'result' : $ res = $ stat -> fetch ( \ PDO :: FETCH_COLUMN ) ; $ count = $ self -> handler -> query ( 'SELECT FOUND_ROWS()' ) -> fetchColumn ( ) ; break ; case PAIR_DB_COUNT : case 'count' : $ res = ( int ) $ stat -> fetch ( \ PDO :: FETCH_COLUMN ) ; $ count = $ res ; break ; } $ self -> logParamQuery ( $ query , $ count , $ params ) ; } catch ( \ PDOException $ e ) { $ self -> handleException ( $ e , $ params ) ; } $ stat -> closeCursor ( ) ; return $ res ; }
|
Return data in various formats by third string parameter . Default is PAIR_DB_OBJECT_LIST parameters as array . Support PDO parameters bind .
|
47,602
|
public static function run ( $ query , $ params = array ( ) ) { $ self = static :: getInstance ( ) ; $ self -> openConnection ( ) ; $ ret = NULL ; try { $ stat = $ self -> handler -> prepare ( $ query ) ; $ stat -> execute ( ( array ) $ params ) ; $ affected = $ stat -> rowCount ( ) ; } catch ( \ PDOException $ e ) { $ self -> logParamQuery ( $ query , 0 , $ params ) ; switch ( $ e -> getCode ( ) ) { default : $ message = $ e -> getMessage ( ) ; break ; } $ self -> addError ( $ message ) ; $ affected = 0 ; } catch ( \ Exception $ e ) { $ self -> logParamQuery ( $ query , 0 , $ params ) ; $ self -> addError ( $ e -> getMessage ( ) ) ; $ affected = 0 ; } $ stat -> closeCursor ( ) ; $ self -> logParamQuery ( $ query , $ affected , $ params ) ; return $ affected ; }
|
Run a query with parameters and return TRUE if success . Support PDO parameters bind .
|
47,603
|
public function loadResult ( $ params = array ( ) ) { $ this -> openConnection ( ) ; $ res = NULL ; try { $ stat = $ this -> handler -> prepare ( $ this -> query ) ; $ stat -> execute ( ( array ) $ params ) ; $ count = $ this -> handler -> query ( 'SELECT FOUND_ROWS()' ) -> fetchColumn ( ) ; $ this -> logParamQuery ( $ this -> query , $ count , $ params ) ; $ res = $ stat -> fetch ( \ PDO :: FETCH_COLUMN ) ; } catch ( \ PDOException $ e ) { $ this -> handleException ( $ e , $ params ) ; } $ stat -> closeCursor ( ) ; return $ res ; }
|
Returns first field value or NULL if row is not found .
|
47,604
|
public function loadCount ( $ params = array ( ) ) { $ this -> openConnection ( ) ; $ res = 0 ; try { $ stat = $ this -> handler -> prepare ( $ this -> query ) ; $ stat -> execute ( ( array ) $ params ) ; $ res = ( int ) $ stat -> fetch ( \ PDO :: FETCH_COLUMN ) ; $ this -> logParamQuery ( $ this -> query , $ res , $ params ) ; } catch ( \ PDOException $ e ) { $ this -> handleException ( $ e , $ params ) ; } $ stat -> closeCursor ( ) ; return $ res ; }
|
Return the query count as integer number .
|
47,605
|
public function insertObject ( $ table , $ object ) { $ fields = array ( ) ; $ values = array ( ) ; foreach ( get_object_vars ( $ object ) as $ k => $ v ) { if ( is_string ( $ v ) or is_numeric ( $ v ) ) { $ fields [ ] = '`' . $ k . '`' ; $ values [ ] = $ this -> quote ( $ v ) ; } else if ( is_null ( $ v ) ) { $ fields [ ] = '`' . $ k . '`' ; $ values [ ] = 'NULL' ; } } $ sql = 'INSERT INTO `' . $ table . '` (%s) VALUES (%s)' ; $ this -> query = sprintf ( $ sql , implode ( ', ' , $ fields ) , implode ( ', ' , $ values ) ) ; $ res = $ this -> exec ( $ this -> query ) ; return ( bool ) $ res ; }
|
Inserts a new row in param table with all properties value as fields value .
|
47,606
|
public function insertObjects ( $ table , $ list ) { if ( ! is_array ( $ list ) or 0 == count ( $ list ) ) { return 0 ; } $ records = array ( ) ; $ fields = array ( ) ; foreach ( $ list as $ object ) { $ values = array ( ) ; foreach ( get_object_vars ( $ object ) as $ k => $ v ) { if ( ! count ( $ records ) ) { $ fields [ ] = '`' . $ k . '`' ; } $ values [ ] = is_null ( $ v ) ? 'NULL' : $ this -> quote ( $ v ) ; } $ records [ ] = '(' . implode ( ',' , $ values ) . ')' ; } $ sql = 'INSERT INTO `' . $ table . '` (%s) VALUES %s' ; $ this -> query = sprintf ( $ sql , implode ( ',' , $ fields ) , implode ( ',' , $ records ) ) ; $ res = $ this -> exec ( $ this -> query ) ; return $ res ; }
|
Insert more than one row into param table .
|
47,607
|
public function updateObject ( $ table , & $ object , $ key ) { $ sets = array ( ) ; $ where = array ( ) ; $ fieldVal = array ( ) ; $ condVal = array ( ) ; foreach ( get_object_vars ( $ key ) as $ field => $ value ) { $ where [ ] = $ field . ' = ?' ; $ condVal [ ] = $ value ; } foreach ( get_object_vars ( $ object ) as $ field => $ value ) { if ( is_null ( $ value ) ) { $ sets [ ] = '`' . $ field . '` = NULL' ; } else { $ sets [ ] = '`' . $ field . '` = ?' ; $ fieldVal [ ] = $ value ; } } $ values = array_merge ( $ fieldVal , $ condVal ) ; if ( count ( $ sets ) and count ( $ where ) ) { $ query = 'UPDATE `' . $ table . '`' . ' SET ' . implode ( ', ' , $ sets ) . ' WHERE ' . implode ( ' AND ' , $ where ) ; $ res = $ this -> exec ( $ query , $ values ) ; } else { $ res = 0 ; } return $ res ; }
|
Update record of given key on the param object . Properly manage NULL values .
|
47,608
|
public function describeTable ( $ tableName ) { if ( ! isset ( $ this -> definitions [ $ tableName ] [ 'describe' ] ) ) { $ res = self :: load ( 'DESCRIBE `' . $ tableName . '`' , NULL , PAIR_DB_OBJECT_LIST ) ; $ this -> definitions [ $ tableName ] [ 'describe' ] = is_null ( $ res ) ? [ ] : $ res ; } return $ this -> definitions [ $ tableName ] [ 'describe' ] ; }
|
Return data about table scheme . Memory cached .
|
47,609
|
public function describeColumn ( $ tableName , $ column ) { if ( isset ( $ this -> definitions [ $ tableName ] [ 'describe' ] ) ) { foreach ( $ this -> definitions [ $ tableName ] [ 'describe' ] as $ d ) { if ( $ column == $ d -> Field ) { return $ d ; } } } $ res = self :: load ( 'DESCRIBE `' . $ tableName . '` `' . $ column . '`' , NULL , PAIR_DB_OBJECT ) ; return ( $ res ? $ res : NULL ) ; }
|
Return data about a column scheme trying to load table description records by object cache . FALSE in case of unvalid column name .
|
47,610
|
public function getTableKeys ( $ tableName ) { $ keys = array ( ) ; $ fields = $ this -> describeTable ( $ tableName ) ; foreach ( $ fields as $ field ) { if ( 'PRI' == $ field -> Key ) { $ keys [ ] = $ field -> Field ; } } return $ keys ; }
|
Return an array of table - key names by using cached methods .
|
47,611
|
public function isAutoIncrement ( $ tableName ) { $ fields = $ this -> describeTable ( $ tableName ) ; foreach ( $ fields as $ field ) { if ( 'auto_increment' == $ field -> Extra ) { return TRUE ; } } return FALSE ; }
|
Check if parameter table has auto - increment primary key by using cached method .
|
47,612
|
public function setUtf8unicode ( ) { $ this -> openConnection ( ) ; try { $ this -> handler -> exec ( 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci' ) ; $ this -> handler -> exec ( 'SET character_set_client = "utf8mb4", character_set_connection = "utf8mb4",' . ' character_set_database = "utf8mb4", character_set_results = "utf8mb4",' . ' character_set_server = "utf8mb4", collation_connection = "utf8mb4_unicode_ci",' . ' collation_database = "utf8mb4_unicode_ci", collation_server = "utf8mb4_unicode_ci"' ) ; } catch ( \ Exception $ e ) { } }
|
Set MySQL connection as UTF8mb4 and collation as utf8mb4_unicode_ci useful to support extended unicode like Emoji .
|
47,613
|
private function logQuery ( $ query , $ result ) { $ subtext = ( int ) $ result . ' ' . ( 1 == $ result ? 'row' : 'rows' ) ; $ logger = Logger :: getInstance ( ) ; $ logger -> addEvent ( $ query , 'query' , $ subtext ) ; }
|
Adds an entry item on system log .
|
47,614
|
private function handleException ( $ e , $ params ) { $ this -> logParamQuery ( $ this -> query , 0 , $ params ) ; switch ( $ e -> getCode ( ) ) { case 'HY093' : if ( is_array ( $ params ) ) { $ message = 'Parameters count is ' . count ( $ params ) . ', an array with different number is expected by function call' ; } else { $ message = 'Parameters are expected in array format by function call, type ' . gettype ( $ params ) . ' was passed' ; } break ; default : $ message = $ e -> getMessage ( ) ; break ; } $ this -> addError ( $ message ) ; }
|
Log query switch error and add to DB class error list .
|
47,615
|
public static function getDebugBacktrace ( ) { $ backtrace = debug_backtrace ( ) ; array_shift ( $ backtrace ) ; $ ret = array ( ) ; foreach ( $ backtrace as $ event ) { $ args = array ( ) ; if ( array_key_exists ( 'args' , $ event ) ) { foreach ( $ event [ 'args' ] as $ arg ) { $ args [ ] = is_array ( $ arg ) ? 'array' : ( is_object ( $ arg ) ? get_class ( $ arg ) : ( string ) $ arg ) ; } } $ ret [ ] = ( isset ( $ event [ 'class' ] ) ? $ event [ 'class' ] . $ event [ 'type' ] : '' ) . $ event [ 'function' ] . '(' . implode ( ', ' , $ args ) . ')' . ( isset ( $ event [ 'file' ] ) ? ' | file ' . basename ( $ event [ 'file' ] ) : '' ) . ( isset ( $ event [ 'line' ] ) ? ' line ' . $ event [ 'line' ] : '' ) ; } return $ ret ; }
|
Get the backtrace and assemble an array with comprehensible items .
|
47,616
|
public static function varToText ( $ var ) { $ type = gettype ( $ var ) ; $ text = is_null ( $ type ) ? 'NULL' : $ type . ':' ; switch ( $ type ) { case 'boolean' : $ text .= $ var ? 'TRUE' : 'FALSE' ; break ; default : $ text .= $ var ; break ; case 'array' : $ parts = array ( ) ; foreach ( $ var as $ k => $ v ) { $ parts [ ] = $ k . '=>' . self :: varToText ( $ v ) ; } $ text .= 'array:[' . implode ( ',' , $ parts ) . ']' ; break ; case 'object' : $ text .= get_class ( $ var ) ; break ; case 'NULL' : break ; } return $ text ; }
|
Creates a plain text string from any variable type .
|
47,617
|
public static function convertDateToHuman ( $ dbDate , $ removeHours = FALSE ) { $ t = Translator :: getInstance ( ) ; $ date = new \ DateTime ( $ dbDate ) ; $ dateFormat = $ removeHours ? 'DATE_FORMAT' : 'DATETIME_FORMAT' ; return $ date -> format ( $ t -> get ( $ dateFormat ) ) ; }
|
Converts a date from DB format to an human readable format based on current user language .
|
47,618
|
public static function convertToDbDate ( \ DateTime $ dateTime ) { $ currentTz = $ dateTime -> getTimezone ( ) ; $ dateTime -> setTimezone ( new \ DateTimeZone ( BASE_TIMEZONE ) ) ; $ ret = $ dateTime -> format ( 'Y-m-d' ) ; $ dateTime -> setTimezone ( $ currentTz ) ; return $ ret ; }
|
Converts a DateTime object to date field type for db query . In case of UTC_DATE parameter on date will be temporary converted to UTC .
|
47,619
|
public static function timestampFromDatepicker ( $ date , $ hour = NULL , $ minute = NULL , $ second = NULL ) { $ d = substr ( $ date , 0 , 2 ) ; $ m = substr ( $ date , 3 , 2 ) ; $ y = substr ( $ date , 6 , 4 ) ; $ time = mktime ( $ hour , $ minute , $ second , $ m , $ d , $ y ) ; return ( $ time ? $ time : null ) ; }
|
Create timestamp of a DateTime object as returned by jQuery datepicker .
|
47,620
|
public static function getJsMessage ( $ title , $ message , $ type = 'info' ) { $ types = array ( 'info' , 'warning' , 'error' ) ; if ( ! in_array ( $ type , $ types ) ) $ type = 'info' ; $ message = '<script>$(document).ready(function(){$.showMessage("' . addslashes ( $ title ) . '","' . addslashes ( $ message ) . '","' . addslashes ( $ type ) . '");});</script>' ; return $ message ; }
|
Return the HTML code that prints a JS message in page at runtime .
|
47,621
|
public static function getTimeago ( $ date ) { $ app = Application :: getInstance ( ) ; if ( is_int ( $ date ) ) { $ dateTime = new \ DateTime ( ) ; $ dateTime -> setTimestamp ( $ dateTime ) ; $ dateTime -> setTimezone ( $ app -> currentUser -> getDateTimeZone ( ) ) ; } else if ( is_string ( $ date ) ) { if ( 0 !== strpos ( $ date , '0000-00-00 00:00:00' ) ) { $ dateTime = new \ DateTime ( $ date ) ; $ dateTime -> setTimezone ( $ app -> currentUser -> getDateTimeZone ( ) ) ; } else { $ dateTime = NULL ; } } else if ( is_a ( $ date , 'DateTime' ) ) { $ dateTime = $ date ; $ dateTime -> setTimezone ( $ app -> currentUser -> getDateTimeZone ( ) ) ; } else { $ dateTime = NULL ; } if ( is_a ( $ dateTime , 'DateTime' ) ) { $ tran = Translator :: getInstance ( ) ; if ( $ tran -> stringExists ( 'LC_DATETIME_FORMAT' ) ) { $ localeTimestamp = $ dateTime -> getTimestamp ( ) ; if ( defined ( 'UTC_DATE' ) and UTC_DATE ) { $ localeTimestamp += $ dateTime -> getOffset ( ) ; } $ humanDate = strftime ( Translator :: do ( 'LC_DATETIME_FORMAT' ) , $ localeTimestamp ) ; } else { $ format = $ tran -> stringExists ( 'DATETIME_FORMAT' ) ? Translator :: do ( 'DATETIME_FORMAT' ) : 'Y-m-d H:i:s' ; $ humanDate = $ dateTime -> format ( $ format ) ; } return '<span class="timeago" title="' . $ dateTime -> format ( DATE_W3C ) . '">' . $ humanDate . '</span>' ; } else { return '<span class="timeago">' . Translator :: do ( 'NOT_AVAILABLE' ) . '</span>' ; } }
|
Will returns a div tag with timeago content .
|
47,622
|
public static function prependNullOption ( & $ list , $ idField = NULL , $ nameField = NULL , $ text = NULL ) { $ idField = $ idField ? $ idField : 'id' ; $ nameField = $ nameField ? $ nameField : 'name' ; $ text = $ text ? $ text : Translator :: do ( 'SELECT_NULL_VALUE' ) ; $ nullItem = new \ stdClass ( ) ; $ nullItem -> $ idField = '' ; $ nullItem -> $ nameField = $ text ; array_unshift ( $ list , $ nullItem ) ; return $ list ; }
|
Adds a NULL select field with translated text - Select - on top .
|
47,623
|
public static function uniqueFilename ( $ filename , $ path ) { self :: fixTrailingSlash ( $ path ) ; if ( file_exists ( $ path . $ filename ) ) { $ dot = strrpos ( $ filename , '.' ) ; $ ext = substr ( $ filename , $ dot ) ; $ name = substr ( $ filename , 0 , $ dot ) ; $ hash = substr ( md5 ( time ( ) ) , 0 , 6 ) ; $ filename = $ name . '-' . $ hash . $ ext ; } return $ filename ; }
|
Rename a file if another with same name exists adding hash of current date . It keep safe the filename extension .
|
47,624
|
public static function deleteFolder ( $ dir ) { if ( ! file_exists ( $ dir ) ) return true ; if ( ! is_dir ( $ dir ) or is_link ( $ dir ) ) return unlink ( $ dir ) ; foreach ( scandir ( $ dir ) as $ item ) { if ( $ item == '.' or $ item == '..' ) continue ; if ( ! self :: deleteFolder ( $ dir . "/" . $ item ) ) { chmod ( $ dir . "/" . $ item , 0777 ) ; if ( ! self :: deleteFolder ( $ dir . "/" . $ item ) ) return false ; } } return rmdir ( $ dir ) ; }
|
Deletes folder with all files and subfolders . Returns TRUE if deletion happens FALSE if folder or file is not found or in case of errors .
|
47,625
|
public static function getDatesFromRange ( $ sStartDate , $ sEndDate ) { $ aDays [ ] = $ sStartDate ; $ sCurrentDate = $ sStartDate ; while ( $ sCurrentDate < $ sEndDate ) { $ sCurrentDate = date ( "Y-m-d" , strtotime ( "+1 day" , strtotime ( $ sCurrentDate ) ) ) ; $ aDays [ ] = $ sCurrentDate ; } return $ aDays ; }
|
Returns list of dates based on date range
|
47,626
|
public static function getDateTimeFromRfc ( $ date ) { $ formats = array ( 'RFC2822' => \ DateTime :: RFC2822 , 'RFC2046' => 'D, d M Y H:i:s O T' , 'CUSTOM1' => 'D, j M Y H:i:s O' , 'CUSTOM2' => 'd M Y H:i:s O' , 'RSS2' => 'D, d M Y H:i:s T' ) ; foreach ( $ formats as $ format ) { $ datetime = \ DateTime :: createFromFormat ( $ format , $ date , new \ DateTimeZone ( BASE_TIMEZONE ) ) ; if ( is_a ( $ datetime , '\DateTime' ) ) { return $ datetime ; } } return NULL ; }
|
Converts string date coming by email in various RFC formats to DateTime . If fails or gets a date over current time sets as now .
|
47,627
|
public static function getCamelCase ( $ varName , $ capFirst = FALSE ) { $ camelCase = str_replace ( ' ' , '' , ucwords ( str_replace ( '_' , ' ' , $ varName ) ) ) ; if ( ! $ capFirst and strlen ( $ camelCase ) > 0 ) { $ camelCase [ 0 ] = lcfirst ( $ camelCase [ 0 ] ) ; } return $ camelCase ; }
|
Convert a snake case variable name into camel case .
|
47,628
|
private static function checkFileMime ( $ file , $ validMime ) { if ( ! function_exists ( 'mime_content_type' ) ) { $ app = Application :: getInstance ( ) ; $ app -> enqueueError ( 'The PHP extention mime_content_type is not installed' ) ; return NULL ; } $ pathParts = pathinfo ( $ file ) ; $ extension = $ pathParts [ 'extension' ] ; $ validMime = ( array ) $ validMime ; foreach ( $ validMime as $ item ) { if ( $ item == mime_content_type ( $ file ) ) { return TRUE ; } } return FALSE ; }
|
Check if passed file is one of passed MIME Content Type . NULL in case of MIME extension not installed .
|
47,629
|
public static function getActiveRecordClasses ( ) { $ classes = array ( ) ; $ checkFolder = function ( $ folder ) use ( & $ classes ) { if ( ! is_dir ( $ folder ) ) return ; $ files = array_diff ( scandir ( $ folder ) , array ( '..' , '.' , '.DS_Store' ) ) ; foreach ( $ files as $ file ) { if ( '.php' != substr ( $ file , - 4 ) ) continue ; include_once ( $ folder . '/' . $ file ) ; $ class = substr ( $ file , 0 , - 4 ) ; if ( PAIR_FOLDER == $ folder ) { $ class = 'Pair\\' . $ class ; $ pair = TRUE ; } else { $ pair = FALSE ; } if ( ! class_exists ( $ class ) ) continue ; $ reflection = new \ ReflectionClass ( $ class ) ; if ( is_subclass_of ( $ class , 'Pair\ActiveRecord' ) and ! $ reflection -> isAbstract ( ) ) { $ constructMethod = new \ ReflectionMethod ( $ class , '__construct' ) ; $ constructor = $ constructMethod -> isPublic ( ) ? TRUE : FALSE ; $ getInstance = method_exists ( $ class , 'getInstance' ) ; $ classes [ $ class ] = [ 'file' => $ file , 'folder' => $ folder , 'tableName' => $ class :: TABLE_NAME , 'constructor' => $ constructor , 'getInstance' => $ getInstance , 'pair' => $ pair ] ; } } } ; $ checkFolder ( PAIR_FOLDER ) ; $ checkFolder ( 'classes' ) ; $ modules = array_diff ( scandir ( 'modules' ) , array ( '..' , '.' , '.DS_Store' ) ) ; foreach ( $ modules as $ module ) { $ checkFolder ( 'modules/' . $ module . '/classes' ) ; } return $ classes ; }
|
Scan the whole system searching for ActiveRecord classes . These will be include_once .
|
47,630
|
public static function getRandomString ( int $ length ) : string { $ availableChars = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZ' ; return substr ( str_shuffle ( $ availableChars . $ availableChars ) , 0 , $ length ) ; }
|
Return a random alpha - numeric string of specified length .
|
47,631
|
private function parseCgiParameters ( ) { if ( FALSE === strpos ( $ this -> url , '?' ) ) { return ; } $ temp = explode ( '?' , $ this -> url ) ; $ this -> url = $ temp [ 0 ] ; if ( ! array_key_exists ( 1 , $ temp ) ) { return ; } $ couples = explode ( '&' , $ temp [ 1 ] ) ; foreach ( $ couples as $ c ) { $ var = explode ( '=' , $ c ) ; if ( array_key_exists ( 1 , $ var ) ) { list ( $ key , $ value ) = $ var ; $ this -> setParam ( $ key , $ value ) ; } } }
|
Checks if there are any GET vars in the URL adds these to object vars and removes from URL .
|
47,632
|
private function getParameters ( ) { $ url = '/' == $ this -> url { 0 } ? substr ( $ this -> url , 1 ) : $ this -> url ; $ params = explode ( '/' , $ url ) ; if ( array_key_exists ( 0 , $ params ) ) { switch ( $ params [ 0 ] ) { case 'ajax' : $ this -> ajax = $ this -> raw = TRUE ; array_shift ( $ params ) ; break ; case 'raw' : $ this -> raw = TRUE ; array_shift ( $ params ) ; break ; } } return $ params ; }
|
remove special prefixes and return parameters .
|
47,633
|
private function parseStandardRoute ( $ params ) { foreach ( $ params as $ pos => $ value ) { switch ( $ pos ) { case 0 : break ; case 1 : $ this -> action = urldecode ( $ value ) ; break ; default : $ param = urldecode ( $ value ) ; if ( 'noLog' == $ param ) { $ this -> sendLog = FALSE ; } else if ( 'order-' == substr ( $ param , 0 , 6 ) ) { $ nr = intval ( substr ( $ param , 6 ) ) ; if ( $ nr ) $ this -> order = $ nr ; } else if ( 'page-' == substr ( $ param , 0 , 5 ) ) { $ nr = intval ( substr ( $ param , 5 ) ) ; $ this -> setPage ( $ nr ) ; } else { if ( '' != $ param and ! is_null ( $ param ) ) { $ this -> vars [ ] = $ param ; } } break ; } } }
|
Populates router variables by standard parameter login .
|
47,634
|
public function setParam ( $ paramIdx = NULL , $ value , $ encode = FALSE ) { if ( $ encode ) { $ value = rtrim ( strtr ( base64_encode ( gzdeflate ( json_encode ( $ value ) , 9 ) ) , '+/' , '-_' ) , '=' ) ; } if ( ! is_null ( $ paramIdx ) ) { $ this -> vars [ $ paramIdx ] = $ value ; } else { $ this -> vars [ ] = $ value ; } }
|
Add a param value to the URL on index position if given and existent .
|
47,635
|
public function getPage ( ) { $ cookieName = Application :: getCookiePrefix ( ) . ucfirst ( $ this -> module ) . ucfirst ( $ this -> action ) ; if ( ! is_null ( $ this -> page ) ) { return ( ( int ) $ this -> page > 1 ? $ this -> page : 1 ) ; } else if ( isset ( $ _COOKIE [ $ cookieName ] ) and ( int ) $ _COOKIE [ $ cookieName ] > 0 ) { return ( int ) $ _COOKIE [ $ cookieName ] ; } else { return 1 ; } }
|
Return the current list page number .
|
47,636
|
public function setPage ( $ number ) { $ number = ( int ) $ number ; $ this -> page = $ number ; $ cookieName = Application :: getCookiePrefix ( ) . ucfirst ( $ this -> module ) . ucfirst ( $ this -> action ) ; setcookie ( $ cookieName , $ number , NULL , '/' ) ; }
|
Set a persistent state as current pagination index .
|
47,637
|
public function resetPage ( ) { $ this -> page = 1 ; $ cookieName = Application :: getCookiePrefix ( ) . ucfirst ( $ this -> module ) . ucfirst ( $ this -> action ) ; if ( isset ( $ _COOKIE [ $ cookieName ] ) ) { unset ( $ _COOKIE [ $ cookieName ] ) ; setcookie ( $ cookieName , '' , - 1 , '/' ) ; } }
|
Reset page number to 1 .
|
47,638
|
public static function addRoute ( $ path , $ action , $ module = NULL ) { $ route = new \ stdClass ( ) ; $ route -> path = $ path ; $ route -> action = $ action ; $ route -> module = $ module ; try { self :: $ instance -> routes [ ] = $ route ; } catch ( \ Exception $ e ) { die ( 'Router instance has not been created yet' ) ; } }
|
Add a new route path .
|
47,639
|
public function getUrl ( ) { $ sefParams = array ( ) ; $ cgiParams = array ( ) ; foreach ( $ this -> vars as $ key => $ val ) { if ( is_int ( $ key ) ) { $ sefParams [ ] = $ val ; } else { $ cgiParams [ $ key ] = $ val ; } } $ url = $ this -> module . '/' . $ this -> action ; if ( count ( $ sefParams ) ) { $ url .= '/' . implode ( '/' , $ sefParams ) ; } if ( $ this -> order ) { $ url .= '/order-' . $ this -> order ; } if ( $ this -> page ) { $ url .= '/page-' . $ this -> getPage ( ) ; } if ( count ( $ cgiParams ) ) { $ url .= '?' . http_build_query ( $ cgiParams ) ; } return $ url ; }
|
Returns current relative URL with order and optional pagination .
|
47,640
|
public function getOrderUrl ( $ val = NULL ) { $ tmp = $ this -> order ; $ this -> order = $ val ; $ url = $ this -> getUrl ( ) ; $ this -> order = $ tmp ; return $ url ; }
|
Proxy method to get the current URL with a different order value . If NULL param will reset ordering .
|
47,641
|
public function getPageUrl ( $ page = NULL ) { $ tmp = $ this -> page ; $ this -> page = ( int ) $ page ; $ url = $ this -> getUrl ( ) ; $ this -> page = $ tmp ; return $ url ; }
|
Special method to get the current URL with a different page number . If NULL param will reset pagination .
|
47,642
|
public static function exceedingPaginationFallback ( ) { $ self = static :: $ instance ; if ( ! $ self ) return NULL ; if ( $ self -> page > 1 ) { $ self -> resetPage ( ) ; $ app = Application :: getInstance ( ) ; $ app -> redirect ( $ self -> getUrl ( ) ) ; } }
|
If the page number is greater than 1 it returns the content to the first page . To be used when there are no data to display in the lists with pagination .
|
47,643
|
public function setLocale ( Locale $ newLocale ) { if ( ! $ this -> currentLocale or ( $ this -> currentLocale and $ newLocale -> id != $ this -> currentLocale -> id ) ) { $ this -> currentLocale = $ newLocale ; if ( $ this -> defaultLocale and $ newLocale -> id == $ this -> defaultLocale -> id ) { $ this -> strings = $ this -> defaultStrings ; $ this -> defaultStrings = NULL ; } else { $ this -> strings = NULL ; $ this -> loadStrings ( ) ; } } setlocale ( LC_ALL , str_replace ( '-' , '_' , $ newLocale -> getRepresentation ( ) ) . '.UTF-8' ) ; }
|
Set a new current locale by preparing its language strings .
|
47,644
|
private function checkLocaleSet ( ) { if ( ! $ this -> defaultLocale ) { $ locale = Locale :: getDefault ( ) ; $ this -> defaultLocale = $ locale ; setlocale ( LC_ALL , $ locale -> getRepresentation ( ) ) ; } if ( ! $ this -> currentLocale ) { $ this -> currentLocale = $ this -> defaultLocale ; if ( isset ( $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] ) ) { preg_match_all ( '/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?' . '(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i' , $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] , $ matches , PREG_SET_ORDER ) ; if ( ! isset ( $ matches [ 0 ] [ 1 ] ) or $ this -> currentLocale -> getLanguage ( ) -> code == $ matches [ 0 ] [ 1 ] ) { return ; } $ locale = Locale :: getDefaultByLanguage ( $ matches [ 0 ] [ 1 ] ) ; if ( ! $ locale ) { return ; } $ this -> setLocale ( $ locale ) ; } } }
|
Check that both default and current locales are set .
|
47,645
|
public function stringExists ( $ key ) { $ this -> loadStrings ( ) ; if ( array_key_exists ( $ key , $ this -> strings ) or array_key_exists ( $ key , $ this -> defaultStrings ) ) { return TRUE ; } else { return FALSE ; } }
|
Return TRUE if passed language is available for translation .
|
47,646
|
public function translateSelectOptions ( $ optSelect ) { $ this -> loadStrings ( ) ; foreach ( $ optSelect as $ value => $ text ) { if ( strtoupper ( $ text ) == $ text and strlen ( $ text ) > 3 ) { $ optSelect [ $ value ] = $ this -> get ( $ text ) ; } } return $ optSelect ; }
|
Translate the text in an array of select - options strings if uppercase .
|
47,647
|
public function translateActiveRecordList ( $ list , $ propertyName ) { if ( ! isset ( $ list [ 0 ] ) or ! property_exists ( $ list [ 0 ] , $ propertyName ) ) { return $ list ; } $ translatedVar = 'translated' . ucfirst ( $ propertyName ) ; foreach ( $ list as $ item ) { $ item -> $ translatedVar = $ this -> get ( $ item -> $ propertyName ) ; } return $ list ; }
|
Translate a list of ActiveRecord objects by specifing a property name .
|
47,648
|
public static function generateTable ( $ array , $ css = true ) { if ( ! isset ( $ array [ 0 ] ) ) { $ tmp = $ array ; $ array = array ( ) ; $ array [ 0 ] = $ tmp ; } if ( $ array [ 0 ] === null ) { return "NULL<br>" ; } if ( $ css === true ) { $ html = '<style>.generateTable { border-collapse: collapse; width: 100%; } .generateTable td, .generateTable th { border: 1px solid #ddd; padding: 8px; } .generateTable tr:nth-child(even){background-color: #f2f2f2;} .generateTable tr:hover {background-color: #ddd;} .generateTable th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4CAF50; color: white; } </style>' ; } else { $ html = '' ; } $ html .= '<table class="' . ( is_string ( $ css ) ? $ css : 'generateTable' ) . '">' ; $ html .= '<thead><tr >' ; if ( is_array ( $ array [ 0 ] ) ) { foreach ( $ array [ 0 ] as $ key => $ value ) { $ html .= '<th >' . htmlspecialchars ( $ key ) . '</th>' ; } } else { $ html .= '<th >Column</th>' ; } $ html .= '</tr></thead>' ; foreach ( $ array as $ key => $ value ) { $ html .= '<tr >' ; if ( is_array ( $ value ) ) { foreach ( $ value as $ key2 => $ value2 ) { $ html .= '<td >' . htmlspecialchars ( $ value2 ) . '</td>' ; } } else { $ html .= '<td >' . $ value . '</td>' ; } $ html .= '</tr>' ; } $ html .= '</table>' ; return $ html ; }
|
Generate a table from an array
|
47,649
|
public static function keepSnapshot ( $ description ) { $ app = Application :: getInstance ( ) ; $ router = Router :: getInstance ( ) ; $ snap = new self ( ) ; $ snap -> createdTime = new \ DateTime ( ) ; $ snap -> userId = $ app -> currentUser -> id ; $ snap -> module = $ router -> module ; $ snap -> action = $ router -> action ; $ snap -> getData = serialize ( $ _GET ) ; $ snap -> postData = serialize ( $ _POST ) ; $ snap -> cookieData = serialize ( $ _COOKIE ) ; $ snap -> description = $ description ; $ snap -> userMessages = serialize ( $ app -> messages ) ; if ( isset ( $ _SERVER [ 'HTTP_REFERER' ] ) ) { if ( 0 === strpos ( $ _SERVER [ 'HTTP_REFERER' ] , BASE_HREF ) ) { $ snap -> referer = substr ( $ _SERVER [ 'HTTP_REFERER' ] , strlen ( BASE_HREF ) ) ; } else { $ snap -> referer = $ _SERVER [ 'HTTP_REFERER' ] ; } } return $ snap -> create ( ) ; }
|
Allows to keep the current Application and browser state .
|
47,650
|
protected static function getBinds ( ) { $ db = Database :: getInstance ( ) ; $ columns = $ db -> describeTable ( static :: TABLE_NAME ) ; $ maps = [ ] ; foreach ( $ columns as $ col ) { $ property = lcfirst ( str_replace ( ' ' , '' , ucwords ( str_replace ( [ '_' , '\\' ] , ' ' , $ col -> Field ) ) ) ) ; $ maps [ $ property ] = $ col -> Field ; } return $ maps ; }
|
Returns array with matching object property name on related db fields .
|
47,651
|
final private function populate ( $ dbRow ) { $ this -> beforePopulate ( $ dbRow ) ; $ class = get_called_class ( ) ; $ varFields = $ class :: getBinds ( ) ; foreach ( $ varFields as $ objProperty => $ dbField ) { $ this -> __set ( $ objProperty , $ dbRow -> $ dbField ) ; } $ this -> afterPopulate ( ) ; }
|
Bind the object properties with all fields coming from database translating the field names into object properties names . DateTime Boolean and Integer will be properly managed .
|
47,652
|
final private function loadFromDb ( $ key ) { $ class = get_called_class ( ) ; $ where = ' WHERE ' . implode ( ' AND ' , $ this -> getSqlKeyConditions ( ) ) ; $ query = 'SELECT * FROM `' . $ class :: TABLE_NAME . '`' . $ where . ' LIMIT 1' ; $ this -> db -> setQuery ( $ query ) ; $ obj = $ this -> db -> loadObject ( $ key ) ; if ( is_object ( $ obj ) ) { $ this -> populate ( $ obj ) ; $ this -> loadedFromDb = TRUE ; } else { $ this -> loadedFromDb = FALSE ; } }
|
Load object from DB and bind with its properties . If DB record is not found unset any properties of inherited object but required props by ActiveRecord .
|
47,653
|
final public function reload ( ) { $ app = Application :: getInstance ( ) ; $ class = get_called_class ( ) ; $ propertiesToSave = array ( 'keyProperties' , 'db' , 'loadedFromDb' , 'typeList' , 'cache' , 'errors' ) ; $ propertiesToSave = array_merge ( $ propertiesToSave , $ this -> keyProperties ) ; foreach ( $ this as $ key => $ value ) { if ( ! in_array ( $ key , $ propertiesToSave ) ) { unset ( $ this -> $ key ) ; } } $ this -> cache = array ( ) ; $ this -> errors = array ( ) ; $ this -> loadFromDb ( $ this -> getSqlKeyValues ( ) ) ; $ app -> logEvent ( 'Reloaded ' . $ class . ' object with ' . $ this -> getKeyForEventlog ( ) ) ; }
|
Update this object from the current DB record with same primary key .
|
47,654
|
public function areKeysPopulated ( ) { $ populated = TRUE ; $ keys = ( array ) $ this -> getId ( ) ; if ( ! count ( $ keys ) ) return FALSE ; foreach ( $ keys as $ k ) { if ( ! $ k ) $ populated = FALSE ; } return $ populated ; }
|
Return TRUE if each key property has a value .
|
47,655
|
final private function getSqlKeyConditions ( ) { $ class = get_called_class ( ) ; $ tableKey = ( array ) $ class :: TABLE_KEY ; $ conds = array ( ) ; foreach ( $ tableKey as $ field ) { $ conds [ ] = $ this -> db -> escape ( $ field ) . ' = ?' ; } return $ conds ; }
|
Build a list of SQL conditions to select the current mapped object into DB .
|
47,656
|
final private function getSqlKeyValues ( ) { $ propertyNames = ( array ) $ this -> keyProperties ; $ values = array ( ) ; foreach ( $ propertyNames as $ name ) { $ values [ ] = $ this -> { $ name } ; } return $ values ; }
|
Return an indexed array with current table key values regardless of object properties value .
|
47,657
|
final private function getKeyForEventlog ( ) { $ properties = ( array ) $ this -> keyProperties ; $ keyParts = array ( ) ; foreach ( $ properties as $ propertyName ) { $ keyParts [ ] = $ propertyName . '=' . $ this -> $ propertyName ; } return implode ( ', ' , $ keyParts ) ; }
|
Return a list of primary or compound key of this object .
|
47,658
|
final public function update ( $ properties = NULL ) { $ this -> beforeUpdate ( ) ; $ app = Application :: getInstance ( ) ; $ class = get_called_class ( ) ; $ binds = static :: getBinds ( ) ; $ properties = ( array ) $ properties ; if ( ! count ( $ properties ) ) { $ properties = array_keys ( $ class :: getBinds ( ) ) ; } $ logParam = $ this -> getKeyForEventlog ( ) ; if ( $ this -> areKeysPopulated ( ) ) { $ dbObj = $ this -> prepareData ( $ properties ) ; $ key = ( array ) $ this -> keyProperties ; $ dbKey = new \ stdClass ( ) ; foreach ( $ key as $ k ) { $ dbKey -> { $ binds [ $ k ] } = $ this -> $ k ; } $ res = ( bool ) $ this -> db -> updateObject ( $ class :: TABLE_NAME , $ dbObj , $ dbKey ) ; $ app -> logEvent ( 'Updated ' . $ class . ' object with ' . $ logParam ) ; } else { $ res = FALSE ; $ app -> logError ( 'The ' . $ class . ' object with ' . $ logParam . ' cannot be updated' ) ; } $ this -> afterUpdate ( ) ; return $ res ; }
|
Store into db the current object properties with option to write only a subset of declared properties .
|
47,659
|
final public function updateNotNull ( ) { $ class = get_called_class ( ) ; $ binds = $ class :: getBinds ( ) ; $ properties = array ( ) ; foreach ( $ binds as $ objProp => $ dbField ) { if ( ! is_null ( $ this -> $ objProp ) ) { $ properties [ ] = $ objProp ; } } $ ret = $ this -> update ( $ properties ) ; return $ ret ; }
|
Store into db the current object properties avoiding null properties .
|
47,660
|
public function isReferenced ( ) { $ exists = FALSE ; $ references = $ this -> db -> getInverseForeignKeys ( static :: TABLE_NAME ) ; foreach ( $ references as $ r ) { $ property = array_search ( $ r -> REFERENCED_COLUMN_NAME , static :: getBinds ( ) ) ; $ query = 'SELECT COUNT(*)' . ' FROM `' . $ this -> db -> escape ( $ r -> TABLE_NAME ) . '`' . ' WHERE ' . $ this -> db -> escape ( $ r -> COLUMN_NAME ) . ' = ?' ; $ this -> db -> setQuery ( $ query ) ; $ count = $ this -> db -> loadCount ( $ this -> $ property ) ; if ( $ count ) $ exists = TRUE ; } return $ exists ; }
|
Check if this object has foreign keys that constraint it . Return TRUE in case of existing constraints .
|
47,661
|
final public function getRelated ( $ relatedProperty ) { $ cacheName = $ relatedProperty . 'RelatedObject' ; if ( $ this -> issetCache ( $ cacheName ) ) { return $ this -> getCache ( $ cacheName ) ; } $ foreignKeys = $ this -> db -> getForeignKeys ( static :: TABLE_NAME ) ; $ relatedField = $ this -> getMappedField ( $ relatedProperty ) ; $ referencedTable = NULL ; foreach ( $ foreignKeys as $ fk ) { if ( $ fk -> COLUMN_NAME == $ relatedField ) { $ referencedTable = $ fk -> REFERENCED_TABLE_NAME ; $ referencedColumn = $ fk -> REFERENCED_COLUMN_NAME ; break ; } } if ( ! $ referencedTable ) { $ this -> addError ( 'Property ' . $ relatedProperty . ' has not a foreign-key mapped into DB' ) ; return NULL ; } $ relatedClass = NULL ; $ loadedClasses = \ get_declared_classes ( ) ; foreach ( $ loadedClasses as $ c ) { if ( is_subclass_of ( $ c , 'Pair\ActiveRecord' ) and property_exists ( $ c , 'TABLE_NAME' ) and $ c :: TABLE_NAME == $ referencedTable ) { $ relatedClass = $ c ; break ; } } if ( ! $ relatedClass ) { $ classes = Utilities :: getActiveRecordClasses ( ) ; foreach ( $ classes as $ class => $ opts ) { if ( $ opts [ 'tableName' ] == $ referencedTable ) { include_once ( $ opts [ 'folder' ] . '/' . $ opts [ 'file' ] ) ; $ relatedClass = $ class ; break ; } } } if ( ! $ relatedClass ) { $ this -> addError ( 'Table ' . $ referencedTable . ' has not any Pair-class mapping' ) ; return NULL ; } $ obj = new $ relatedClass ( $ this -> $ relatedProperty ) ; $ ret = ( $ obj -> isLoaded ( ) ? $ obj : NULL ) ; $ this -> setCache ( $ cacheName , $ ret ) ; return $ ret ; }
|
Return the Pair \ ActiveRecord inherited object related to this by a ForeignKey in DB - table . Cached method .
|
47,662
|
final public function getRelatedProperty ( $ relatedProperty , $ wantedProperty ) { $ obj = $ this -> getRelated ( $ relatedProperty ) ; if ( $ obj ) { return $ obj -> $ wantedProperty ; } else { return NULL ; } }
|
Extended method to return a property value of the Pair \ ActiveRecord inherited object related to this by a ForeignKey in DB - table . Cached method .
|
47,663
|
final public static function isNullable ( $ fieldName ) { $ db = Database :: getInstance ( ) ; $ column = $ db -> describeColumn ( static :: TABLE_NAME , $ fieldName ) ; if ( is_null ( $ column ) ) { return NULL ; } return ( 'YES' == $ column -> Null ? TRUE : FALSE ) ; }
|
Check whether the DB - table - field is capable to store null values .
|
47,664
|
final public static function isEmptiable ( $ fieldName ) { $ column = static :: getColumnType ( $ fieldName ) ; if ( is_null ( $ column ) ) { return NULL ; } $ emptiables = [ 'CHAR' , 'VARCHAR' , 'TINYTEXT' , 'TEXT' , 'MEDIUMTEXT' , 'BIGTEXT' ] ; if ( in_array ( $ column -> type , $ emptiables ) or ( 'ENUM' == $ column -> type and in_array ( '' , $ column -> length ) ) ) { return TRUE ; } else { return FALSE ; } }
|
Check whether the DB - table - field is capable to store empty strings .
|
47,665
|
public function isDeletable ( ) { $ inverseForeignKeys = $ this -> db -> getInverseForeignKeys ( static :: TABLE_NAME ) ; foreach ( $ inverseForeignKeys as $ r ) { if ( 'RESTRICT' != $ r -> DELETE_RULE ) continue ; $ propertyName = $ this -> getMappedProperty ( $ r -> REFERENCED_COLUMN_NAME ) ; return ! $ this -> checkRecordExists ( $ r -> TABLE_NAME , $ r -> COLUMN_NAME , $ this -> $ propertyName ) ; } return TRUE ; }
|
Check whether record of this object is deletable based on inverse foreign - key list .
|
47,666
|
private function checkRecordExists ( $ table , $ column , $ value ) { if ( ! $ value ) { return FALSE ; } $ query = 'SELECT COUNT(1) FROM `' . $ table . '` WHERE ' . $ column . ' = ?' ; return ( bool ) Database :: load ( $ query , ( array ) $ value , 'count' ) ; }
|
Check if a record with column = value exists .
|
47,667
|
final private function setDatetimeProperty ( $ propertyName , $ value ) { $ app = Application :: getInstance ( ) ; if ( is_a ( $ app -> currentUser , 'User' ) ) { $ dtz = $ app -> currentUser -> getDateTimeZone ( ) ; } else { $ dtz = new \ DateTimeZone ( BASE_TIMEZONE ) ; } if ( defined ( 'UTC_DATE' ) and UTC_DATE and ( is_int ( $ value ) or ctype_digit ( $ value ) ) ) { $ this -> $ propertyName = new \ DateTime ( '@' . ( int ) $ value ) ; $ this -> $ propertyName -> setTimezone ( $ dtz ) ; } else if ( is_string ( $ value ) ) { if ( in_array ( $ value , [ '0000-00-00 00:00:00' , '0000-00-00' , '' ] ) ) { $ this -> $ propertyName = NULL ; } else { try { $ this -> $ propertyName = new \ DateTime ( $ value , $ dtz ) ; } catch ( \ Exception $ e ) { $ this -> $ propertyName = NULL ; $ this -> addError ( $ e -> getMessage ( ) ) ; } } } else if ( is_a ( $ value , 'DateTime' ) ) { $ value -> setTimeZone ( $ dtz ) ; $ this -> $ propertyName = $ value ; } else { $ this -> $ propertyName = NULL ; } }
|
This method will populates a Datetime property with strings or DateTime obj . It will also sets time zone for all created datetimes with daylight saving value . Integer timestamps are only managed as UTC .
|
47,668
|
final public function existsInDb ( ) { $ class = get_called_class ( ) ; $ conds = implode ( ' AND ' , $ this -> getSqlKeyConditions ( ) ) ; $ this -> db -> setQuery ( 'SELECT COUNT(1) FROM `' . $ class :: TABLE_NAME . '` WHERE ' . $ conds ) ; return ( bool ) $ this -> db -> loadCount ( $ this -> getId ( ) ) ; }
|
Check if this object still exists in DB as record . Return TRUE if exists .
|
47,669
|
public static function getLast ( ) { $ class = get_called_class ( ) ; if ( $ class :: hasCompoundKey ( ) ) { return NULL ; } $ db = Database :: getInstance ( ) ; if ( ! $ db -> isAutoIncrement ( $ class :: TABLE_NAME ) ) { return NULL ; } $ tableKey = ( is_array ( $ class :: TABLE_KEY ) and array_key_exists ( 0 , $ class :: TABLE_KEY ) ) ? $ class :: TABLE_KEY [ 0 ] : $ class :: TABLE_KEY ; $ db -> setQuery ( 'SELECT * FROM `' . $ class :: TABLE_NAME . '` ORDER BY `' . $ tableKey . '` DESC LIMIT 1' ) ; $ obj = $ db -> loadObject ( ) ; return ( is_a ( $ obj , 'stdClass' ) ? new $ class ( $ obj ) : NULL ) ; }
|
Return last insert record object for single auto - increment primary key .
|
47,670
|
final public static function getObjectByQuery ( $ query , $ params = [ ] ) { $ app = Application :: getInstance ( ) ; $ db = Database :: getInstance ( ) ; $ class = get_called_class ( ) ; $ db -> setQuery ( $ query ) ; $ row = $ db -> loadObject ( $ params ) ; $ customBinds = [ ] ; if ( ! is_a ( $ row , 'stdClass' ) ) { return NULL ; } $ binds = $ class :: getBinds ( ) ; $ fields = get_object_vars ( $ row ) ; foreach ( $ fields as $ field => $ value ) { if ( ! array_search ( $ field , $ binds ) ) { $ customBinds [ Utilities :: getCamelCase ( $ field ) ] = $ field ; } } $ object = new $ class ( $ row ) ; foreach ( $ customBinds as $ customProp => $ customField ) { $ object -> $ customProp = $ row -> $ customField ; } $ object -> loadedFromDb = TRUE ; $ app -> logEvent ( 'Loaded a ' . $ class . ' object' . ( count ( $ customBinds ) ? ' with custom fields ' . implode ( ',' , $ customBinds ) : '' ) ) ; return $ object ; }
|
Get one object of inherited class as result of the query run .
|
47,671
|
final public static function getObjectsByQuery ( $ query , $ params = [ ] ) { $ app = Application :: getInstance ( ) ; $ db = Database :: getInstance ( ) ; $ class = get_called_class ( ) ; $ db -> setQuery ( $ query ) ; $ list = $ db -> loadObjectList ( $ params ) ; $ objects = [ ] ; $ customBinds = [ ] ; if ( is_array ( $ list ) and isset ( $ list [ 0 ] ) ) { $ binds = $ class :: getBinds ( ) ; $ fields = get_object_vars ( $ list [ 0 ] ) ; foreach ( $ fields as $ field => $ value ) { if ( ! array_search ( $ field , $ binds ) ) { $ customBinds [ Utilities :: getCamelCase ( $ field ) ] = $ field ; } } foreach ( $ list as $ row ) { $ object = new $ class ( $ row ) ; foreach ( $ customBinds as $ customProp => $ customField ) { $ object -> $ customProp = $ row -> $ customField ; } $ object -> loadedFromDb = TRUE ; $ objects [ ] = $ object ; } } $ app -> logEvent ( 'Loaded ' . count ( $ objects ) . ' ' . $ class . ' objects with custom fields ' . implode ( ',' , $ customBinds ) ) ; return $ objects ; }
|
Get all objects of inherited class as result of the query run .
|
47,672
|
final public static function exists ( $ keys ) : bool { $ db = Database :: getInstance ( ) ; $ tableKey = ( array ) static :: TABLE_KEY ; $ conds = array ( ) ; foreach ( $ tableKey as $ field ) { $ conds [ ] = $ field . ' = ?' ; } $ query = 'SELECT COUNT(1) FROM `' . static :: TABLE_NAME . '` WHERE ' . implode ( ' AND ' , $ conds ) ; return ( bool ) Database :: load ( $ query , ( array ) $ keys , PAIR_DB_COUNT ) ; }
|
Return TRUE if db record with passed primary or compound key exists . Faster method .
|
47,673
|
final public function getCache ( $ name ) { return ( ( is_array ( $ this -> cache ) and array_key_exists ( $ name , $ this -> cache ) ) ? $ this -> cache [ $ name ] : NULL ) ; }
|
Returns a variable NULL in case of variable not found .
|
47,674
|
final public function unsetCache ( $ name ) { if ( is_array ( $ this -> cache ) and isset ( $ this -> cache [ $ name ] ) ) { unset ( $ this -> cache [ $ name ] ) ; } }
|
Reset a cache variable by its name .
|
47,675
|
final public function formatDateTime ( $ prop , $ format = NULL ) { if ( ! is_a ( $ this -> $ prop , 'DateTime' ) ) { return NULL ; } $ app = Application :: getInstance ( ) ; if ( is_a ( $ app -> currentUser , 'User' ) ) { $ dtz = $ app -> currentUser -> getDateTimeZone ( ) ; } else { $ dtz = new \ DateTimeZone ( BASE_TIMEZONE ) ; } $ this -> $ prop -> setTimeZone ( $ dtz ) ; if ( ! $ format ) { $ tran = Translator :: getInstance ( ) ; if ( $ tran -> stringExists ( 'LC_DATETIME_FORMAT' ) ) { return strftime ( Translator :: do ( 'LC_DATETIME_FORMAT' ) , $ this -> $ prop -> getTimestamp ( ) ) ; } else { $ format = $ tran -> stringExists ( 'DATETIME_FORMAT' ) ? Translator :: do ( 'DATETIME_FORMAT' ) : 'Y-m-d H:i:s' ; } } return $ this -> $ prop -> format ( $ format ) ; }
|
Safely formats and returns a DateTime if valid . If language string LC_DATETIME_FORMAT is set a locale translated date is returned .
|
47,676
|
final static public function getMappedProperty ( $ fieldName ) { $ binds = static :: getBinds ( ) ; return in_array ( $ fieldName , $ binds ) ? array_search ( $ fieldName , $ binds ) : NULL ; }
|
Get the name of class property mapped by db field . NULL if not found .
|
47,677
|
final static public function getMappedField ( $ propertyName ) { $ binds = static :: getBinds ( ) ; return isset ( $ binds [ $ propertyName ] ) ? $ binds [ $ propertyName ] : NULL ; }
|
Get the name of db field mapped by a class property . NULL if not found .
|
47,678
|
final public function getObjectByCachedList ( $ class , $ property , $ value ) { $ app = Application :: getInstance ( ) ; $ cacheName = $ class . 'ObjectList' ; if ( ! $ app -> issetState ( $ cacheName ) ) { $ app -> setState ( $ cacheName , $ class :: getAllObjects ( ) ) ; } foreach ( $ app -> getState ( $ cacheName ) as $ object ) { if ( $ object -> $ property == $ value ) { return $ object ; } } return NULL ; }
|
Load all records in a table from the DB and store them in the Application cache then look for the required property in this list . It is very useful for repeated searches on small tables of the DB eg . less than 1000 records .
|
47,679
|
final public function populateByRequest ( ) { $ args = func_get_args ( ) ; $ binds = static :: getBinds ( ) ; foreach ( $ binds as $ property => $ field ) { if ( ! count ( $ args ) or ( isset ( $ args [ 0 ] ) and in_array ( $ property , $ args [ 0 ] ) ) ) { $ type = $ this -> getPropertyType ( $ property ) ; if ( Input :: isSent ( $ property ) or 'bool' == $ type ) { $ this -> __set ( $ property , Input :: get ( $ property ) ) ; } } } }
|
Populates the inherited object with input vars with same name as properties .
|
47,680
|
final public function getId ( ) { $ ids = array ( ) ; foreach ( $ this -> keyProperties as $ propertyName ) { $ ids [ ] = $ this -> { $ propertyName } ; } return ( static :: hasCompoundKey ( ) ? $ ids : $ ids [ 0 ] ) ; }
|
Returns unique ID of inherited object or in case of compound key an indexed array .
|
47,681
|
public function jsonSerialize ( ) { $ vars = get_object_vars ( $ this ) ; unset ( $ vars [ 'keyProperties' ] ) ; unset ( $ vars [ 'db' ] ) ; unset ( $ vars [ 'loadedFromDb' ] ) ; unset ( $ vars [ 'typeList' ] ) ; unset ( $ vars [ 'cache' ] ) ; unset ( $ vars [ 'errors' ] ) ; return $ vars ; }
|
Function for serializing the object through json response .
|
47,682
|
protected function afterCreate ( ) { $ this -> unsetSiblingsDefaults ( ) ; $ defaultRuleId = $ this -> getDefaultModule ( ) ; if ( $ defaultRuleId ) { $ acl = new Acl ( ) ; $ acl -> ruleId = $ defaultRuleId ; $ acl -> groupId = $ this -> id ; $ acl -> default = TRUE ; $ acl -> create ( ) ; } }
|
If default is TRUE will set other groups to zero . Insert default Module as ACL default module when create a Group .
|
47,683
|
protected function beforeDelete ( ) { $ acls = Acl :: getAllObjects ( array ( 'groupId' => $ this -> id ) ) ; foreach ( $ acls as $ acl ) { $ acl -> delete ( ) ; } $ users = User :: getAllObjects ( array ( 'groupId' => $ this -> id ) ) ; foreach ( $ users as $ user ) { $ user -> delete ( ) ; } }
|
Deletes all Acl and User objects of this Group .
|
47,684
|
public function getUsers ( ) { $ this -> db -> setQuery ( 'SELECT * FROM `users` WHERE group_id=?' ) ; $ list = $ this -> db -> loadObjectList ( $ this -> id ) ; $ users = array ( ) ; $ userClass = PAIR_USER_CLASS ; foreach ( $ list as $ row ) { $ users [ ] = new $ userClass ( $ row ) ; } return $ users ; }
|
Returns list of User objects of this Group .
|
47,685
|
public function setDefaultAcl ( $ aclId ) { Database :: run ( 'UPDATE `acl` SET `is_default` = 0 WHERE `group_id` = ? AND `id` <> ?' , [ $ this -> id , $ aclId ] ) ; Database :: run ( 'UPDATE `acl` SET `is_default` = 1 WHERE `group_id` = ? AND `id` = ?' , [ $ this -> id , $ aclId ] ) ; }
|
Set a default Acl of this group .
|
47,686
|
public function getModuleName ( ) { $ query = ' SELECT m.name' . ' FROM `rules` as r ' . ' INNER JOIN `modules` as m ON m.id = r.module_id' . ' WHERE r.id = ?' ; $ this -> db -> setQuery ( $ query ) ; $ name = $ this -> db -> loadResult ( $ this -> ruleId ) ; return $ name ; }
|
Returns module name for this ACL .
|
47,687
|
public function getPlugin ( ) { $ folder = $ this -> getBaseFolder ( ) . '/' . strtolower ( str_replace ( array ( ' ' , '_' ) , '' , $ this -> name ) ) ; $ dateReleased = $ this -> dateReleased -> format ( 'Y-m-d' ) ; $ options = [ 'derived' => ( string ) \ intval ( $ this -> derived ) , 'palette' => implode ( ',' , $ this -> palette ) ] ; $ plugin = new Plugin ( 'Template' , $ this -> name , $ this -> version , $ dateReleased , $ this -> appVersion , $ folder , $ options ) ; return $ plugin ; }
|
Creates and returns the Plugin object of this Template object .
|
47,688
|
public function storeByPlugin ( \ SimpleXMLElement $ options ) { $ children = $ options -> children ( ) ; $ this -> derived = ( bool ) $ children -> derived ; foreach ( $ children -> palette -> children ( ) as $ color ) { $ this -> palette [ ] = ( string ) $ color ; } return $ this -> store ( ) ; }
|
Get option parameters and store this object loaded by a Plugin .
|
47,689
|
public static function getPluginByName ( $ name ) { $ db = Database :: getInstance ( ) ; $ db -> setQuery ( 'SELECT * FROM `templates` WHERE name=?' ) ; $ obj = $ db -> loadObject ( $ name ) ; return ( is_a ( $ obj , 'stdClass' ) ? new Template ( $ obj ) : NULL ) ; }
|
Load and return a Template object by its name .
|
47,690
|
public function render ( $ name ) { $ logger = Logger :: getInstance ( ) ; $ logger -> addEvent ( 'Rendering ' . $ name . ' widget' ) ; $ file = $ this -> scriptPath . $ name . '.php' ; ob_start ( ) ; $ script = require $ file ; $ widget = ob_get_clean ( ) ; return $ widget ; }
|
Renders the widget layout and returns it .
|
47,691
|
public static function pluginExists ( $ name ) { $ db = Database :: getInstance ( ) ; $ db -> setQuery ( 'SELECT COUNT(1) FROM `modules` WHERE name = ?' ) ; return ( bool ) $ db -> loadCount ( $ name ) ; }
|
Checks if Module is already installed in this application .
|
47,692
|
public function getPlugin ( ) { $ folder = $ this -> getBaseFolder ( ) . '/' . strtolower ( str_replace ( array ( ' ' , '_' ) , '' , $ this -> name ) ) ; $ dateReleased = $ this -> dateReleased -> format ( 'Y-m-d' ) ; $ plugin = new Plugin ( 'Module' , $ this -> name , $ this -> version , $ dateReleased , $ this -> appVersion , $ folder ) ; return $ plugin ; }
|
Creates and returns the Plugin object of this Module object .
|
47,693
|
public static function getByName ( $ name ) { $ db = Database :: getInstance ( ) ; $ db -> setQuery ( 'SELECT * FROM `modules` WHERE name = ?' ) ; return $ db -> loadObject ( $ name ) ; }
|
Return an installed Module of this application .
|
47,694
|
private function getMime ( $ file ) { $ info = new \ stdClass ; $ audio = array ( 'audio/basic' , 'audio/mpeg' ) ; $ docs = array ( 'text/plain' , 'application/pdf' , 'application/msword' , 'application/vnd.ms-excel' , 'application/vnd.ms-powerpoint' ) ; $ flash = array ( 'application/x-shockwave-flash' ) ; $ images = array ( 'image/gif' , 'image/jpeg' , 'image/png' , 'image/svg+xml' , 'image/tiff' ) ; $ movies = array ( 'video/mpeg' , 'video/mp4' , 'video/quicktime' , 'video/webm' , 'video/x-flv' , 'video/x-msvideo' , 'video/x-ms-asf' ) ; $ zip = array ( 'application/zip' ) ; if ( function_exists ( 'mime_content_type' ) ) { $ info -> mime = mime_content_type ( $ file ) ; } else if ( extension_loaded ( 'fileinfo' ) or dl ( 'fileinfo.so' ) ) { $ const = defined ( 'FILEINFO_MIME_TYPE' ) ? FILEINFO_MIME_TYPE : FILEINFO_MIME ; $ finfo = finfo_open ( $ const ) ; $ info -> mime = finfo_file ( $ finfo , $ file ) ; finfo_close ( $ finfo ) ; } else { $ this -> setError ( 'No extensions available for this file' ) ; $ info -> mime = NULL ; $ info -> type = NULL ; return $ info ; } if ( in_array ( $ info -> mime , $ docs ) ) { $ info -> type = 'document' ; } else if ( in_array ( $ info -> mime , $ movies ) ) { $ info -> type = 'movie' ; } else if ( in_array ( $ info -> mime , $ images ) ) { $ info -> type = 'image' ; } else if ( in_array ( $ info -> mime , $ flash ) ) { $ info -> type = 'flash' ; } else if ( in_array ( $ info -> mime , $ audio ) ) { $ info -> type = 'audio' ; } else if ( in_array ( $ info -> mime , $ zip ) ) { $ info -> type = 'zip' ; } else { $ info -> type = 'unknown' ; } return $ info ; }
|
Will returns Mime and Type for the file as parameter .
|
47,695
|
public static function getUploadProgress ( $ uniqueId ) { $ upload = apc_fetch ( 'upload_' . $ uniqueId ) ; if ( $ upload [ 'done' ] ) { $ percent = 100 ; } else if ( 0 == $ upload [ 'total' ] ) { $ percent = 0 ; } else { $ percent = round ( ( $ upload [ 'current' ] / $ upload [ 'total' ] * 100 ) , 0 ) ; } return $ percent ; }
|
Will returns percentual of upload progress with APC .
|
47,696
|
private function setError ( $ error ) { $ this -> errors [ ] = $ error ; $ app = Application :: getInstance ( ) ; $ app -> logError ( $ error ) ; }
|
Will sets an error on queue of main Application singleton object .
|
47,697
|
final public function enqueueMessage ( $ text , $ title = '' , $ type = NULL ) { $ this -> app -> enqueueMessage ( $ text , $ title , $ type ) ; }
|
Proxy to append a text message to queue .
|
47,698
|
public function getView ( ) { try { if ( $ this -> view ) { $ file = $ this -> modulePath . '/view' . ucfirst ( $ this -> view ) . '.php' ; if ( ! file_exists ( $ file ) ) { if ( $ this -> app -> currentUser -> areKeysPopulated ( ) ) { throw new \ Exception ( 'View file ' . $ file . ' has not been found' ) ; } else { die ( 'Access denied' ) ; } } include_once ( $ file ) ; $ viewName = ucfirst ( $ this -> name ) . 'View' . ucfirst ( $ this -> view ) ; if ( ! class_exists ( $ viewName ) ) { throw new \ Exception ( 'Class ' . $ viewName . ' was not found in file ' . $ file ) ; } return new $ viewName ( ) ; } else { throw new \ Exception ( 'No view file has been set' ) ; } } catch ( \ Exception $ e ) { $ this -> app -> logError ( $ e -> getMessage ( ) ) ; $ url = ! isset ( $ _SERVER [ 'REFERER' ] ) ? $ _SERVER [ 'REFERER' ] : BASE_HREF ; $ this -> redirect ( $ url , TRUE ) ; } return NULL ; }
|
Return View object related to this controller .
|
47,699
|
public function display ( ) { $ view = $ this -> getView ( ) ; if ( is_subclass_of ( $ view , 'Pair\View' ) ) { $ view -> display ( ) ; } else { if ( ! $ this -> router -> isRaw ( ) ) { $ this -> enqueueError ( $ this -> translator -> get ( 'RESOURCE_NOT_FOUND' , $ this -> router -> module . '/' . $ this -> router -> action ) ) ; } $ this -> redirect ( $ this -> router -> module ) ; } }
|
Include the file for View formatting . Display an error message and redirect to default view as fallback in case of view not found for non - ajax requests .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.