idx int64 0 60.3k | question stringlengths 101 6.21k | target stringlengths 7 803 |
|---|---|---|
13,900 | public static function glob_to_regex ( $ glob ) { $ first_byte = true ; $ escaping = false ; $ in_curlies = 0 ; $ regex = '' ; for ( $ i = 0 ; $ i < strlen ( $ glob ) ; $ i ++ ) { $ car = $ glob [ $ i ] ; if ( $ first_byte ) { if ( self :: $ strict_leading_dot && $ car != '.' ) { $ regex .= '(?=[^\.])' ; } $ first_byte = false ; } if ( $ car == '/' ) { $ first_byte = true ; } if ( $ car == '.' || $ car == '(' || $ car == ')' || $ car == '|' || $ car == '+' || $ car == '^' || $ car == '$' ) { $ regex .= "\\$car" ; } else if ( $ car == '*' ) { $ regex .= ( $ escaping ? "\\*" : ( self :: $ strict_wildcard_slash ? "[^/]*" : ".*" ) ) ; } else if ( $ car == '?' ) { $ regex .= ( $ escaping ? "\\?" : ( self :: $ strict_wildcard_slash ? "[^/]" : "." ) ) ; } else if ( $ car == '{' ) { $ regex .= ( $ escaping ? "\\{" : "(" ) ; if ( ! $ escaping ) ++ $ in_curlies ; } else if ( $ car == '}' && $ in_curlies ) { $ regex .= ( $ escaping ? "}" : ")" ) ; if ( ! $ escaping ) -- $ in_curlies ; } else if ( $ car == ',' && $ in_curlies ) { $ regex .= ( $ escaping ? "," : "|" ) ; } else if ( $ car == "\\" ) { if ( $ escaping ) { $ regex .= "\\\\" ; $ escaping = false ; } else { $ escaping = true ; } continue ; } else { $ regex .= $ car ; $ escaping = false ; } $ escaping = false ; } return "#^$regex$#" ; } | Returns a compiled regex which is the equiavlent of the globbing pattern . |
13,901 | public function call ( $ name , array $ params = [ ] ) { $ this -> checkName ( $ name ) ; array_unshift ( $ params , $ this ) ; call_user_func_array ( $ this -> callbacks [ $ name ] , $ params ) ; return $ this ; } | Call breadcrumb . |
13,902 | public function push ( $ title , $ url = null , array $ data = [ ] ) { $ this -> breadcrumbs -> addOne ( $ title , $ url , $ data ) ; return $ this ; } | Push a breadcrumb . |
13,903 | protected function handle ( $ signal , $ handler , $ placement ) { declare ( ticks = 1 ) ; $ signalNumber = $ this -> translateSignal ( $ signal ) ; if ( is_int ( $ handler ) && in_array ( $ handler , [ SIG_IGN , SIG_DFL ] ) ) { unset ( $ this -> handlers [ $ signalNumber ] ) ; $ this -> registerHandler ( $ signalNumber , $ handler ) ; return ; } $ this -> placeHandler ( $ signalNumber , $ handler , $ placement ) ; } | Define a handler for the given signal . |
13,904 | protected function placeHandler ( $ signalNumber , callable $ handler , $ placement ) { if ( ! isset ( $ this -> handlers [ $ signalNumber ] ) ) { $ this -> handlers [ $ signalNumber ] = [ ] ; $ this -> registerHandler ( $ signalNumber , $ this ) ; } switch ( $ placement ) { case 'set' : $ this -> handlers [ $ signalNumber ] = [ $ handler ] ; break ; case 'append' : array_push ( $ this -> handlers [ $ signalNumber ] , $ handler ) ; break ; case 'prepend' : array_unshift ( $ this -> handlers [ $ signalNumber ] , $ handler ) ; break ; } } | Define a callback handler for the given signal . |
13,905 | public function getHandlers ( $ signal ) { $ signalNumber = $ this -> translateSignal ( $ signal ) ; $ handlers = [ ] ; if ( isset ( $ this -> handlers [ $ signalNumber ] ) ) { $ handlers = $ this -> handlers [ $ signalNumber ] ; } return $ handlers ; } | Returns handlers of a specific signal . |
13,906 | public function send ( $ signal , $ processId = null ) { if ( null === $ processId ) { $ processId = posix_getpid ( ) ; } return posix_kill ( $ processId , $ this -> translateSignal ( $ signal ) ) ; } | Send a signal to a process . |
13,907 | protected function translateSignal ( $ signal ) { if ( isset ( $ this -> signals [ $ signal ] ) ) { $ signal = $ this -> signals [ $ signal ] ; } elseif ( defined ( $ signal ) ) { $ signal = constant ( $ signal ) ; } if ( ! is_int ( $ signal ) ) { throw new InvalidArgumentException ( 'The given value is not a valid signal' ) ; } return $ signal ; } | Translate signals names to codes . |
13,908 | public function createHandlerByConfig ( ) : \ SessionHandlerInterface { if ( ! isset ( $ this -> getConfig ( ) [ 'driver' ] ) ) { throw new \ InvalidArgumentException ( 'Session driver required' ) ; } $ handler = $ this -> getHandler ( $ this -> getConfig ( ) [ 'driver' ] ) ; $ handler instanceof LifetimeInterface && $ handler -> setLifetime ( $ this -> getConfig ( ) [ 'lifetime' ] ) ; return $ handler ; } | Create a handler by config |
13,909 | public function getHandler ( string $ name ) : \ SessionHandlerInterface { $ name = strtolower ( $ name ) ; $ this -> isValidate ( $ name ) ; return App :: getBean ( $ this -> handlers [ $ name ] ) ; } | Get a handler by name |
13,910 | private function buildContainer ( InputInterface $ input , OutputInterface $ output ) { $ nonContainerCommands = [ 'blocks-install' , 'blocks-update' , 'blocks-dumpautoload' , 'help' ] ; if ( in_array ( $ input -> getFirstArgument ( ) , $ nonContainerCommands ) ) { return ; } $ this -> container = new ContainerBuilder ( $ this , $ input , $ output ) ; $ this -> container -> compile ( ) ; } | Builds the container with extensions |
13,911 | public function find ( $ name ) { try { return parent :: find ( $ name ) ; } catch ( \ InvalidArgumentException $ e ) { $ this -> shortcut = true ; return parent :: find ( 'run' ) ; } } | Falls back to run for a shortcut |
13,912 | private function getJobs ( ) { if ( $ this -> hasParameter ( 'profile' ) ) { $ this -> fetchJobs ( $ this -> getParameter ( 'profile' ) ) ; return ; } $ this -> buildJobs ( [ $ this -> getParameter ( 'job' ) ] ) ; } | Fetches the tasks for either the profile or the passed task |
13,913 | public function setEnd ( $ end , $ write = true ) { $ e = $ this ; if ( $ e -> TimeFrameType == 'DateTime' ) { $ e -> EndDateTime = $ end ; } elseif ( $ e -> TimeFrameType == 'Duration' ) { $ duration = $ this -> calcDurationBasedOnEndDateTime ( $ end ) ; if ( $ duration ) { $ e -> Duration = $ duration ; } else { $ e -> TimeFrameType = 'DateTime' ; $ e -> EndDateTime = $ end ; } } if ( $ write ) { $ e -> write ( ) ; } } | Set new end date |
13,914 | public function calcEndDateTimeBasedOnDuration ( ) { $ duration = $ this -> Duration ; $ secs = ( substr ( $ duration , 0 , 2 ) * 3600 ) + ( substr ( $ duration , 3 , 2 ) * 60 ) ; $ startDate = strtotime ( $ this -> StartDateTime ) ; $ endDate = $ startDate + $ secs ; $ formatDate = date ( "Y-m-d H:i:s" , $ endDate ) ; return $ formatDate ; } | Calculation of end date based on duration Should only be used in OnBeforeWrite |
13,915 | public function calcDurationBasedOnEndDateTime ( $ end ) { $ startDate = strtotime ( $ this -> StartDateTime ) ; $ endDate = strtotime ( $ end ) ; $ duration = $ endDate - $ startDate ; $ secsInDay = 60 * 60 * 24 ; if ( $ duration > $ secsInDay ) { return false ; } $ formatDate = gmdate ( "H:i" , $ duration ) ; return $ formatDate ; } | Calculation of duration based on end datetime Returns false if there s more than 24h between start and end date |
13,916 | public function isAllDay ( ) { if ( $ this -> AllDay ) { return true ; } $ secsInDay = 60 * 60 * 24 ; $ startTime = strtotime ( $ this -> StartDateTime ) ; $ endTime = strtotime ( $ this -> EndDateTime ) ; if ( ( $ endTime - $ startTime ) > $ secsInDay ) { return true ; } } | All Day getter Any events that spans more than 24h will be displayed as allday events Beyond that those events marked as all day events will also be displayed as such |
13,917 | public function getFrontEndFields ( $ params = null ) { $ timeFrameHeaderText = 'Time Frame' ; if ( ! CalendarConfig :: subpackage_setting ( 'events' , 'force_end' ) ) { $ timeFrameHeaderText = 'End Date / Time (optional)' ; } $ fields = FieldList :: create ( TextField :: create ( 'Title' ) -> setAttribute ( 'placeholder' , 'Enter a title' ) , CheckboxField :: create ( 'AllDay' , 'All-day' ) , $ startDateTime = DatetimeField :: create ( 'StartDateTime' , 'Start' ) , CheckboxField :: create ( 'NoEnd' , 'Open End' ) , HeaderField :: create ( 'TimeFrameHeader' , $ timeFrameHeaderText , 5 ) , SelectionGroup :: create ( 'TimeFrameType' , array ( "Duration//Duration" => TimeField :: create ( 'Duration' , '' ) -> setRightTitle ( 'up to 24h' ) -> setAttribute ( 'placeholder' , 'Enter duration' ) , "DateTime//Date/Time" => $ endDateTime = DateTimeField :: create ( 'EndDateTime' , '' ) ) ) , LiteralField :: create ( 'Clear' , '<div class="clear"></div>' ) ) ; $ timeExpl = 'Time, e.g. 11:15am or 15:30' ; $ startDateTime -> getDateField ( ) -> setConfig ( 'showcalendar' , 1 ) -> setAttribute ( 'placeholder' , 'Enter date' ) -> setAttribute ( 'readonly' , 'true' ) ; $ startDateTime -> getTimeField ( ) -> setConfig ( 'timeformat' , 'HH:mm' ) -> setAttribute ( 'placeholder' , 'Enter time' ) ; $ endDateTime -> getDateField ( ) -> setConfig ( 'showcalendar' , 1 ) -> setAttribute ( 'placeholder' , 'Enter date' ) -> setAttribute ( 'readonly' , 'true' ) ; $ endDateTime -> getTimeField ( ) -> setConfig ( 'timeformat' , 'HH:mm' ) -> setAttribute ( 'placeholder' , 'Enter time' ) ; if ( ! CalendarConfig :: subpackage_setting ( 'events' , 'enable_allday_events' ) ) { $ fields -> removeByName ( 'AllDay' ) ; } if ( CalendarConfig :: subpackage_setting ( 'events' , 'force_end' ) ) { $ fields -> removeByName ( 'NoEnd' ) ; } else { if ( ! $ this -> ID ) { } } $ this -> extend ( 'updateFrontEndFields' , $ fields ) ; return $ fields ; } | Frontend fields Simple list of the basic fields - how they re intended to be edited |
13,918 | public function publicevents ( $ request , $ json = true , $ calendars = null , $ offset = 30 ) { $ calendarsSupplied = false ; if ( $ calendars ) { $ calendarsSupplied = true ; } $ events = PublicEvent :: get ( ) -> filter ( array ( 'StartDateTime:GreaterThan' => $ this -> eventlistOffsetDate ( 'start' , $ request -> postVar ( 'start' ) , $ offset ) , 'EndDateTime:LessThan' => $ this -> eventlistOffsetDate ( 'end' , $ request -> postVar ( 'end' ) , $ offset ) , ) ) ; $ sC = CalendarConfig :: subpackage_settings ( 'calendars' ) ; if ( $ sC [ 'shading' ] ) { if ( ! $ calendars ) { $ calendars = PublicCalendar :: get ( ) ; $ calendars = $ calendars -> filter ( array ( 'shaded' => false ) ) ; } } if ( $ calendars ) { $ calIDList = $ calendars -> getIdList ( ) ; if ( ! $ calendarsSupplied ) { $ calIDList [ 0 ] = 0 ; } $ events = $ events -> filter ( 'CalendarID' , $ calIDList ) ; } $ result = array ( ) ; if ( $ events ) { foreach ( $ events as $ event ) { $ calendar = $ event -> Calendar ( ) ; $ bgColor = '#999' ; $ textColor = '#FFF' ; $ borderColor = '#555' ; if ( $ calendar -> exists ( ) ) { $ bgColor = $ calendar -> getColorWithHash ( ) ; $ textColor = '#FFF' ; $ borderColor = $ calendar -> getColorWithHash ( ) ; } $ resultArr = self :: format_event_for_fullcalendar ( $ event ) ; $ resultArr = array_merge ( $ resultArr , array ( 'backgroundColor' => $ bgColor , 'textColor' => '#FFF' , 'borderColor' => $ borderColor , ) ) ; $ result [ ] = $ resultArr ; } } if ( $ json ) { $ response = new SS_HTTPResponse ( Convert :: array2json ( $ result ) ) ; $ response -> addHeader ( 'Content-Type' , 'application/json' ) ; return $ response ; } else { return $ result ; } } | Handles returning the JSON events data for a time range . |
13,919 | public function shadedevents ( $ request , $ json = true , $ calendars = null , $ offset = 3000 ) { if ( ! $ calendars ) { $ calendars = PublicCalendar :: get ( ) ; } $ calendars = $ calendars -> filter ( array ( 'shaded' => true ) ) ; return $ this -> publicevents ( $ request , $ json , $ calendars , $ offset ) ; } | Shaded events controller Shaded events for the calendar are called once on calendar initialization hence the offset of 3000 days |
13,920 | public function handleJsonResponse ( $ success = false , $ retVars = null ) { $ result = array ( ) ; if ( $ success ) { $ result = array ( 'success' => $ success ) ; } if ( $ retVars ) { $ result = array_merge ( $ retVars , $ result ) ; } $ response = new SS_HTTPResponse ( json_encode ( $ result ) ) ; $ response -> addHeader ( 'Content-Type' , 'application/json' ) ; return $ response ; } | AJAX Json Response handler |
13,921 | public static function format_event_for_fullcalendar ( $ event ) { $ bgColor = '#999' ; $ textColor = '#FFF' ; $ borderColor = '#555' ; $ arr = array ( 'id' => $ event -> ID , 'title' => $ event -> Title , 'start' => self :: format_datetime_for_fullcalendar ( $ event -> StartDateTime ) , 'end' => self :: format_datetime_for_fullcalendar ( $ event -> EndDateTime ) , 'allDay' => $ event -> isAllDay ( ) , 'className' => $ event -> ClassName , 'backgroundColor' => $ bgColor , 'textColor' => '#FFFFFF' , 'borderColor' => $ borderColor , ) ; return $ arr ; } | Format an event to comply with the fullcalendar format |
13,922 | public function buildForm ( FormBuilderInterface $ builder , array $ options ) { if ( $ options [ 'add_author' ] ) { $ builder -> add ( 'authorName' , TextType :: class , [ 'required' => true ] ) ; $ this -> vars [ 'add_author' ] = $ options [ 'add_author' ] ; } if ( $ options [ 'show_note' ] ) { $ builder -> add ( 'note' , ChoiceType :: class , [ 'required' => false , 'choices' => $ this -> noteProvider -> getValues ( ) , ] ) ; } $ builder -> add ( 'website' , UrlType :: class , [ 'required' => false ] ) -> add ( 'email' , EmailType :: class , [ 'required' => false ] ) ; } | Configures a Comment form . |
13,923 | public static function getDescriptions ( $ function_name ) { if ( is_string ( $ function_name ) ) $ reflection = new ReflectionFunction ( $ function_name ) ; elseif ( is_array ( $ function_name ) ) $ reflection = new ReflectionMethod ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ; else throw new LogicException ( ) ; $ comment = $ reflection -> getDocComment ( ) ; $ lines = explode ( "\n" , $ comment ) ; $ obj = new self ( $ lines ) ; return array ( trim ( $ obj -> short_desc ) , trim ( $ obj -> long_desc ) ) ; } | Returns short and log description of function |
13,924 | public function purify ( $ html = '' , $ config = [ ] ) { return $ this -> purifier -> purify ( $ html , $ this -> getConfig ( $ config ) ) ; } | Filter HTML . |
13,925 | protected function getConfig ( $ data = [ ] ) { $ config = HTMLPurifier_Config :: createDefault ( ) ; $ config -> autofinalize = false ; if ( empty ( $ data ) ) { $ data = 'default' ; } if ( is_string ( $ data ) ) { $ data = config ( sprintf ( 'parsedownextra.purifier.settings.%s' , $ data ) ) ; } $ data = array_replace_recursive ( ( array ) config ( 'parsedownextra.purifier.settings.global' ) , ( array ) $ data ) ; if ( is_array ( $ data ) ) { $ config -> loadArray ( $ data ) ; } return $ config ; } | Get HTMLPurifier config . |
13,926 | public function getRegisterLink ( ) { $ o = $ this -> owner ; $ detailStr = 'register/' . $ o -> ID ; $ calendarPage = CalendarPage :: get ( ) -> First ( ) ; return $ calendarPage -> Link ( ) . $ detailStr ; } | Getter for registration link |
13,927 | public function attach ( Process $ process ) { if ( $ this -> stopped ) { throw new RuntimeException ( 'Could not attach child to non-running pool' ) ; } $ firstProcess = $ this -> getFirstProcess ( ) ; if ( $ this -> isRunning ( ) && $ firstProcess instanceof Process && $ this -> count ( ) >= $ this -> processLimit ) { $ firstProcess -> wait ( ) ; $ this -> detach ( $ firstProcess ) ; } $ this -> process -> attach ( $ process ) ; if ( $ this -> isRunning ( ) ) { $ process -> start ( ) ; } } | Attachs a new process to the pool . |
13,928 | public function getFirstProcess ( ) { $ firstProcess = null ; foreach ( $ this -> process as $ process ) { if ( $ this -> isRunning ( ) && ! $ process -> isRunning ( ) ) { $ this -> detach ( $ process ) ; continue ; } if ( null !== $ firstProcess ) { continue ; } $ firstProcess = $ process ; } return $ firstProcess ; } | Returns the fist process in the queue . |
13,929 | public function getHandlers ( ) { $ handlers = [ ] ; foreach ( $ this -> handlers as $ key => $ handler ) { $ handlers [ $ key ] = $ handler -> getCallable ( ) ; } return $ handlers ; } | Returns all defined handlers . |
13,930 | public function create ( $ owner , $ email , array $ data ) { $ data = self :: mergeData ( $ data , [ 'owner' => $ owner , 'email' => $ email , ] ) ; return $ this -> client -> doPost ( 'contact/addContactExtEvent' , $ data ) ; } | Creating a new external event . |
13,931 | public function update ( $ owner , $ eventId , array $ data ) { $ data = self :: mergeData ( $ data , [ 'owner' => $ owner , 'contactEvent' => [ 'eventId' => $ eventId , ] , ] ) ; return $ this -> client -> doPost ( 'contact/updateContactExtEvent' , $ data ) ; } | Updating external event . |
13,932 | public function isFilterable ( ) { $ hasFilters = false ; foreach ( $ this -> columns as $ column ) { if ( $ column -> isFilterable ( ) ) { $ hasFilters = true ; break ; } } return $ hasFilters ; } | Is table filterable? |
13,933 | public function execute ( $ path , array $ args = [ ] , array $ envs = [ ] ) { if ( false === @ pcntl_exec ( $ path , $ args , $ envs ) ) { throw new RuntimeException ( 'Error when executing command' ) ; } } | Executes specified program in current process space . |
13,934 | public function flush ( $ seconds = 0 ) { if ( ! ( is_float ( $ seconds ) || is_int ( $ seconds ) ) || $ seconds < 0 ) { throw new InvalidArgumentException ( 'Seconds must be a number greater than or equal to 0' ) ; } if ( is_int ( $ seconds ) ) { sleep ( $ seconds ) ; } else { usleep ( $ seconds * 1000000 ) ; } clearstatcache ( ) ; gc_collect_cycles ( ) ; } | Try to flush current process memory . |
13,935 | public function setUserName ( $ userName ) { $ user = posix_getpwnam ( $ userName ) ; if ( ! isset ( $ user [ 'uid' ] ) ) { throw new InvalidArgumentException ( sprintf ( '"%s" is not a valid user name' , $ userName ) ) ; } $ this -> setUserId ( $ user [ 'uid' ] ) ; } | Defines the current user name . |
13,936 | public function setGroupName ( $ groupName ) { $ group = posix_getgrnam ( $ groupName ) ; if ( ! isset ( $ group [ 'gid' ] ) ) { throw new InvalidArgumentException ( sprintf ( '"%s" is not a valid group name' , $ groupName ) ) ; } $ this -> setGroupId ( $ group [ 'gid' ] ) ; } | Defines the current group name . |
13,937 | public static function fromGlobals ( array $ server = null , array $ query = null , array $ body = null , array $ cookies = null , array $ files = null ) : ServerRequestInterface { $ server = $ server ?? $ _SERVER ?? [ ] ; $ query = $ query ?? $ _GET ?? [ ] ; $ body = $ body ?? $ _POST ?? [ ] ; $ cookies = $ cookies ?? $ _COOKIE ?? [ ] ; $ files = $ files ?? $ _FILES ?? [ ] ; $ request = ( new ServerRequest ) -> withProtocolVersion ( request_http_version ( $ server ) ) -> withBody ( request_body ( ) ) -> withMethod ( request_method ( $ server ) ) -> withUri ( request_uri ( $ server ) ) -> withServerParams ( $ server ) -> withCookieParams ( $ cookies ) -> withQueryParams ( $ query ) -> withUploadedFiles ( request_files ( $ files ) ) -> withParsedBody ( $ body ) ; foreach ( request_headers ( $ server ) as $ name => $ value ) { $ request = $ request -> withHeader ( $ name , $ value ) ; } return $ request ; } | Creates the server request instance from superglobals variables |
13,938 | public function catchAll ( ... $ args ) : object { $ title = " | Anax" ; $ pages = [ "403" => [ "Anax 403: Forbidden" , "You are not permitted to do this." ] , "404" => [ "Anax 404: Not Found" , "The page you are looking for is not here." ] , "500" => [ "Anax 500: Internal Server Error" , "An unexpected condition was encountered." ] , ] ; $ path = $ this -> di -> get ( "router" ) -> getMatchedPath ( ) ; if ( ! array_key_exists ( $ path , $ pages ) ) { throw new NotFoundException ( "Internal route for '$path' is not found." ) ; } $ page = $ this -> di -> get ( "page" ) ; $ page -> add ( "anax/v2/error/default" , [ "header" => $ pages [ $ path ] [ 0 ] , "text" => $ pages [ $ path ] [ 1 ] , ] ) ; return $ page -> render ( [ "title" => $ pages [ $ path ] [ 0 ] . $ title ] , $ path ) ; } | Add internal routes for 403 404 and 500 that provides a page with error information using the default page layout . |
13,939 | private function startProcess ( OutputInterface $ output ) { $ arguments = $ this -> resolveProcessArgs ( ) ; $ name = sha1 ( serialize ( $ arguments ) ) ; if ( $ this -> background -> hasProcess ( $ name ) ) { throw new \ RuntimeException ( "Service is already running." ) ; } $ builder = new ProcessBuilder ( $ arguments ) ; if ( $ this -> hasParameter ( 'cwd' ) ) { $ builder -> setWorkingDirectory ( $ this -> getParameter ( 'cwd' ) ) ; } $ process = $ builder -> getProcess ( ) ; if ( $ output -> getVerbosity ( ) === OutputInterface :: VERBOSITY_VERBOSE ) { $ output -> writeln ( $ process -> getCommandLine ( ) ) ; } if ( $ this -> hasParameter ( 'output' ) ) { $ append = $ this -> hasParameter ( 'append' ) && $ this -> getParameter ( 'append' ) ? 'a' : 'w' ; $ stream = fopen ( $ this -> getParameter ( 'output' ) , $ append ) ; $ output = new StreamOutput ( $ stream , StreamOutput :: VERBOSITY_NORMAL , true ) ; } $ process -> start ( function ( $ type , $ buffer ) use ( $ output ) { $ output -> write ( $ buffer ) ; } ) ; $ this -> background -> addProcess ( $ name , $ process ) ; if ( ! in_array ( $ process -> getExitCode ( ) , $ this -> getParameter ( 'successCodes' ) ) ) { throw new TaskRuntimeException ( $ this -> getName ( ) , $ process -> getErrorOutput ( ) ) ; } } | Creates the given process |
13,940 | private function endProcess ( ) { $ arguments = $ this -> resolveProcessArgs ( ) ; $ name = sha1 ( serialize ( $ arguments ) ) ; if ( $ this -> background -> hasProcess ( $ name ) ) { $ this -> background -> getProcess ( $ name ) -> stop ( ) ; $ this -> background -> removeProcess ( $ name ) ; } } | Kills the given process |
13,941 | protected function getFiles ( array $ source ) { $ fileSet = [ ] ; foreach ( $ source as $ set ) { if ( ! array_key_exists ( 'files' , $ set ) ) { throw new \ Exception ( "`src` must have a `files` option" ) ; } if ( ! array_key_exists ( 'path' , $ set ) ) { $ set [ 'path' ] = getcwd ( ) ; } if ( ! array_key_exists ( 'recursive' , $ set ) ) { $ set [ 'recursive' ] = false ; } $ paths = is_array ( $ set [ 'path' ] ) ? $ set [ 'path' ] : [ $ set [ 'path' ] ] ; $ files = is_array ( $ set [ 'files' ] ) ? $ set [ 'files' ] : [ $ set [ 'files' ] ] ; foreach ( $ paths as $ path ) { foreach ( $ files as $ file ) { $ finder = new Finder ( ) ; $ finder -> files ( ) -> in ( $ path ) -> name ( $ file ) ; if ( ! $ set [ 'recursive' ] ) { $ finder -> depth ( '== 0' ) ; } $ fileSet = $ this -> appendFileSet ( $ finder , $ fileSet ) ; } } } return $ fileSet ; } | Finds all the files for the given config |
13,942 | public static function matchRequest ( $ regexp , $ method , $ url , $ query_data = null , $ body = null , array $ headers = array ( ) , array $ options = array ( ) ) { $ response = self :: request ( $ method , $ url , $ query_data , $ body , $ headers , $ options ) ; $ result = preg_match ( $ regexp , $ response ) ; if ( false === $ result ) { throw new pakeException ( "There's some error with this regular expression: " . $ regexp ) ; } if ( 0 === $ result ) { throw new pakeException ( "HTTP Response didn't match against regular expression: " . $ regexp ) ; } pake_echo_comment ( 'HTTP response matched against ' . $ regexp ) ; } | execute HTTP Request and match response against PCRE regexp |
13,943 | public static function get ( $ url , $ query_data = null , array $ headers = array ( ) , array $ options = array ( ) ) { return self :: request ( 'GET' , $ url , $ query_data , null , $ headers , $ options ) ; } | Convenience wrappers follow |
13,944 | protected function setApplicationName ( $ applicationName ) { if ( $ applicationName != strtolower ( $ applicationName ) ) { throw new InvalidArgumentException ( 'Application name should be lowercase' ) ; } if ( preg_match ( '/[^a-z0-9]/' , $ applicationName ) ) { throw new InvalidArgumentException ( 'Application name should contains only alphanumeric chars' ) ; } if ( strlen ( $ applicationName ) > 16 ) { $ message = 'Application name should be no longer than 16 characters' ; throw new InvalidArgumentException ( $ message ) ; } $ this -> applicationName = $ applicationName ; } | Defines application name . |
13,945 | protected function setLockDirectory ( $ lockDirectory ) { if ( ! is_dir ( $ lockDirectory ) ) { throw new InvalidArgumentException ( sprintf ( '"%s" is not a valid directory' , $ lockDirectory ) ) ; } if ( ! is_writable ( $ lockDirectory ) ) { throw new InvalidArgumentException ( sprintf ( '"%s" is not a writable directory' , $ lockDirectory ) ) ; } $ this -> lockDirectory = $ lockDirectory ; } | Defines the lock directory . |
13,946 | protected function getFileName ( ) { if ( null === $ this -> fileName ) { $ this -> fileName = $ this -> lockDirectory . '/' . $ this -> applicationName . '.pid' ; } return $ this -> fileName ; } | Returns the Pidfile filename . |
13,947 | protected function getFileResource ( ) { if ( null === $ this -> fileResource ) { $ fileResource = @ fopen ( $ this -> getFileName ( ) , 'a+' ) ; if ( ! $ fileResource ) { throw new RuntimeException ( 'Could not open pidfile' ) ; } $ this -> fileResource = $ fileResource ; } return $ this -> fileResource ; } | Returns the Pidfile file resource . |
13,948 | public function isActive ( ) { $ pid = $ this -> getProcessId ( ) ; if ( null === $ pid ) { return false ; } return $ this -> control -> signal ( ) -> send ( 0 , $ pid ) ; } | Returns TRUE when pidfile is active or FALSE when is not . |
13,949 | public function getProcessId ( ) { if ( null === $ this -> processId ) { $ content = fgets ( $ this -> getFileResource ( ) ) ; $ pieces = explode ( PHP_EOL , trim ( $ content ) ) ; $ this -> processId = reset ( $ pieces ) ? : 0 ; } return $ this -> processId ? : null ; } | Returns Pidfile content with the PID or NULL when there is no stored PID . |
13,950 | public function initialize ( ) { if ( $ this -> isActive ( ) ) { throw new RuntimeException ( 'Process is already active' ) ; } $ handle = $ this -> getFileResource ( ) ; if ( ! @ flock ( $ handle , ( LOCK_EX | LOCK_NB ) ) ) { throw new RuntimeException ( 'Could not lock pidfile' ) ; } if ( - 1 === @ fseek ( $ handle , 0 ) ) { throw new RuntimeException ( 'Could not seek pidfile cursor' ) ; } if ( ! @ ftruncate ( $ handle , 0 ) ) { throw new RuntimeException ( 'Could not truncate pidfile' ) ; } if ( ! @ fwrite ( $ handle , $ this -> control -> info ( ) -> getId ( ) . PHP_EOL ) ) { throw new RuntimeException ( 'Could not write on pidfile' ) ; } } | Initializes pidfile . |
13,951 | public function finalize ( ) { @ flock ( $ this -> getFileResource ( ) , LOCK_UN ) ; @ fclose ( $ this -> getFileResource ( ) ) ; @ unlink ( $ this -> getFileName ( ) ) ; } | Finalizes pidfile . |
13,952 | public function getConfigDir ( ) { $ home = getenv ( 'PHPCRSH_HOME' ) ; if ( $ home ) { return $ home ; } if ( defined ( 'PHP_WINDOWS_VERSION_MAJOR' ) ) { if ( ! getenv ( 'APPDATA' ) ) { throw new \ RuntimeException ( 'The APPDATA or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly' ) ; } $ home = strtr ( getenv ( 'APPDATA' ) , '\\' , '/' ) . '/phpcrsh' ; return $ home ; } if ( ! getenv ( 'HOME' ) ) { throw new \ RuntimeException ( 'The HOME or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly' ) ; } $ home = rtrim ( getenv ( 'HOME' ) , '/' ) . '/.phpcrsh' ; return $ home ; } | Return the configuration directory . |
13,953 | public function initConfig ( OutputInterface $ output = null ) { $ log = function ( $ message ) use ( $ output ) { if ( $ output ) { $ output -> writeln ( $ message ) ; } } ; if ( strtoupper ( substr ( PHP_OS , 0 , 3 ) ) === 'WIN' ) { throw new \ RuntimeException ( 'This feature is currently only supported on Linux and OSX (maybe). Please submit a PR to support it on windows.' ) ; } $ configDir = $ this -> getConfigDir ( ) ; $ distDir = $ this -> getDistConfigDir ( ) ; if ( ! $ this -> filesystem -> exists ( $ configDir ) ) { $ log ( '<info>[+] Creating directory:</info> ' . $ configDir ) ; $ this -> filesystem -> mkdir ( $ configDir ) ; } $ configFilenames = [ 'alias.yml' , 'phpcrsh.yml' , ] ; foreach ( $ configFilenames as $ configFilename ) { $ srcFile = $ distDir . '/' . $ configFilename ; $ destFile = $ configDir . '/' . $ configFilename ; if ( ! $ this -> filesystem -> exists ( $ srcFile ) ) { throw new \ Exception ( 'Dist (source) file "' . $ srcFile . '" does not exist.' ) ; } if ( $ this -> filesystem -> exists ( $ destFile ) ) { $ log ( sprintf ( '<info>File</info> %s <info> already exists, not overwriting.' , $ destFile ) ) ; return ; } $ this -> filesystem -> copy ( $ srcFile , $ destFile ) ; $ log ( '<info>[+] Creating file:</info> ' . $ destFile ) ; } } | Initialize a configuration files . |
13,954 | protected function hasBundle ( $ name , ContainerBuilder $ container ) { $ bundles = $ container -> getParameter ( 'kernel.bundles' ) ; return isset ( $ bundles [ $ name ] ) ; } | Returns if a bundle is available . |
13,955 | public function getRecentMedia ( $ tag , $ count = null , $ minTagId = null , $ maxTagId = null ) { $ params = [ 'query' => [ 'count' => $ count , 'min_tag_id' => $ minTagId , 'max_tag_id' => $ maxTagId , ] ] ; return $ this -> client -> request ( 'GET' , "tags/$tag/media/recent" , $ params ) ; } | Get a list of recently tagged media . |
13,956 | public function getLoginUrl ( array $ options = [ ] ) { $ url = $ this -> provider -> getAuthorizationUrl ( $ options ) ; $ this -> store -> set ( 'oauth2state' , $ this -> provider -> getState ( ) ) ; return $ url ; } | Sets CSRF value and returns the login URL . |
13,957 | public function getAccessToken ( $ code , $ grant = 'authorization_code' ) { $ this -> validateCsrf ( ) ; return $ this -> provider -> getAccessToken ( $ grant , [ 'code' => $ code ] ) ; } | Validates CSRF and returns the access token . |
13,958 | protected function validateCsrf ( ) { if ( empty ( $ this -> getInput ( 'state' ) ) || ( $ this -> getInput ( 'state' ) !== $ this -> store -> get ( 'oauth2state' ) ) ) { $ this -> store -> set ( 'oauth2state' , null ) ; throw new CsrfException ( 'Invalid state' ) ; } return ; } | Validates any CSRF parameters . |
13,959 | public function getAccessToken ( $ code , $ grant = 'authorization_code' ) { $ token = $ this -> container -> get ( RedirectLoginHelper :: class ) -> getAccessToken ( $ code , $ grant ) ; $ this -> setAccessToken ( $ token ) ; return $ token ; } | Sets and returns the access token . |
13,960 | public function setAccessToken ( AccessToken $ token ) { $ this -> container -> get ( 'config' ) -> set ( 'access_token' , json_encode ( $ token -> jsonSerialize ( ) ) ) ; } | Sets an access token and adds it to AuthMiddleware so the application can make authenticated requests . |
13,961 | public function getData ( $ sEmail ) { $ this -> sFormat = 'php' ; $ sProfile = file_get_contents ( $ this -> getUrl ( $ sEmail ) ) ; $ aProfile = unserialize ( $ sProfile ) ; if ( is_array ( $ aProfile ) && isset ( $ aProfile [ 'entry' ] ) ) { return $ aProfile ; } } | Return profile data based on the provided email address . |
13,962 | public function format ( $ sFormat = null ) { if ( null === $ sFormat ) { return $ this -> getFormat ( ) ; } return $ this -> setFormat ( $ sFormat ) ; } | Get or set the profile format to use . |
13,963 | public function setFormat ( $ sFormat = null ) { if ( null === $ sFormat ) { return $ this ; } if ( ! in_array ( $ sFormat , $ this -> aValidFormats ) ) { $ message = sprintf ( 'The format "%s" is not a valid one, profile format for Gravatar can be: %s' , $ sFormat , implode ( ', ' , $ this -> aValidFormats ) ) ; throw new InvalidProfileFormatException ( $ message ) ; } $ this -> sFormat = $ sFormat ; return $ this ; } | Set the profile format to use . |
13,964 | protected function createSignup ( array $ data , $ userId ) { return Signup :: create ( [ 'user_id' => $ userId , 'firstname' => $ data [ 'firstname' ] , 'surname' => $ data [ 'surname' ] , 'gender' => $ data [ 'gender' ] , 'email' => $ data [ 'email' ] , 'mobile_number' => $ data [ 'mobile_number' ] , ] ) ; } | Create a new user profile after a valid registration . |
13,965 | private static function handleErrors ( $ response ) { switch ( $ response -> getStatusCode ( ) ) { case 200 : return json_decode ( $ response -> getBody ( ) ) ; break ; case 401 : throw new UnauthorizedException ( 'Unauthorized (Invalid API key or insufficient permissions)' ) ; break ; case 404 : throw new NotFoundException ( 'Object not found within your account scope' ) ; break ; case 406 : throw new InvalidFormatException ( 'Requested format is not supported - request JSON or XML only' ) ; break ; case 422 : throw new ValidationException ( 'Validation error(s) for create or update method' ) ; break ; case 500 : throw new ServerException ( 'Something went wrong on Challonge\'s end' ) ; break ; default : $ decodedResponse = json_decode ( $ response -> getBody ( ) ) ; throw new UnexpectedErrorException ( $ decodedResponse ) ; break ; } } | Handles the response and throws errors accordingly . |
13,966 | protected function primeCoordinateParsers ( ) { $ this -> latitude -> getParser ( ) -> setDirection ( N :: LAT ) ; $ this -> longitude -> getParser ( ) -> setDirection ( N :: LONG ) ; } | Prime the coordinate parser with any additional information necessary |
13,967 | private function servicosDisponiveisUnidade ( $ unidade ) { $ rs = $ this -> getDoctrine ( ) -> getManager ( ) -> createQueryBuilder ( ) -> select ( [ 'e' , 's' , 'sub' ] ) -> from ( ServicoUnidade :: class , 'e' ) -> join ( 'e.servico' , 's' ) -> leftJoin ( 's.subServicos' , 'sub' ) -> where ( 's.mestre IS NULL' ) -> andWhere ( 'e.ativo = TRUE' ) -> andWhere ( 'e.unidade = :unidade' ) -> orderBy ( 's.nome' , 'ASC' ) -> setParameter ( 'unidade' , $ unidade ) -> getQuery ( ) -> getResult ( ) ; $ dados = [ 'unidade' => $ unidade -> getNome ( ) , 'servicos' => $ rs , ] ; return $ dados ; } | Retorna todos os servicos disponiveis para cada unidade . |
13,968 | public function registerEvents ( ) { if ( config ( 'passwordless.empty_tokens_after_login' ) === true ) { Event :: listen ( Authenticated :: class , function ( Authenticated $ event ) { $ event -> user -> tokens ( ) -> delete ( ) ; } ) ; } } | Register application event listeners |
13,969 | public function processOne ( ObjectId $ id ) : void { $ this -> catchSignal ( ) ; $ this -> logger -> debug ( 'process job [' . $ id . '] and exit' , [ 'category' => get_class ( $ this ) , ] ) ; try { $ job = $ this -> scheduler -> getJob ( $ id ) -> toArray ( ) ; $ this -> queueJob ( $ job ) ; } catch ( \ Exception $ e ) { $ this -> logger -> error ( 'failed process job [' . $ id . ']' , [ 'category' => get_class ( $ this ) , 'exception' => $ e , ] ) ; } } | Process one . |
13,970 | public function cleanup ( ) { $ this -> saveState ( ) ; if ( null === $ this -> current_job ) { $ this -> logger -> debug ( 'received cleanup call on worker [' . $ this -> id . '], no job is currently processing, exit now' , [ 'category' => get_class ( $ this ) , 'pm' => $ this -> process , ] ) ; $ this -> exit ( ) ; return null ; } $ this -> logger -> debug ( 'received cleanup call on worker [' . $ this -> id . '], reschedule current processing job [' . $ this -> current_job [ '_id' ] . ']' , [ 'category' => get_class ( $ this ) , 'pm' => $ this -> process , ] ) ; $ this -> updateJob ( $ this -> current_job , JobInterface :: STATUS_CANCELED ) ; $ this -> db -> { $ this -> scheduler -> getEventQueue ( ) } -> insertOne ( [ 'job' => $ this -> current_job [ '_id' ] , 'worker' => $ this -> id , 'status' => JobInterface :: STATUS_CANCELED , 'timestamp' => new UTCDateTime ( ) , ] ) ; $ options = $ this -> current_job [ 'options' ] ; $ options [ 'at' ] = 0 ; $ result = $ this -> scheduler -> addJob ( $ this -> current_job [ 'class' ] , $ this -> current_job [ 'data' ] , $ options ) -> getId ( ) ; $ this -> exit ( ) ; return $ result ; } | Cleanup and exit . |
13,971 | protected function saveState ( ) : self { foreach ( $ this -> queue as $ key => $ job ) { $ this -> db -> selectCollection ( $ this -> scheduler -> getJobQueue ( ) ) -> updateOne ( [ '_id' => $ job [ '_id' ] , '$isolated' => true ] , [ '$setOnInsert' => $ job ] , [ 'upsert' => true ] ) ; } return $ this ; } | Save local queue . |
13,972 | protected function catchSignal ( ) : self { pcntl_async_signals ( true ) ; pcntl_signal ( SIGTERM , [ $ this , 'cleanup' ] ) ; pcntl_signal ( SIGINT , [ $ this , 'cleanup' ] ) ; pcntl_signal ( SIGALRM , [ $ this , 'timeout' ] ) ; return $ this ; } | Catch signals and cleanup . |
13,973 | protected function queueJob ( array $ job ) : bool { if ( ! isset ( $ job [ 'status' ] ) ) { return false ; } if ( true === $ this -> collectJob ( $ job , JobInterface :: STATUS_PROCESSING ) ) { $ this -> processJob ( $ job ) ; } elseif ( JobInterface :: STATUS_POSTPONED === $ job [ 'status' ] ) { $ this -> logger -> debug ( 'found postponed job [' . $ job [ '_id' ] . '] to requeue' , [ 'category' => get_class ( $ this ) , 'pm' => $ this -> process , ] ) ; $ this -> queue [ ( string ) $ job [ '_id' ] ] = $ job ; } return true ; } | Queue job . |
13,974 | protected function processLocalQueue ( ) : bool { $ now = time ( ) ; foreach ( $ this -> queue as $ key => $ job ) { $ this -> db -> { $ this -> scheduler -> getJobQueue ( ) } -> updateOne ( [ '_id' => $ job [ '_id' ] , '$isolated' => true ] , [ '$setOnInsert' => $ job ] , [ 'upsert' => true ] ) ; if ( $ job [ 'options' ] [ 'at' ] <= $ now ) { $ this -> logger -> info ( 'postponed job [' . $ job [ '_id' ] . '] [' . $ job [ 'class' ] . '] can now be executed' , [ 'category' => get_class ( $ this ) , 'pm' => $ this -> process , ] ) ; unset ( $ this -> queue [ $ key ] ) ; $ job [ 'options' ] [ 'at' ] = 0 ; if ( true === $ this -> collectJob ( $ job , JobInterface :: STATUS_PROCESSING , JobInterface :: STATUS_POSTPONED ) ) { $ this -> processJob ( $ job ) ; } } } return true ; } | Check local queue for postponed jobs . |
13,975 | protected function executeJob ( array $ job ) : bool { if ( ! class_exists ( $ job [ 'class' ] ) ) { throw new InvalidJobException ( 'job class does not exists' ) ; } if ( null === $ this -> container ) { $ instance = new $ job [ 'class' ] ( ) ; } else { $ instance = $ this -> container -> get ( $ job [ 'class' ] ) ; } if ( ! ( $ instance instanceof JobInterface ) ) { throw new InvalidJobException ( 'job must implement JobInterface' ) ; } $ instance -> setData ( $ job [ 'data' ] ) -> setId ( $ job [ '_id' ] ) -> start ( ) ; $ return = $ this -> updateJob ( $ job , JobInterface :: STATUS_DONE ) ; $ this -> db -> { $ this -> scheduler -> getEventQueue ( ) } -> insertOne ( [ 'job' => $ job [ '_id' ] , 'worker' => $ this -> id , 'status' => JobInterface :: STATUS_DONE , 'timestamp' => new UTCDateTime ( ) , ] ) ; unset ( $ instance ) ; return $ return ; } | Execute job . |
13,976 | public static function addToHTML ( ) { if ( ! self :: isViewingHTMLPage ( ) ) { return ; } $ paths = self :: getAssetFilePaths ( 'js' ) ; echo sprintf ( '<script>%s</script>' , self :: getCombinedContents ( $ paths ) ) ; $ paths = self :: getAssetFilePaths ( 'css' ) ; echo sprintf ( '<style>%s</style>' , self :: getCombinedContents ( $ paths ) ) ; } | Add HTML to the page for frontend code This is probably not the right way to do it but it avoids us needing to reference files from vendor over HTTP requests . |
13,977 | public static function isViewingHTMLPage ( ) { if ( ! is_admin ( ) ) { return false ; } if ( ! array_key_exists ( 'SCRIPT_NAME' , $ _SERVER ) ) { return false ; } $ whitelisted_script_names = array ( 'wp-admin/post-new.php' , 'wp-admin/post.php' , 'wp-admin/edit.php' , ) ; $ script_name = strstr ( $ _SERVER [ 'SCRIPT_NAME' ] , 'wp-admin' ) ; if ( ! in_array ( $ script_name , $ whitelisted_script_names ) ) { return false ; } return true ; } | Is the user currently viewing a HTML page? Things that are not HTML would be admin - ajax . php for instance |
13,978 | public static function getAssetFilePaths ( $ type ) { $ path = sprintf ( '%s/assets/%s/' , __DIR__ , $ type ) ; $ filenames = preg_grep ( '/^[^\.]/' , scandir ( $ path ) ) ; if ( ! Arr :: iterable ( $ filenames ) ) { return array ( ) ; } return array_map ( function ( $ filename ) use ( $ path ) { return $ path . $ filename ; } , $ filenames ) ; } | Get file paths for a type of asset |
13,979 | public static function getCombinedContents ( $ paths ) { if ( ! Arr :: iterable ( $ paths ) ) { return '' ; } $ out = array ( ) ; foreach ( $ paths as $ path ) { $ out [ ] = file_get_contents ( $ path ) ; } return join ( "\n" , $ out ) ; } | Get the combined contents of multiple file paths |
13,980 | public function decode ( $ decrypted ) { $ pad = ord ( substr ( $ decrypted , - 1 ) ) ; if ( $ pad < 1 || $ pad > $ this -> blockSize ) { $ pad = 0 ; } return substr ( $ decrypted , 0 , ( strlen ( $ decrypted ) - $ pad ) ) ; } | Decode string . |
13,981 | public static function validateOptions ( array $ options ) : array { foreach ( $ options as $ option => $ value ) { switch ( $ option ) { case Scheduler :: OPTION_AT : case Scheduler :: OPTION_INTERVAL : case Scheduler :: OPTION_RETRY : case Scheduler :: OPTION_RETRY_INTERVAL : case Scheduler :: OPTION_TIMEOUT : if ( ! is_int ( $ value ) ) { throw new InvalidArgumentException ( 'option ' . $ option . ' must be an integer' ) ; } break ; case Scheduler :: OPTION_IGNORE_DATA : case Scheduler :: OPTION_FORCE_SPAWN : if ( ! is_bool ( $ value ) ) { throw new InvalidArgumentException ( 'option ' . $ option . ' must be a boolean' ) ; } break ; case Scheduler :: OPTION_ID : if ( ! $ value instanceof ObjectId ) { throw new InvalidArgumentException ( 'option ' . $ option . ' must be a an instance of ' . ObjectId :: class ) ; } break ; default : throw new InvalidArgumentException ( 'invalid option ' . $ option . ' given' ) ; } } return $ options ; } | Validate given job options . |
13,982 | protected static function addRedirectUriToServiceConfig ( array $ config ) { if ( ! empty ( $ config [ 'constructor' ] ) && is_array ( $ config [ 'constructor' ] ) ) { $ key = key ( $ config [ 'constructor' ] ) ; if ( ! isset ( $ config [ 'constructor' ] [ $ key ] [ 'redirectUri' ] ) ) { $ config [ 'constructor' ] [ $ key ] [ 'redirectUri' ] = static :: getRedirectUri ( ) ; } } return $ config ; } | Add in the redirectUri option to this service s constructor options |
13,983 | public function getUrl ( $ sEmail = null ) { if ( null !== $ sEmail ) { $ this -> setEmail ( $ sEmail ) ; } return static :: URL . 'avatar/' . $ this -> getHash ( $ this -> getEmail ( ) ) . $ this -> getParams ( ) ; } | Build the avatar URL based on the provided email address . |
13,984 | public function size ( $ iSize = null ) { if ( null === $ iSize ) { return $ this -> getSize ( ) ; } return $ this -> setSize ( $ iSize ) ; } | Get or set the avatar size to use . |
13,985 | public function defaultImage ( $ sDefaultImage = null , $ bForce = false ) { if ( null === $ sDefaultImage ) { return $ this -> getDefaultImage ( ) ; } return $ this -> setDefaultImage ( $ sDefaultImage , $ bForce ) ; } | Get or set the default image to use for avatars . |
13,986 | public function forceDefault ( $ bForceDefault = null ) { if ( null === $ bForceDefault ) { return $ this -> getForceDefault ( ) ; } return $ this -> setForceDefault ( $ bForceDefault ) ; } | Get or set if we have to force the default image to be always load . |
13,987 | public function rating ( $ sRating = null ) { if ( null === $ sRating ) { return $ this -> getMaxRating ( ) ; } return $ this -> setMaxRating ( $ sRating ) ; } | Get or set the maximum allowed rating for avatars . |
13,988 | public function extension ( $ sExtension = null ) { if ( null === $ sExtension ) { return $ this -> getExtension ( ) ; } return $ this -> setExtension ( $ sExtension ) ; } | Get or set the avatar extension to use . |
13,989 | public function setExtension ( $ sExtension = null ) { if ( null === $ sExtension ) { return $ this ; } if ( ! in_array ( $ sExtension , $ this -> aValidExtensions ) ) { $ message = sprintf ( 'The extension "%s" is not a valid one, extension image for Gravatar can be: %s' , $ sExtension , implode ( ', ' , $ this -> aValidExtensions ) ) ; throw new InvalidImageExtensionException ( $ message ) ; } $ this -> sExtension = $ sExtension ; return $ this ; } | Set the avatar extension to use . |
13,990 | protected function getParams ( ) { $ aParams = [ ] ; if ( null !== $ this -> getSize ( ) ) { $ aParams [ 's' ] = $ this -> getSize ( ) ; } if ( null !== $ this -> getDefaultImage ( ) ) { $ aParams [ 'd' ] = $ this -> getDefaultImage ( ) ; } if ( null !== $ this -> getMaxRating ( ) ) { $ aParams [ 'r' ] = $ this -> getMaxRating ( ) ; } if ( $ this -> forcingDefault ( ) ) { $ aParams [ 'f' ] = 'y' ; } return ( null !== $ this -> sExtension ? '.' . $ this -> sExtension : '' ) . ( empty ( $ aParams ) ? '' : '?' . http_build_query ( $ aParams , '' , '&' ) ) ; } | Compute params according to current settings . |
13,991 | public function render ( FileInterface $ file , $ width , $ height , array $ options = [ ] , $ usedPathsRelativeToCurrentScript = false ) : string { if ( ! array_key_exists ( self :: OPTIONS_IMAGE_RELATVE_WIDTH_KEY , $ options ) && isset ( $ GLOBALS [ 'TSFE' ] -> register [ self :: REGISTER_IMAGE_RELATVE_WIDTH_KEY ] ) ) { $ options [ self :: OPTIONS_IMAGE_RELATVE_WIDTH_KEY ] = ( float ) $ GLOBALS [ 'TSFE' ] -> register [ self :: REGISTER_IMAGE_RELATVE_WIDTH_KEY ] ; } $ view = $ this -> initializeView ( ) ; $ view -> assignMultiple ( [ 'isAnimatedGif' => $ this -> isAnimatedGif ( $ file ) , 'config' => $ this -> getConfig ( ) , 'data' => $ GLOBALS [ 'TSFE' ] -> cObj -> data , 'file' => $ file , 'options' => $ options , ] ) ; return $ view -> render ( 'pictureTag' ) ; } | Renders a responsive image tag . |
13,992 | public function getPattern ( PackageInterface $ package ) { if ( isset ( $ this -> packages [ $ package -> getName ( ) ] ) ) { return $ this -> packages [ $ package -> getName ( ) ] ; } elseif ( isset ( $ this -> packages [ $ package -> getPrettyName ( ) ] ) ) { return $ this -> packages [ $ package -> getPrettyName ( ) ] ; } elseif ( isset ( $ this -> types [ $ package -> getType ( ) ] ) ) { return $ this -> types [ $ package -> getType ( ) ] ; } } | Retrieve the pattern for the given package . |
13,993 | protected function convert ( $ extra ) { if ( isset ( $ extra [ 'custom-installer' ] ) ) { foreach ( $ extra [ 'custom-installer' ] as $ pattern => $ specs ) { foreach ( $ specs as $ spec ) { $ match = array ( ) ; if ( preg_match ( '/^type:(.*)$/' , $ spec , $ match ) ) { $ this -> types [ $ match [ 1 ] ] = $ pattern ; } else { $ this -> packages [ $ spec ] = $ pattern ; } } } } } | Converts the given extra data to relevant configuration values . |
13,994 | protected function getReturnUrl ( ) { $ backUrl = $ this -> getRequest ( ) -> getSession ( ) -> get ( 'oauth2.backurl' ) ; if ( ! $ backUrl || ! Director :: is_site_url ( $ backUrl ) ) { $ backUrl = Director :: absoluteBaseURL ( ) ; } return $ backUrl ; } | Get the return URL previously stored in session |
13,995 | public function authenticate ( HTTPRequest $ request ) { $ providerName = $ request -> getVar ( 'provider' ) ; $ context = $ request -> getVar ( 'context' ) ; $ scope = $ request -> getVar ( 'scope' ) ; if ( ! $ providerName || ! is_array ( $ scope ) ) { $ this -> httpError ( 404 ) ; return null ; } $ providerFactory = Injector :: inst ( ) -> get ( ProviderFactory :: class ) ; $ provider = $ providerFactory -> getProvider ( $ providerName ) ; $ url = $ provider -> getAuthorizationUrl ( [ 'scope' => $ scope ] ) ; $ request -> getSession ( ) -> set ( 'oauth2' , [ 'state' => $ provider -> getState ( ) , 'provider' => $ providerName , 'context' => $ context , 'scope' => $ scope , 'backurl' => $ this -> findBackUrl ( $ request ) ] ) ; return $ this -> redirect ( $ url ) ; } | This takes parameters like the provider scopes and callback url builds an authentication url with the provider s site and then redirects to it |
13,996 | public function callback ( HTTPRequest $ request ) { $ session = $ request -> getSession ( ) ; if ( ! $ this -> validateState ( $ request ) ) { $ session -> clear ( 'oauth2' ) ; $ this -> httpError ( 400 , 'Invalid session state.' ) ; return null ; } $ providerName = $ session -> get ( 'oauth2.provider' ) ; $ providerFactory = Injector :: inst ( ) -> get ( ProviderFactory :: class ) ; $ provider = $ providerFactory -> getProvider ( $ providerName ) ; $ returnUrl = $ this -> getReturnUrl ( ) ; try { $ accessToken = $ provider -> getAccessToken ( 'authorization_code' , [ 'code' => $ request -> getVar ( 'code' ) ] ) ; $ handlers = $ this -> getHandlersForContext ( $ session -> get ( 'oauth2.context' ) ) ; $ results = [ ] ; foreach ( $ handlers as $ handlerConfig ) { $ handler = Injector :: inst ( ) -> create ( $ handlerConfig [ 'class' ] ) ; $ results [ ] = $ handler -> handleToken ( $ accessToken , $ provider ) ; } foreach ( $ results as $ result ) { if ( $ result instanceof HTTPResponse ) { $ session -> clear ( 'oauth2' ) ; if ( $ result -> isRedirect ( ) ) { $ location = $ result -> getHeader ( 'location' ) ; $ relativeLocation = Director :: makeRelative ( $ location ) ; if ( strpos ( $ relativeLocation , Security :: config ( ) -> uninherited ( 'login_url' ) ) === 0 && strpos ( $ relativeLocation , 'BackURL' ) !== - 1 ) { $ session -> set ( 'BackURL' , $ returnUrl ) ; $ location = HTTP :: setGetVar ( 'BackURL' , $ returnUrl , $ location ) ; $ result -> addHeader ( 'location' , $ location ) ; } } return $ result ; } } } catch ( IdentityProviderException $ e ) { $ logger = Injector :: inst ( ) -> get ( LoggerInterface :: class . '.oauth' ) ; $ logger -> error ( 'OAuth IdentityProviderException: ' . $ e -> getMessage ( ) ) ; $ this -> httpError ( 400 , 'Invalid access token.' ) ; return null ; } catch ( Exception $ e ) { $ logger = Injector :: inst ( ) -> get ( LoggerInterface :: class . '.oauth' ) ; $ logger -> error ( 'OAuth Exception: ' . $ e -> getMessage ( ) ) ; $ this -> httpError ( 400 , $ e -> getMessage ( ) ) ; return null ; } finally { $ session -> clear ( 'oauth2' ) ; } return $ this -> redirect ( $ returnUrl ) ; } | The return endpoint after the user has authenticated with a provider |
13,997 | protected function getHandlersForContext ( $ context = null ) { $ handlers = $ this -> config ( ) -> get ( 'token_handlers' ) ; if ( empty ( $ handlers ) ) { throw new Exception ( 'No token handlers were registered' ) ; } $ allowedContexts = [ '*' ] ; if ( $ context ) { $ allowedContexts [ ] = $ context ; } $ handlers = array_filter ( $ handlers , function ( $ handler ) use ( $ allowedContexts ) { return in_array ( $ handler [ 'context' ] , $ allowedContexts ) ; } ) ; uasort ( $ handlers , function ( $ a , $ b ) { if ( ! array_key_exists ( 'priority' , $ a ) || ! array_key_exists ( 'priority' , $ b ) ) { return 0 ; } return ( $ a [ 'priority' ] < $ b [ 'priority' ] ) ? - 1 : 1 ; } ) ; return $ handlers ; } | Get a list of token handlers for the given context |
13,998 | public function validateState ( HTTPRequest $ request ) { $ state = $ request -> getVar ( 'state' ) ; $ session = $ request -> getSession ( ) ; $ data = $ session -> get ( 'oauth2' ) ; if ( empty ( $ data [ 'state' ] ) || empty ( $ data [ 'provider' ] ) || empty ( $ data [ 'scope' ] ) || $ state !== $ data [ 'state' ] ) { $ session -> clear ( 'oauth2' ) ; return false ; } return true ; } | Validate the request s state against the one stored in session |
13,999 | public function getTournaments ( ) { $ response = Guzzle :: get ( 'tournaments' ) ; $ tournaments = [ ] ; foreach ( $ response as $ tourney ) { $ tournaments [ ] = new Tournament ( $ tourney -> tournament ) ; } return $ tournaments ; } | Retrieve a set of tournaments created with your account . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.