idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
42,400
private function createEditForm ( MediaType $ entity ) { $ form = $ this -> createForm ( new MediaTypeType ( ) , $ entity , array ( 'action' => $ this -> generateUrl ( 'mediatype_update' , array ( 'id' => $ entity -> getId ( ) ) ) , 'method' => 'PUT' , ) ) ; $ form -> add ( 'submit' , 'submit' , array ( 'label' => 'Update' ) ) ; return $ form ; }
Creates a form to edit a MediaType entity .
42,401
private function extractHeaders ( $ str ) { $ this -> debug -> log ( __METHOD__ ) ; $ this -> debug -> groupUncollapse ( ) ; $ headerStart = 0 ; $ headerLenStack = array ( ) ; $ i = 0 ; while ( true ) { $ headerEnd = \ strpos ( $ str , "\r\n\r\n" , $ headerStart ) ; $ headerLength = $ headerEnd - $ headerStart ; $ headers = \ substr ( $ str , $ headerStart , $ headerLength ) ; $ headerStart = $ headerEnd + 4 ; $ headerLenStack [ ] = \ strlen ( $ headers ) + 4 ; if ( \ count ( $ headerLenStack ) > $ this -> curlInfo [ 'redirect_count' ] ) { $ sum = 0 ; for ( $ j = $ i ; $ j >= 0 ; $ j -- ) { $ sum += $ headerLenStack [ $ j ] ; if ( $ sum == $ this -> curlInfo [ 'header_size' ] ) { break 2 ; } } } if ( $ headerEnd === false || $ i > 20 ) { $ this -> debug -> warn ( 'error parsing headers' ) ; break ; } $ i ++ ; } return $ headers ; }
for a string containing both headers and content return the header portion
42,402
protected function curlGetOptions ( $ url , $ options = array ( ) ) { $ this -> debug -> groupCollapsed ( __METHOD__ ) ; $ urlParts = Html :: parseUrl ( $ url ) ; $ optionsDefault = $ this -> curlOptionsDefault ( $ url ) ; $ options = $ this -> curlOptionsNormalize ( $ options ) ; $ options = ArrayUtil :: mergeDeep ( $ optionsDefault , $ options ) ; $ options [ 'CURLOPT_URL' ] = \ str_replace ( ' ' , '%20' , $ options [ 'CURLOPT_URL' ] ) ; $ options [ 'CURLOPT_FOLLOWLOCATION' ] = false ; if ( $ options [ 'verbose' ] ) { $ options [ 'CURLOPT_VERBOSE' ] = true ; $ options [ 'CURLINFO_HEADER_OUT' ] = false ; $ options [ 'CURLOPT_STDERR' ] = \ fopen ( 'php://temp' , 'rw' ) ; } if ( ! empty ( $ options [ 'CURLOPT_PROXY' ] ) && \ in_array ( $ urlParts [ 'host' ] , array ( '127.0.0.1' , 'localhost' ) ) ) { $ this -> debug -> log ( 'not using proxy for localhost' ) ; $ options [ 'CURLOPT_PROXY' ] = false ; } if ( empty ( $ options [ 'CURLOPT_PROXY' ] ) && \ getenv ( 'http_proxy' ) ) { $ this -> debug -> log ( 'http_proxy env variable is set.... setting NO_PROXY env variable' ) ; \ putenv ( 'NO_PROXY=' . $ urlParts [ 'host' ] ) ; } $ this -> debug -> groupEnd ( ) ; return $ options ; }
Get complete options
42,403
protected function curlOptionsDefault ( $ url ) { $ this -> debug -> groupCollapsed ( __METHOD__ ) ; $ opts = array ( 'curl_getinfo' => false , 'verbose' => false , 'CURLINFO_HEADER_OUT' => true , 'CURLOPT_FOLLOWLOCATION' => false , 'CURLOPT_HEADER' => true , 'CURLOPT_IPRESOLVE' => CURL_IPRESOLVE_V4 , 'CURLOPT_URL' => $ url , 'CURLOPT_HTTPHEADER' => array ( ) , 'CURLOPT_REFERER' => Html :: getSelfUrl ( array ( ) , array ( 'fullUrl' => true , 'chars' => false ) ) , 'CURLOPT_RETURNTRANSFER' => true , 'CURLOPT_SSL_VERIFYPEER' => false , 'CURLOPT_USERAGENT' => ! empty ( $ _SERVER [ 'HTTP_USER_AGENT' ] ) ? $ _SERVER [ 'HTTP_USER_AGENT' ] : 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' , ) ; $ opts = \ array_merge ( $ opts , $ this -> cfg [ 'curl_opts' ] ) ; $ proxy = \ getenv ( 'http_proxy' ) ; if ( $ proxy ) { $ this -> debug -> log ( 'http_proxy env var set...setting default PROXY, CURLOPT_PROXYUSERPWD, and PROXYAUTH' ) ; $ pup = \ parse_url ( $ proxy ) ; $ opts [ 'CURLOPT_PROXY' ] = $ pup [ 'host' ] ; if ( ! empty ( $ pup [ 'port' ] ) ) { $ opts [ 'CURLOPT_PROXY' ] .= ':' . $ pup [ 'port' ] ; } if ( ! empty ( $ pup [ 'user' ] ) ) { $ opts [ 'CURLOPT_PROXYUSERPWD' ] = $ pup [ 'user' ] ; if ( ! empty ( $ pup [ 'pass' ] ) ) { $ opts [ 'CURLOPT_PROXYUSERPWD' ] .= ':' . $ pup [ 'pass' ] ; } } $ opts [ 'CURLOPT_PROXYAUTH' ] = CURLAUTH_BASIC ; } $ this -> debug -> groupEnd ( ) ; return $ opts ; }
Get defautl cURL options
42,404
protected function curlGetReturn ( ) { $ follow = ! isset ( $ this -> optionsPassed [ 'CURLOPT_FOLLOWLOCATION' ] ) || $ this -> optionsPassed [ 'CURLOPT_FOLLOWLOCATION' ] ; $ headers = $ this -> fetchResponse [ 'headers' ] ; if ( $ follow && isset ( $ headers [ 'Location' ] ) ) { $ location = Html :: getAbsUrl ( $ this -> options [ 'CURLOPT_URL' ] , $ headers [ 'Location' ] ) ; $ this -> debug -> info ( 'redirect' , $ location ) ; if ( \ count ( \ array_keys ( $ this -> redirectHistory , $ location ) ) > 1 ) { $ this -> debug -> warn ( 'redirect loop' , $ this -> redirectHistory ) ; $ return = false ; } else { if ( \ in_array ( $ headers [ 'Return-Code' ] , array ( 302 , 303 ) ) ) { $ this -> optionsPassed [ 'CURLOPT_POSTFIELDS' ] = null ; $ this -> optionsPassed [ 'post' ] = null ; } $ this -> optionsPassed [ 'cookies' ] = $ this -> fetchResponse [ 'cookies' ] ; unset ( $ this -> optionsPassed [ 'url' ] ) ; unset ( $ this -> optionsPassed [ 'CURLOPT_URL' ] ) ; $ return = $ this -> fetchCurl ( $ location , $ this -> optionsPassed ) ; } } else { $ this -> redirectHistory = array ( ) ; if ( $ headers && $ headers [ 'Return-Code' ] != 200 && $ follow ) { $ return = false ; } else { if ( ! empty ( $ headers [ 'Content-Encoding' ] ) && $ headers [ 'Content-Encoding' ] == 'gzip' ) { $ this -> debug -> info ( 'decompressing gzip content' ) ; $ this -> fetchResponse [ 'body' ] = Gzip :: decompressString ( $ this -> fetchResponse [ 'body' ] ) ; } $ return = $ this -> fetchResponse ; } } return $ return ; }
Build return value from fetchResponse
42,405
protected function _setFile ( $ path ) { $ this -> _name .= $ path ; $ this -> _data [ '' . $ path . '' ] = file_get_contents ( $ path ) ; if ( $ this -> _type == 'css' ) { $ this -> _currentPath = dirname ( $ path ) . '/' ; $ this -> _data [ '' . $ path . '' ] = preg_replace_callback ( '`url\((.*)\)`isU' , [ 'Gcs\Framework\Core\Asset\Asset' , '_parseRelativePathCssUrl' ] , $ this -> _data [ '' . $ path . '' ] ) ; $ this -> _data [ '' . $ path . '' ] = preg_replace_callback ( '`src=\'(.*)\'`isU' , [ 'Gcs\Framework\Core\Asset\Asset' , '_parseRelativePathCssSrc' ] , $ this -> _data [ '' . $ path . '' ] ) ; } }
configure one file
42,406
protected function _setDir ( $ path ) { if ( $ handle = opendir ( $ path ) ) { while ( false !== ( $ entry = readdir ( $ handle ) ) ) { $ extension = explode ( '.' , basename ( $ entry ) ) ; $ ext = $ extension [ count ( $ extension ) - 1 ] ; if ( $ ext == $ this -> _type ) { $ this -> _setFile ( $ path . $ entry ) ; } } closedir ( $ handle ) ; } }
configure a directory
42,407
protected function _parseRelativePathCss ( $ m ) { $ pathReplace = '' ; if ( ! preg_match ( '~(?:f|ht)tps?://~i' , $ m [ 1 ] ) && ! preg_match ( '~(data)~i' , $ m [ 1 ] ) ) { $ m [ 1 ] = preg_replace ( "#^/#isU" , '' , $ m [ 1 ] ) ; $ m [ 1 ] = str_replace ( '"' , '' , $ m [ 1 ] ) ; $ m [ 1 ] = str_replace ( "'" , '' , $ m [ 1 ] ) ; $ this -> _currentPath = preg_replace ( "#^/#isU" , '' , $ this -> _currentPath ) ; $ numberParentDir = substr_count ( $ m [ 1 ] , '../' ) ; if ( $ numberParentDir > 0 ) { for ( $ i = 0 ; $ i < $ numberParentDir ; $ i ++ ) { $ pathReplace .= '(.[^\/]+)\/' ; } $ pathReplace .= '$' ; $ newCurrentPath = preg_replace ( '#' . $ pathReplace . '#isU' , '/' , $ this -> _currentPath ) ; $ m [ 1 ] = preg_replace ( '#\.\./#isU' , '' , $ m [ 1 ] ) ; if ( $ newCurrentPath != $ this -> _currentPath ) { $ m [ 1 ] = $ newCurrentPath . $ m [ 1 ] ; } else if ( ! preg_match ( '#^' . preg_quote ( $ newCurrentPath ) . '#isU' , $ m [ 1 ] ) ) { if ( ! preg_match ( '#^/asset#isU' , $ m [ 1 ] ) && ! preg_match ( '#^asset#isU' , $ m [ 1 ] ) ) { $ m [ 1 ] = $ newCurrentPath . $ m [ 1 ] ; } } } if ( ! preg_match ( '#^/#isU' , $ m [ 1 ] ) ) { $ m [ 1 ] = '/' . $ m [ 1 ] ; } if ( Config :: config ( ) [ 'user' ] [ 'output' ] [ 'https' ] ) { return 'https://' . str_replace ( '//' , '/' , $ _SERVER [ 'HTTP_HOST' ] . '/' . Config :: config ( ) [ 'user' ] [ 'framework' ] [ 'folder' ] . $ m [ 1 ] ) ; } else { return 'http://' . str_replace ( '//' , '/' , $ _SERVER [ 'HTTP_HOST' ] . '/' . Config :: config ( ) [ 'user' ] [ 'framework' ] [ 'folder' ] . $ m [ 1 ] ) ; } } else { return $ m [ 1 ] ; } }
correct wrong links
42,408
protected function _compress ( ) { foreach ( $ this -> _data as $ value ) { $ this -> _concatContent .= $ value ; } if ( $ this -> _type == 'css' ) { $ this -> _concatContent = preg_replace ( '!/\*[^*]*\*+([^/][^*]*\*+)*/!' , '' , $ this -> _concatContent ) ; $ this -> _concatContent = str_replace ( ': ' , ':' , $ this -> _concatContent ) ; $ this -> _concatContent = str_replace ( [ "\r\n" , "\r" , "\n" , "\t" , ' ' , ' ' , ' ' ] , '' , $ this -> _concatContent ) ; } }
concatenate parser content
42,409
public function getResource ( $ identifier ) { $ client = $ this -> getRepository ( ) -> findOneBy ( array ( 'id' => $ identifier ) ) ; if ( ! $ client ) { throw new NotFoundHttpException ( $ this -> translator -> trans ( 'error.client_not_found' , array ( '%id%' => $ identifier ) ) ) ; } return $ this -> createResourceFromClient ( $ client ) ; }
Returns the oAuth2 Client with the given identifier .
42,410
public function getCollection ( array $ options = array ( ) ) { $ collection = $ this -> getRepository ( ) -> findAll ( ) ; $ resource = new Resource ( $ this -> generateBrowseUrl ( ) , array ( 'count' => count ( $ collection ) ) ) ; foreach ( $ collection as $ element ) { $ resource -> setEmbedded ( 'client' , $ this -> createResourceFromClient ( $ element ) ) ; } return $ resource ; }
Returns all clients in a single collection resource .
42,411
public function delete ( Resource $ resource ) { $ data = $ resource -> toArray ( ) ; $ client = $ this -> getRepository ( ) -> findOneBy ( array ( 'id' => $ data [ 'id' ] ) ) ; if ( ! $ client ) { $ errorMessage = $ this -> translator -> trans ( 'error.client_not_found' , array ( '%id%' => $ data [ 'id' ] ) ) ; throw new NotFoundHttpException ( $ errorMessage ) ; } $ this -> entityManager -> remove ( $ client ) ; }
Removes the Client from the database .
42,412
protected function createResourceFromClient ( ClientEntity $ client ) { $ resource = new Resource ( $ this -> generateReadUrl ( $ client -> getId ( ) ) , array ( 'id' => $ client -> getId ( ) , 'publicId' => $ client -> getPublicId ( ) , 'secret' => $ client -> getSecret ( ) , 'redirectUris' => $ client -> getRedirectUris ( ) , 'grants' => $ client -> getAllowedGrantTypes ( ) , ) ) ; return $ resource ; }
Creates a new resource from the given Client entity .
42,413
public function handle ( GetResponseEvent $ event ) { if ( ! $ this -> registered && null !== $ this -> dispatcher && $ event -> isMasterRequest ( ) ) { $ this -> dispatcher -> addListener ( KernelEvents :: RESPONSE , array ( $ this , 'onKernelResponse' ) ) ; $ this -> registered = true ; } $ request = $ event -> getRequest ( ) ; $ session = $ request -> getSession ( ) ; if ( null === $ session || null === $ token = $ session -> get ( '_security_' . $ this -> contextKey ) ) { $ this -> context -> setToken ( null ) ; return ; } $ token = unserialize ( $ token ) ; if ( null !== $ this -> logger ) { $ this -> logger -> debug ( 'Read SecurityContext from the session' ) ; } if ( $ token instanceof TokenInterface ) { $ token = $ this -> refreshUser ( $ token ) ; } elseif ( null !== $ token ) { if ( null !== $ this -> logger ) { $ this -> logger -> warning ( sprintf ( 'Session includes a "%s" where a security token is expected' , is_object ( $ token ) ? get_class ( $ token ) : gettype ( $ token ) ) ) ; } $ token = null ; } $ this -> context -> setToken ( $ token ) ; }
Reads the SecurityContext from the session .
42,414
public function onKernelResponse ( FilterResponseEvent $ event ) { if ( ! $ event -> isMasterRequest ( ) ) { return ; } if ( ! $ event -> getRequest ( ) -> hasSession ( ) ) { return ; } if ( null !== $ this -> logger ) { $ this -> logger -> debug ( 'Write SecurityContext in the session' ) ; } $ request = $ event -> getRequest ( ) ; $ session = $ request -> getSession ( ) ; if ( null === $ session ) { return ; } if ( ( null === $ token = $ this -> context -> getToken ( ) ) || ( $ token instanceof AnonymousToken ) ) { if ( $ request -> hasPreviousSession ( ) ) { $ session -> remove ( '_security_' . $ this -> contextKey ) ; } } else { $ session -> set ( '_security_' . $ this -> contextKey , serialize ( $ token ) ) ; } }
Writes the SecurityContext to the session .
42,415
private function refreshUser ( TokenInterface $ token ) { $ user = $ token -> getUser ( ) ; if ( ! $ user instanceof UserInterface ) { return $ token ; } if ( null !== $ this -> logger ) { $ this -> logger -> debug ( sprintf ( 'Reloading user from user provider.' ) ) ; } foreach ( $ this -> userProviders as $ provider ) { try { $ refreshedUser = $ provider -> refreshUser ( $ user ) ; $ token -> setUser ( $ refreshedUser ) ; if ( null !== $ this -> logger ) { $ this -> logger -> debug ( sprintf ( 'Username "%s" was reloaded from user provider.' , $ refreshedUser -> getUsername ( ) ) ) ; } return $ token ; } catch ( UnsupportedUserException $ unsupported ) { } catch ( UsernameNotFoundException $ notFound ) { if ( null !== $ this -> logger ) { $ this -> logger -> warning ( sprintf ( 'Username "%s" could not be found.' , $ notFound -> getUsername ( ) ) ) ; } return ; } } throw new \ RuntimeException ( sprintf ( 'There is no user provider for user "%s".' , get_class ( $ user ) ) ) ; }
Refreshes the user by reloading it from the user provider
42,416
public function Table ( $ Page = '0' ) { if ( $ this -> SyndicationMethod == SYNDICATION_NONE ) $ this -> View = 'table' ; $ this -> Index ( $ Page ) ; }
Table layout for discussions . Mimics more traditional forum discussion layout .
42,417
public function Bookmarked ( $ Page = '0' ) { $ this -> Permission ( 'Garden.SignIn.Allow' ) ; Gdn_Theme :: Section ( 'DiscussionList' ) ; $ Layout = C ( 'Vanilla.Discussions.Layout' ) ; switch ( $ Layout ) { case 'table' : if ( $ this -> SyndicationMethod == SYNDICATION_NONE ) $ this -> View = 'table' ; break ; default : $ this -> View = 'index' ; break ; } list ( $ Page , $ Limit ) = OffsetLimit ( $ Page , C ( 'Vanilla.Discussions.PerPage' , 30 ) ) ; $ this -> CanonicalUrl ( Url ( ConcatSep ( '/' , 'discussions' , 'bookmarked' , PageNumber ( $ Page , $ Limit , TRUE , FALSE ) ) , TRUE ) ) ; if ( ! is_numeric ( $ Page ) || $ Page < 0 ) $ Page = 0 ; $ DiscussionModel = new DiscussionModel ( ) ; $ Wheres = array ( 'w.Bookmarked' => '1' , 'w.UserID' => Gdn :: Session ( ) -> UserID ) ; $ this -> DiscussionData = $ DiscussionModel -> Get ( $ Page , $ Limit , $ Wheres ) ; $ this -> SetData ( 'Discussions' , $ this -> DiscussionData ) ; $ CountDiscussions = $ DiscussionModel -> GetCount ( $ Wheres ) ; $ this -> SetData ( 'CountDiscussions' , $ CountDiscussions ) ; $ this -> Category = FALSE ; $ this -> SetJson ( 'Loading' , $ Page . ' to ' . $ Limit ) ; $ PagerFactory = new Gdn_PagerFactory ( ) ; $ this -> EventArguments [ 'PagerType' ] = 'Pager' ; $ this -> FireEvent ( 'BeforeBuildBookmarkedPager' ) ; $ this -> Pager = $ PagerFactory -> GetPager ( $ this -> EventArguments [ 'PagerType' ] , $ this ) ; $ this -> Pager -> ClientID = 'Pager' ; $ this -> Pager -> Configure ( $ Page , $ Limit , $ CountDiscussions , 'discussions/bookmarked/%1$s' ) ; if ( ! $ this -> Data ( '_PagerUrl' ) ) $ this -> SetData ( '_PagerUrl' , 'discussions/bookmarked/{Page}' ) ; $ this -> SetData ( '_Page' , $ Page ) ; $ this -> SetData ( '_Limit' , $ Limit ) ; $ this -> FireEvent ( 'AfterBuildBookmarkedPager' ) ; if ( $ this -> _DeliveryType != DELIVERY_TYPE_ALL ) { $ this -> SetJson ( 'LessRow' , $ this -> Pager -> ToString ( 'less' ) ) ; $ this -> SetJson ( 'MoreRow' , $ this -> Pager -> ToString ( 'more' ) ) ; $ this -> View = 'discussions' ; } $ this -> AddModule ( 'DiscussionFilterModule' ) ; $ this -> AddModule ( 'NewDiscussionModule' ) ; $ this -> AddModule ( 'CategoriesModule' ) ; $ this -> SetData ( 'Title' , T ( 'My Bookmarks' ) ) ; $ this -> SetData ( 'Breadcrumbs' , array ( array ( 'Name' => T ( 'My Bookmarks' ) , 'Url' => '/discussions/bookmarked' ) ) ) ; $ this -> Render ( ) ; }
Display discussions the user has bookmarked .
42,418
public function Mine ( $ Page = 'p1' ) { $ this -> Permission ( 'Garden.SignIn.Allow' ) ; Gdn_Theme :: Section ( 'DiscussionList' ) ; list ( $ Offset , $ Limit ) = OffsetLimit ( $ Page , C ( 'Vanilla.Discussions.PerPage' , 30 ) ) ; $ Session = Gdn :: Session ( ) ; $ Wheres = array ( 'd.InsertUserID' => $ Session -> UserID ) ; $ DiscussionModel = new DiscussionModel ( ) ; $ this -> DiscussionData = $ DiscussionModel -> Get ( $ Offset , $ Limit , $ Wheres ) ; $ this -> SetData ( 'Discussions' , $ this -> DiscussionData ) ; $ CountDiscussions = $ this -> SetData ( 'CountDiscussions' , $ DiscussionModel -> GetCount ( $ Wheres ) ) ; $ PagerFactory = new Gdn_PagerFactory ( ) ; $ this -> EventArguments [ 'PagerType' ] = 'MorePager' ; $ this -> FireEvent ( 'BeforeBuildMinePager' ) ; $ this -> Pager = $ PagerFactory -> GetPager ( $ this -> EventArguments [ 'PagerType' ] , $ this ) ; $ this -> Pager -> MoreCode = 'More Discussions' ; $ this -> Pager -> LessCode = 'Newer Discussions' ; $ this -> Pager -> ClientID = 'Pager' ; $ this -> Pager -> Configure ( $ Offset , $ Limit , $ CountDiscussions , 'discussions/mine/%1$s' ) ; $ this -> SetData ( '_PagerUrl' , 'discussions/mine/{Page}' ) ; $ this -> SetData ( '_Page' , $ Page ) ; $ this -> SetData ( '_Limit' , $ Limit ) ; $ this -> FireEvent ( 'AfterBuildMinePager' ) ; if ( $ this -> _DeliveryType != DELIVERY_TYPE_ALL ) { $ this -> SetJson ( 'LessRow' , $ this -> Pager -> ToString ( 'less' ) ) ; $ this -> SetJson ( 'MoreRow' , $ this -> Pager -> ToString ( 'more' ) ) ; $ this -> View = 'discussions' ; } $ this -> AddModule ( 'DiscussionFilterModule' ) ; $ this -> AddModule ( 'NewDiscussionModule' ) ; $ this -> AddModule ( 'CategoriesModule' ) ; $ this -> AddModule ( 'BookmarkedModule' ) ; $ this -> SetData ( 'Title' , T ( 'My Discussions' ) ) ; $ this -> SetData ( 'Breadcrumbs' , array ( array ( 'Name' => T ( 'My Discussions' ) , 'Url' => '/discussions/mine' ) ) ) ; $ this -> Render ( 'Index' ) ; }
Display discussions started by the user .
42,419
public function GetCommentCounts ( ) { $ this -> AllowJSONP ( TRUE ) ; $ vanilla_identifier = GetValue ( 'vanilla_identifier' , $ _GET ) ; if ( ! is_array ( $ vanilla_identifier ) ) $ vanilla_identifier = array ( $ vanilla_identifier ) ; $ vanilla_identifier = array_unique ( $ vanilla_identifier ) ; $ FinalData = array_fill_keys ( $ vanilla_identifier , 0 ) ; $ Misses = array ( ) ; $ CacheKey = 'embed.comments.count.%s' ; $ OriginalIDs = array ( ) ; foreach ( $ vanilla_identifier as $ ForeignID ) { $ HashedForeignID = ForeignIDHash ( $ ForeignID ) ; $ OriginalIDs [ $ HashedForeignID ] = $ ForeignID ; $ RealCacheKey = sprintf ( $ CacheKey , $ HashedForeignID ) ; $ Comments = Gdn :: Cache ( ) -> Get ( $ RealCacheKey ) ; if ( $ Comments !== Gdn_Cache :: CACHEOP_FAILURE ) $ FinalData [ $ ForeignID ] = $ Comments ; else $ Misses [ ] = $ HashedForeignID ; } if ( sizeof ( $ Misses ) ) { $ CountData = Gdn :: SQL ( ) -> Select ( 'ForeignID, CountComments' ) -> From ( 'Discussion' ) -> Where ( 'Type' , 'page' ) -> WhereIn ( 'ForeignID' , $ Misses ) -> Get ( ) -> ResultArray ( ) ; foreach ( $ CountData as $ Row ) { $ ForeignID = $ OriginalIDs [ $ Row [ 'ForeignID' ] ] ; $ FinalData [ $ ForeignID ] = $ Row [ 'CountComments' ] ; $ RealCacheKey = sprintf ( $ CacheKey , $ Row [ 'ForeignID' ] ) ; Gdn :: Cache ( ) -> Store ( $ RealCacheKey , $ Row [ 'CountComments' ] , array ( Gdn_Cache :: FEATURE_EXPIRY => 60 ) ) ; } } $ this -> SetData ( 'CountData' , $ FinalData ) ; $ this -> DeliveryMethod = DELIVERY_METHOD_JSON ; $ this -> DeliveryType = DELIVERY_TYPE_DATA ; $ this -> Render ( ) ; }
Takes a set of discussion identifiers and returns their comment counts in the same order .
42,420
public function Sort ( $ Target = '' ) { if ( ! Gdn :: Session ( ) -> IsValid ( ) ) throw PermissionException ( ) ; if ( ! $ this -> Request -> IsAuthenticatedPostBack ( ) ) throw ForbiddenException ( 'GET' ) ; $ SortField = Gdn :: Request ( ) -> Post ( 'DiscussionSort' ) ; $ SortField = 'd.' . StringBeginsWith ( $ SortField , 'd.' , TRUE , TRUE ) ; if ( ! in_array ( $ SortField , DiscussionModel :: AllowedSortFields ( ) ) ) { throw new Gdn_UserException ( "Unknown sort $SortField." ) ; } Gdn :: UserModel ( ) -> SavePreference ( Gdn :: Session ( ) -> UserID , 'Discussions.SortField' , $ SortField ) ; if ( $ Target ) Redirect ( $ Target ) ; $ this -> DeliveryMethod ( DELIVERY_METHOD_JSON ) ; $ this -> Render ( ) ; }
Set user preference for sorting discussions .
42,421
protected function defineType ( string $ strType ) { switch ( $ strType ) { case 'select' : case 'textarea' : $ this -> strElementType = $ strType ; break ; case 'checkbox' : case 'hidden' : case 'radio' : case 'text' : default : $ this -> strElementType = 'input' ; $ this -> aAttribs [ 'type' ] = $ strType ; break ; } }
Init the HTML element type .
42,422
public function renderInput ( array $ aAttribs = [ ] ) { $ this -> aAttribs += $ aAttribs ; $ strElement = $ this -> isMulti ( ) ? $ this -> renderMulti ( ) : $ this -> renderSingle ( ) ; $ strSuffix = $ this -> strSuffix ? ' ' . $ this -> strSuffix : '' ; return $ strElement . $ strSuffix ; }
Render the input element .
42,423
protected function renderSingle ( ) { $ strHtml = '' ; if ( in_array ( $ this -> getType ( ) , [ 'checkbox' , 'radio' ] ) ) $ strHtml .= '<label class="sked-input-multi">' ; $ strHtml .= '<' . $ this -> strElementType . ' ' . $ this -> renderAttribs ( ) . '>' ; if ( ! empty ( $ this -> aOptions ) ) { $ bLabelIsValue = isset ( $ this -> aOptions [ 0 ] ) ; foreach ( $ this -> aOptions as $ mValue => $ strLabel ) { if ( $ bLabelIsValue ) $ mValue = $ strLabel ; $ strSelected = isset ( $ this -> mValue ) && ( string ) $ this -> mValue === ( string ) $ mValue ? ' selected' : '' ; $ strHtml .= '<option value="' . $ mValue . '"' . $ strSelected . '>' . $ strLabel . '</option>' ; } } elseif ( 'textarea' === $ this -> strElementType ) { $ strHtml .= $ this -> mValue ; } if ( 'input' !== $ this -> strElementType ) $ strHtml .= '</' . $ this -> strElementType . '>' ; if ( in_array ( $ this -> getType ( ) , [ 'checkbox' , 'radio' ] ) ) $ strHtml .= '</label>' ; return $ strHtml ; }
Render a single element .
42,424
protected function renderMulti ( ) { $ strHtml = '' ; $ bLabelIsValue = isset ( $ this -> aOptions [ 0 ] ) ; foreach ( $ this -> aOptions as $ mValue => $ strLabel ) { if ( $ bLabelIsValue ) $ mValue = $ strLabel ; $ strSelected = isset ( $ this -> mValue ) && in_array ( $ strLabel , ( array ) $ this -> mValue ) ? ' checked' : '' ; $ strHtml .= '<label class="sked-input-multi">' . '<input value="' . $ mValue . '" ' . $ this -> renderAttribs ( ) . $ strSelected . '> ' . $ strLabel . '</label>' ; } return $ strHtml ; }
Render multiple related elements .
42,425
public function add ( ) { if ( $ moduleEvents = $ this -> module -> events ( ) ) { $ systemEvents = $ this -> load ( ) ; if ( isset ( $ moduleEvents [ 'listen' ] ) ) foreach ( $ moduleEvents [ 'listen' ] as $ event => $ listens ) { if ( isset ( $ systemEvents [ 'listen' ] [ $ event ] ) ) $ systemEvents [ 'listen' ] [ $ event ] = array_merge ( $ systemEvents [ 'listen' ] [ $ event ] , $ listens ) ; else $ systemEvents [ 'listen' ] [ $ event ] = $ listens ; } if ( isset ( $ moduleEvents [ 'subscribe' ] ) ) $ systemEvents [ 'subscribe' ] [ ] = $ moduleEvents [ 'subscribe' ] ; return $ this -> set ( $ systemEvents ) ; } return true ; }
add events to events . php in cache
42,426
public function remove ( ) { if ( $ moduleEvents = $ this -> module -> events ( ) ) { $ systemEvents = $ this -> load ( ) ; if ( isset ( $ moduleEvents [ 'listen' ] ) ) foreach ( $ moduleEvents [ 'listen' ] as $ event => $ listens ) { if ( isset ( $ systemEvents [ 'listen' ] [ $ event ] ) ) { foreach ( $ listens as $ listen ) { $ key = array_search ( $ listen , $ systemEvents [ 'listen' ] [ $ event ] ) ; if ( $ key !== false ) unset ( $ listen , $ systemEvents [ 'listen' ] [ $ event ] [ $ key ] ) ; } } } if ( isset ( $ moduleEvents [ 'subscribe' ] ) ) { $ key = array_search ( $ moduleEvents [ 'subscribe' ] , $ systemEvents [ 'subscribe' ] [ $ event ] ) ; if ( $ key !== false ) unset ( $ systemEvents [ 'subscribe' ] [ $ key ] ) ; } return $ this -> set ( $ systemEvents ) ; } return true ; }
remove events from system
42,427
public function execute ( Framework $ framework , WebRequest $ request , Response $ response ) { $ this -> setTitle ( $ this -> translate ( 'Generate a new password' , '\\Zepi\\Web\\AccessControl' ) ) ; $ result = $ this -> generateNewPassword ( $ framework , $ request , $ response ) ; $ response -> setOutput ( $ this -> render ( '\\Zepi\\Web\\AccessControl\\Templates\\GenerateNewPasswordFinished' , array ( 'title' => $ this -> getTitle ( ) , 'result' => $ result [ 'result' ] , 'message' => $ result [ 'message' ] ) ) ) ; }
Handles the whole registration process
42,428
protected function generateRandomPassword ( ) { $ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+*=-_/()!?[]{}' ; $ password = array ( ) ; $ alphabetLength = strlen ( $ alphabet ) - 1 ; for ( $ i = 0 ; $ i < 10 ; $ i ++ ) { $ charIndex = mt_rand ( 0 , $ alphabetLength ) ; $ password [ ] = $ alphabet [ $ charIndex ] ; } $ password = implode ( '' , $ password ) ; if ( ! preg_match ( '/\d/' , $ password ) ) { $ password = mt_rand ( 0 , 9 ) . $ password . mt_rand ( 0 , 9 ) ; } return $ password ; }
Generates a new random password
42,429
public function setObject ( $ object ) { if ( ! is_object ( $ object ) ) { throw new InvalidArgumentException ( 'Expected an object, but got ' . gettype ( $ object ) ) ; } $ this -> object = new ReflectionClass ( $ object ) ; }
Set the object you want to work with .
42,430
public function property ( $ name ) { if ( ! $ this -> object -> hasProperty ( $ name ) ) { throw new UnexpectedValueException ( "Property {$name} does not exist" ) ; } return $ this -> extractComment ( $ this -> object -> getProperty ( $ name ) ) ; }
Fetch a property comment .
42,431
public function properties ( $ filter = null ) { if ( is_null ( $ filter ) ) { $ properties = $ this -> object -> getProperties ( ) ; } else { $ properties = $ this -> object -> getProperties ( $ filter ) ; } return array_map ( [ $ this , 'extractComment' ] , $ properties ) ; }
Get the comments for all properties .
42,432
public function method ( $ name ) { if ( ! $ this -> object -> hasMethod ( $ name ) ) { throw new UnexpectedValueException ( "Method {$name} does not exist" ) ; } return $ this -> extractComment ( $ this -> object -> getMethod ( $ name ) ) ; }
Get the method comment .
42,433
public function methods ( $ filter = null ) { if ( is_null ( $ filter ) ) { $ methods = $ this -> object -> getMethods ( ) ; } else { $ methods = $ this -> object -> getMethods ( $ filter ) ; } return array_map ( [ $ this , 'extractComment' ] , $ methods ) ; }
Get the comments for all methods .
42,434
public function indexAction ( ) { $ em = $ this -> getDoctrine ( ) -> getManager ( ) ; $ rootName = $ this -> container -> getParameter ( 'flowcode_news.root_category' ) ; $ root = $ em -> getRepository ( 'AmulenClassificationBundle:Category' ) -> findOneBy ( array ( "name" => $ rootName ) ) ; $ entities = $ em -> getRepository ( 'AmulenClassificationBundle:Category' ) -> getChildren ( $ root ) ; return array ( 'entities' => $ entities , 'rootcategory' => $ root , ) ; }
Lists all Category entities .
42,435
public function childrensAction ( $ id ) { $ em = $ this -> getDoctrine ( ) -> getManager ( ) ; $ parent = $ em -> getRepository ( 'AmulenClassificationBundle:Category' ) -> findOneBy ( array ( "id" => $ id ) ) ; $ childrens = $ em -> getRepository ( 'AmulenClassificationBundle:Category' ) -> getChildren ( $ parent , true ) ; return array ( 'entities' => $ childrens , 'parent' => $ parent , ) ; }
Select parent .
42,436
private function createDeleteForm ( $ id ) { return $ this -> createFormBuilder ( ) -> setAction ( $ this -> generateUrl ( 'admin_news_category_delete' , array ( 'id' => $ id ) ) ) -> setMethod ( 'DELETE' ) -> add ( 'submit' , 'submit' , array ( 'label' => 'Delete' , 'attr' => array ( 'onclick' => 'return confirm("Estás seguro?")' ) ) ) -> getForm ( ) ; }
Creates a form to delete a Category entity by id .
42,437
protected function parseFilters ( $ filters ) { $ beforeFilter = array ( ) ; $ afterFilter = array ( ) ; if ( isset ( $ filters [ Route :: BEFORE ] ) ) { $ beforeFilter = array_intersect_key ( $ this -> filters , array_flip ( ( array ) $ filters [ Route :: BEFORE ] ) ) ; } if ( isset ( $ filters [ Route :: AFTER ] ) ) { $ afterFilter = array_intersect_key ( $ this -> filters , array_flip ( ( array ) $ filters [ Route :: AFTER ] ) ) ; } return array ( $ beforeFilter , $ afterFilter ) ; }
Normalise the array filters attached to the route and merge with any global filters .
42,438
protected function dispatchRoute ( $ httpMethod , $ uri ) { if ( isset ( $ this -> staticRouteMap [ $ uri ] ) ) { return $ this -> dispatchStaticRoute ( $ httpMethod , $ uri ) ; } return $ this -> dispatchVariableRoute ( $ httpMethod , $ uri ) ; }
Perform the route dispatching . Check static routes first followed by variable routes .
42,439
protected function dispatchStaticRoute ( $ httpMethod , $ uri ) { $ routes = $ this -> staticRouteMap [ $ uri ] ; if ( ! isset ( $ routes [ $ httpMethod ] ) ) { $ httpMethod = $ this -> checkFallbacks ( $ routes , $ httpMethod ) ; } return $ routes [ $ httpMethod ] ; }
Handle the dispatching of static routes .
42,440
protected function dispatchVariableRoute ( $ httpMethod , $ uri ) { foreach ( $ this -> variableRouteData as $ data ) { if ( ! preg_match ( $ data [ 'regex' ] , $ uri , $ matches ) ) { continue ; } $ count = count ( $ matches ) ; while ( ! isset ( $ data [ 'routeMap' ] [ $ count ++ ] ) ) { ; } $ routes = $ data [ 'routeMap' ] [ $ count - 1 ] ; if ( ! isset ( $ routes [ $ httpMethod ] ) ) { $ httpMethod = $ this -> checkFallbacks ( $ routes , $ httpMethod ) ; } foreach ( array_values ( $ routes [ $ httpMethod ] [ 2 ] ) as $ i => $ varName ) { if ( ! isset ( $ matches [ $ i + 1 ] ) || $ matches [ $ i + 1 ] === '' ) { unset ( $ routes [ $ httpMethod ] [ 2 ] [ $ varName ] ) ; } else { $ routes [ $ httpMethod ] [ 2 ] [ $ varName ] = $ matches [ $ i + 1 ] ; } } return $ routes [ $ httpMethod ] ; } throw new HttpRouteNotFoundException ( 'Route ' . $ uri . ' does not exist' ) ; }
Handle the dispatching of variable routes .
42,441
public function find ( int $ iId ) { $ oSelect = $ this -> oConnector -> prepare ( 'SELECT * FROM sked_events WHERE id = :id' ) ; if ( ! $ oSelect -> execute ( [ ':id' => $ iId ] ) ) throw new \ Exception ( __METHOD__ . ' - ' . $ oSelect -> errorInfo ( ) [ 2 ] ) ; return $ oSelect -> fetch ( \ PDO :: FETCH_ASSOC ) ; }
Retrieve an event from the database .
42,442
protected function queryDay ( string $ strDateStart , string $ strDateEnd ) { $ strQuery = $ this -> querySelectFrom ( $ strDateStart ) . $ this -> queryJoin ( ) . $ this -> queryWhereNotExpired ( ) ; $ strQuery .= ' AND (' ; $ strQuery .= ' sked_events.starts_at BETWEEN :date_start AND :date_end' ; $ strQuery .= ' OR (sked_events.starts_at <= :date_start AND (' ; $ strQuery .= ' ( sked_events.interval = "1" AND ( DATEDIFF( :date_start_NOTIME, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d") )/sked_events.frequency ) % 1 =0 )' ; $ strQuery .= ' OR ( sked_events.interval = "7" AND sked_events.' . date ( 'D' , strtotime ( $ strDateStart ) ) . ' = 1 AND ( DATEDIFF( :date_start_NOTIME, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d") )/7 ) % sked_events.frequency = 0 )' ; $ strQuery .= ' OR ( sked_events.interval = "Monthly" AND sked_events.' . date ( 'D' , strtotime ( $ strDateStart ) ) . ' = 1 AND TIMESTAMPADD( MONTH, ROUND(DATEDIFF(:date_start, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d"))/30), sked_events.starts_at ) BETWEEN :date_start AND :date_end )' ; $ strQuery .= ' OR ( sked_events.interval = "Monthly" AND sked_events.Mon = 0 AND sked_events.Tue = 0 AND sked_events.Wed = 0 AND sked_events.Thu = 0 AND sked_events.Fri = 0 AND sked_events.Sat = 0 AND sked_events.Sun = 0 AND DAYOFMONTH(sked_events.starts_at) = :date_start_DAYOFMONTH AND (:date_start_YEARMONTH - EXTRACT(YEAR_MONTH FROM sked_events.starts_at)) % sked_events.frequency = 0 )' ; $ strQuery .= '))' ; $ strQuery .= ')' . $ this -> queryGroupAndOrder ( ) ; return $ this -> queryPDO ( $ strQuery , $ this -> aQueryParams + [ ':date_start' => $ strDateStart , ':date_start_NOTIME' => date ( 'Y-m-d' , strtotime ( $ strDateStart ) ) , ':date_start_DAYOFMONTH' => date ( 'd' , strtotime ( $ strDateStart ) ) , ':date_start_YEARMONTH' => date ( 'Ym' , strtotime ( $ strDateStart ) ) , ':date_end' => $ strDateEnd , ] ) ; }
Build the events query for today .
42,443
private function queryPDO ( string $ strQuery , array $ aParams = [ ] ) { $ oStmt = $ this -> oConnector -> prepare ( $ strQuery ) ; if ( ! $ oStmt -> execute ( $ aParams ) ) throw new \ Exception ( __METHOD__ . ' - ' . $ oStmt -> errorInfo ( ) [ 2 ] ) ; list ( $ strMethod ) = explode ( ' ' , trim ( $ strQuery ) ) ; switch ( strtoupper ( $ strMethod ) ) { case 'SELECT' : return $ oStmt -> fetchAll ( \ PDO :: FETCH_ASSOC ) ; break ; case 'INSERT' : return $ this -> oConnector -> lastInsertId ( ) ; break ; case 'UPDATE' : return $ aParams [ ':id_value' ] ; break ; case 'DELETE' : default : return true ; break ; } }
Execute the query with PDO and return results .
42,444
protected function saveEventMembers ( int $ iEventId , array $ aMembers ) { if ( ! empty ( $ aMembers ) ) { $ aExecParams [ ':sked_event_id' ] = $ iEventId ; $ strQuery = 'INSERT IGNORE INTO `sked_event_members` (`sked_event_id`, `member_id`, `owner`, `lead_time`, `created_at`) VALUES ' ; $ aValueSets = [ ] ; foreach ( $ aMembers as $ iMemberId => $ aSettings ) { $ strMemberParam = ':member_id_' . $ iMemberId ; $ strOwnerParam = ':owner_' . $ iMemberId ; $ strLeadTimeParam = ':lead_time_' . $ iMemberId ; $ aValueSets [ ] = '(:sked_event_id, ' . $ strMemberParam . ', ' . $ strOwnerParam . ', ' . $ strLeadTimeParam . ', NOW())' ; $ aExecParams [ $ strMemberParam ] = $ iMemberId ; $ aExecParams [ $ strOwnerParam ] = $ aSettings [ 'owner' ] ?? 0 ; $ aExecParams [ $ strLeadTimeParam ] = $ aSettings [ 'lead_time' ] ?? 0 ; } $ strQuery .= implode ( ',' , $ aValueSets ) . ' ON DUPLICATE KEY UPDATE' . ' `owner` = VALUES(`owner`), `lead_time` = VALUES(`lead_time`)' ; $ this -> queryPDO ( $ strQuery , $ aExecParams ) ; } return true ; }
Persist event member data to the database .
42,445
protected function saveEventTags ( int $ iEventId , array $ aTags ) { $ this -> queryPDO ( 'DELETE FROM `sked_event_tags` WHERE `sked_event_id` = ?' , [ $ iEventId ] ) ; if ( ! empty ( $ aTags ) ) { $ aValueSets = [ ] ; $ aExecParams [ ':sked_event_id' ] = $ iEventId ; $ strQuery = 'INSERT INTO `sked_event_tags` (`sked_event_id`, `tag_id`, `value`, `created_at`) VALUES ' ; foreach ( $ aTags as $ iTagId => $ mTagValue ) { $ strTagParam = ':tag_id_' . $ iTagId ; $ strValueParam = ':value_' . $ iTagId ; $ aValueSets [ ] = '(:sked_event_id, ' . $ strTagParam . ', ' . $ strValueParam . ', NOW())' ; $ aExecParams [ $ strTagParam ] = $ iTagId ; $ aExecParams [ $ strValueParam ] = $ mTagValue ; } $ strQuery .= implode ( ',' , $ aValueSets ) ; $ this -> queryPDO ( $ strQuery , $ aExecParams ) ; } return true ; }
Persist event tag data to the database .
42,446
public function dataFormatoDestino ( $ data , $ formatoDestino ) { $ dataFormatada = false ; if ( ! $ dataFormatada && $ this -> validarDataPorFormato ( $ data , $ this -> FORMATO_DATA_SQL ) ) { $ dataFormatada = $ this -> dataFormatoOrigemDestino ( $ data , $ this -> FORMATO_DATA_SQL , $ formatoDestino ) ; } if ( ! $ dataFormatada && $ this -> validarDataPorFormato ( $ data , $ this -> FORMATO_DATA_HORA_SQL ) ) { $ dataFormatada = $ this -> dataFormatoOrigemDestino ( $ data , $ this -> FORMATO_DATA_HORA_SQL , $ formatoDestino ) ; } if ( ! $ dataFormatada && $ this -> validarDataPorFormato ( $ data , $ this -> FORMATO_DATA_BR ) ) { $ dataFormatada = $ this -> dataFormatoOrigemDestino ( $ data , $ this -> FORMATO_DATA_BR , $ formatoDestino ) ; } if ( ! $ dataFormatada && $ this -> validarDataPorFormato ( $ data , $ this -> FORMATO_DATA_HORA_BR ) ) { $ dataFormatada = $ this -> dataFormatoOrigemDestino ( $ data , $ this -> FORMATO_DATA_HORA_BR , $ formatoDestino ) ; } return $ dataFormatada ; }
Converter uma data identificando o formato origem para o formato destino informado .
42,447
public function dataFormatoOrigemDestino ( $ data , $ formatoOrigem , $ formatoDestino ) { $ data = $ this -> converterParaDateTime ( $ data , $ formatoOrigem ) ; if ( ! $ data ) { return false ; } return ( $ data -> format ( $ formatoDestino ) ) ; }
Converter uma data de um formato origem para um formato destino .
42,448
public function send ( $ mobileNumber , $ message , $ messageId = null ) { return $ this -> app [ 'chikka.sender' ] -> send ( $ mobileNumber , $ message , $ messageId ) ; }
Send capability .
42,449
public function sendAsync ( $ mobileNumber , $ message , $ messageId = null ) { return $ this -> app [ 'chikka.sender' ] -> sendAsync ( $ mobileNumber , $ message , $ messageId ) ; }
Send capability without async .
42,450
public static function getUniqFilename ( $ filename = '' , $ dir = null , $ force_file = true , $ extension = 'txt' ) { if ( empty ( $ filename ) ) { return '' ; } $ extension = trim ( $ extension , '.' ) ; if ( empty ( $ filename ) ) { $ filename = uniqid ( ) ; if ( $ force_file ) $ filename .= '.' . $ extension ; } if ( is_null ( $ dir ) ) { $ dir = defined ( '_DIR_TMP' ) ? _DIR_TMP : '/tmp' ; } $ dir = Directory :: slashDirname ( $ dir ) ; $ _ext = self :: getExtension ( $ filename , true ) ; $ _fname = str_replace ( $ _ext , '' , $ filename ) ; $ i = 0 ; while ( file_exists ( $ dir . $ _fname . $ _ext ) ) { $ _fname .= ( $ i == 0 ? '_' : '' ) . rand ( 10 , 99 ) ; $ i ++ ; } return $ _fname . $ _ext ; }
Returns a filename or directory that does not exist in the destination
42,451
public static function formatFilename ( $ filename = '' , $ lowercase = false , $ delimiter = '-' ) { if ( empty ( $ filename ) ) { return '' ; } $ _ext = self :: getExtension ( $ filename , true ) ; if ( $ _ext ) { $ filename = str_replace ( $ _ext , '' , $ filename ) ; } $ string = $ filename ; if ( $ lowercase ) { $ string = strtolower ( $ string ) ; } $ string = str_replace ( " " , $ delimiter , $ string ) ; $ string = preg_replace ( '#\-+#' , $ delimiter , $ string ) ; $ string = preg_replace ( '#([-]+)#' , $ delimiter , $ string ) ; $ string = trim ( $ string , $ delimiter ) ; $ string = TextHelper :: stripSpecialChars ( $ string , $ delimiter . '.' ) ; if ( $ _ext ) { $ string .= $ _ext ; } return $ string ; }
Formatting file names
42,452
public static function getExtension ( $ filename = '' , $ dot = false ) { if ( empty ( $ filename ) ) { return '' ; } $ exploded_file_name = explode ( '.' , $ filename ) ; return ( strpos ( $ filename , '.' ) ? ( $ dot ? '.' : '' ) . end ( $ exploded_file_name ) : null ) ; }
Returns the extension of a file name
42,453
public static function touch ( $ file_path = null , array & $ logs = array ( ) ) { if ( is_null ( $ file_path ) ) { return null ; } if ( ! file_exists ( $ file_path ) ) { $ target_dir = dirname ( $ file_path ) ; $ ok = ! file_exists ( $ target_dir ) ? Directory :: create ( $ target_dir ) : true ; } else { $ ok = true ; } if ( touch ( $ file_path ) ) { clearstatcache ( ) ; return true ; } else { $ logs [ ] = sprintf ( 'Can not touch file "%s".' , $ file_path ) ; } return false ; }
Create an empty file or touch an existing file
42,454
public static function remove ( $ file_path = null , array & $ logs = array ( ) ) { if ( is_null ( $ file_path ) ) { return null ; } if ( file_exists ( $ file_path ) ) { if ( unlink ( $ file_path ) ) { clearstatcache ( ) ; return true ; } else { $ logs [ ] = sprintf ( 'Can not unlink file "%s".' , $ file_path ) ; } } else { $ logs [ ] = sprintf ( 'File path "%s" does not exist (can not be removed).' , $ file_path ) ; } return false ; }
Remove a file if it exists
42,455
public static function write ( $ file_path = null , $ content , $ type = 'a' , $ force = false , array & $ logs = array ( ) ) { if ( is_null ( $ file_path ) ) { return null ; } if ( ! file_exists ( $ file_path ) ) { if ( true === $ force ) { self :: touch ( $ file_path , $ logs ) ; } else { $ logs [ ] = sprintf ( 'File path "%s" to copy was not found.' , $ file_path ) ; return false ; } } if ( is_writable ( $ file_path ) ) { $ h = fopen ( $ file_path , $ type ) ; if ( false !== fwrite ( $ h , $ content ) ) { fclose ( $ h ) ; return true ; } } $ logs [ ] = sprintf ( 'Can not write in file "%s".' , $ file_path ) ; return false ; }
Write a content in a file
42,456
public function find ( $ primaryKeys ) { if ( is_array ( $ primaryKeys ) ) { $ primaryKeys = reset ( $ primaryKeys ) ; } $ rootId = ( ( int ) $ primaryKeys ) ? : null ; return $ this -> createStructure ( array ( 'rootId' => $ rootId , 'extra' => $ this -> getExtraMapper ( ) -> findByRoot ( $ rootId ) , 'rules' => $ this -> getRuleMapper ( ) -> findAllByRoot ( $ rootId , $ this -> getRuleOrder ( ) ) , ) ) ; }
Find a structure by root paragraph id
42,457
public function findByExtra ( ExtraStructure $ extra ) { $ rootId = $ extra -> rootParagraphId ; return $ this -> createStructure ( array ( 'rootId' => $ rootId , 'extra' => $ extra , 'rules' => $ this -> getRuleMapper ( ) -> findAllByRoot ( $ rootId , $ this -> getRuleOrder ( ) ) , ) ) ; }
Find a structure by its extra structure
42,458
public function toArray ( ) : array { $ this -> setExtractFlags ( self :: EXTR_BOTH ) ; $ data = [ ] ; foreach ( $ this as $ item ) { $ data [ ] = $ item ; } return $ data ; }
Iterates the queue and returns an array containing each item with the data and priority set .
42,459
public function insert ( $ data , $ priority = self :: PIRORITY_DEFAULT ) : void { parent :: insert ( $ data , $ priority ) ; }
Allows inserting data into the queue without explicitly setting a priority value . Inserts without a priority will use the PRIORITY_DEFAULT value .
42,460
public function unserialize ( $ queue ) { foreach ( unserialize ( $ queue ) as $ item ) { $ this -> insert ( $ item [ 'data' ] , $ item [ 'priority' ] ) ; } }
Unserializes the queue .
42,461
public function merge ( self $ queue ) : void { $ data = $ queue -> toArray ( ) ; foreach ( $ data as $ item ) { $ this -> insert ( $ item [ 'data' ] , $ item [ 'priority' ] ) ; } }
Merges the given queue data into this queue .
42,462
public static function display ( array $ assocArgs , ResultCollection $ resultCollection ) : void { $ assocArgs [ 'fields' ] = $ assocArgs [ 'fields' ] ?? self :: DEFAULT_FIELDS ; $ formatter = new Formatter ( $ assocArgs , $ assocArgs [ 'fields' ] ) ; $ formatter -> display_items ( self :: toTable ( $ resultCollection ) , true ) ; }
Display a result collection in a given format .
42,463
private static function toTable ( ResultCollection $ resultCollection ) : array { return array_map ( function ( ResultInterface $ result ) : array { return self :: toRow ( $ result ) ; } , $ resultCollection -> all ( ) ) ; }
Converts the underlying results into a plain PHP array which printable on console tables .
42,464
private static function toRow ( ResultInterface $ result ) : array { $ row = [ 'id' => $ result -> getChecker ( ) -> getId ( ) , 'link' => $ result -> getChecker ( ) -> getLink ( ) , 'description' => $ result -> getChecker ( ) -> getDescription ( ) , 'status' => $ result -> getStatus ( ) , 'messages' => $ result -> getMessages ( ) , ] ; $ row [ 'status' ] = self :: colorize ( $ result , $ row [ 'status' ] ) ; $ row [ 'message' ] = implode ( PHP_EOL , $ row [ 'messages' ] ) ; return $ row ; }
Converts the underlying result into a plain PHP array which printable as console table row .
42,465
private static function colorize ( ResultInterface $ result , string $ text ) : string { $ colors = [ Success :: class => '%G' , Disabled :: class => '%P' , Failure :: class => '%R' , Error :: class => '%1%w' , 'reset' => '%n' , ] ; $ color = $ colors [ get_class ( $ result ) ] ?? $ colors [ 'reset' ] ; return WP_CLI :: colorize ( $ color . $ text . '%n' ) ; }
Colorize a string for output .
42,466
public function header ( $ header , $ value , $ replace = true ) { $ this -> headers [ ] = array ( $ header , $ value , $ replace ) ; }
Sets a response header .
42,467
public function process ( \ SS_HTTPRequest $ request ) { if ( $ identifier = $ request -> param ( 'ID' ) ) { if ( $ this -> currencyService -> setActiveCurrency ( new Identifier ( $ identifier ) ) ) { return [ 'Success' => true ] ; } } return [ 'Success' => false ] ; }
Method to determine how to handle the request . Uses the currency service to set the active currency
42,468
public function run ( array $ input ) { return Std :: foldl ( function ( $ current , TransformInterface $ input ) { return $ input -> run ( $ current ) ; } , $ input , $ this -> transforms ) ; }
Run the input through the pipeline .
42,469
public function subscribe ( $ topicQueueName , callable $ handler ) { $ isSubscriptionLoopActive = true ; while ( $ isSubscriptionLoopActive ) { $ request = new SubscribeMessageRequest ( [ 'queueName' => $ topicQueueName , 'pollingWaitSeconds' => 0 , ] ) ; try { $ message = $ this -> client -> send ( $ request ) ; } catch ( RequestException $ e ) { throw $ e ; } catch ( ResponseException $ e ) { $ message = $ e -> getBody ( ) ; if ( ! $ message -> has ( 'code' ) ) { throw $ e ; } else if ( ! in_array ( $ message -> get ( 'code' ) , [ '7000' , '6070' ] ) ) { throw $ e ; } } catch ( \ Exception $ e ) { throw $ e ; } if ( $ message === null || $ message -> get ( 'msgBody' ) === null ) { sleep ( mt_rand ( 1 , 5 ) ) ; continue ; } call_user_func ( $ handler , Utils :: unserializeMessagePayload ( $ message -> get ( 'msgBody' ) ) , new MessageHandler ( $ this -> client , $ topicQueueName , $ message ) ) ; unset ( $ message ) ; } }
Subscribe a handler to a topic queue .
42,470
public function detectForeignKey ( $ config , $ class ) { $ foreignKey = $ this -> getConfig ( $ config ) ; if ( ! $ foreignKey ) { $ foreignKey = $ this -> buildForeignKey ( $ class ) ; $ this -> setConfig ( $ config , $ foreignKey ) ; } return $ foreignKey ; }
Return a foreign key either for the primary or related model . If no foreign key is defined automatically inflect one and set it .
42,471
public function getPrimaryModel ( ) { if ( $ model = $ this -> _model ) { return $ model ; } $ class = $ this -> getPrimaryClass ( ) ; if ( ! $ class ) { return null ; } $ this -> setPrimaryModel ( new $ class ( ) ) ; return $ this -> _model ; }
Return a primary model object .
42,472
public function getRelatedModel ( ) { if ( $ model = $ this -> _relatedModel ) { return $ model ; } $ class = $ this -> getRelatedClass ( ) ; $ this -> setRelatedModel ( new $ class ( ) ) ; return $ this -> _relatedModel ; }
Return a related model object .
42,473
public function setPrimaryModel ( Model $ model ) { $ this -> _model = $ model ; $ this -> setPrimaryClass ( get_class ( $ model ) ) ; return $ this ; }
Set the primary model object .
42,474
public function setRelatedModel ( Model $ model ) { $ this -> _relatedModel = $ model ; $ this -> setRelatedClass ( get_class ( $ model ) ) ; return $ this ; }
Set the related model object .
42,475
public function setHash ( $ hash ) { if ( ! is_string ( $ hash ) || strlen ( trim ( $ hash ) ) == 0 ) throw new InvalidArgumentException ( __METHOD__ . '; Invalid hash, must be a non empty string' ) ; $ this -> hash = $ hash ; }
Set hash of this User
42,476
public function publish ( ) { if ( ! $ this -> console instanceof Command ) { $ message = "The 'console' property must instance of \\Illuminate\\Console\\Command." ; throw new \ RuntimeException ( $ message ) ; } if ( ! $ this -> getFilesystem ( ) -> isDirectory ( $ sourcePath = $ this -> getSourcePath ( ) ) ) { return ; } if ( ! $ this -> getFilesystem ( ) -> isDirectory ( $ destinationPath = $ this -> getDestinationPath ( ) ) ) { $ this -> getFilesystem ( ) -> makeDirectory ( $ destinationPath , 0775 , true ) ; } if ( $ this -> getFilesystem ( ) -> copyDirectory ( $ sourcePath , $ destinationPath ) ) { if ( $ this -> showMessage === true ) { $ this -> console -> line ( "<info>Published</info>: {$this->component->getStudlyName()}" ) ; } } else { $ this -> console -> error ( $ this -> error ) ; } }
Publish something .
42,477
public function save ( array $ answers ) { $ path = $ this -> directory . DIRECTORY_SEPARATOR . $ this -> file ; if ( ! file_exists ( $ path ) ) { if ( ! is_writable ( $ this -> directory ) ) { throw new WritableException ( sprintf ( 'The env file is not present and the directory `%s` is not writeable!' , $ this -> directory ) ) ; } touch ( $ path ) ; } if ( ! is_writable ( $ path ) ) { throw new WritableException ( sprintf ( 'The env file `%s` is not writeable!' , $ path ) ) ; } $ text = '' ; foreach ( $ answers as $ key => $ value ) { $ text .= sprintf ( "%s=%s\n" , $ key , $ value ) ; } file_put_contents ( $ path , $ text ) ; }
Save the given answers to the env file .
42,478
public function getCalls ( ) { if ( null == $ this -> calls ) { $ this -> calls = $ this -> extractCalls ( ) ; } return $ this -> calls ; }
Get the direct calls object .
42,479
public function extractCalls ( ) { $ calls = array ( ) ; if ( 'form' == $ this -> callType ) { $ calls [ ] = new Call ( $ this -> post , 'form' ) ; } else { $ decoded = json_decode ( $ this -> rawPost ) ; $ decoded = ! is_array ( $ decoded ) ? array ( $ decoded ) : $ decoded ; array_walk_recursive ( $ decoded , array ( $ this , 'parseRawToArray' ) ) ; if ( $ this -> requestDecode ) array_walk_recursive ( $ decoded , array ( $ this , 'decode' ) ) ; foreach ( $ decoded as $ call ) { $ calls [ ] = new Call ( ( array ) $ call , 'single' ) ; } } return $ calls ; }
Extract the ExtDirect calls from request .
42,480
private function parseRawToArray ( & $ value , & $ key ) { if ( is_string ( $ value ) ) { $ pos = substr ( $ value , 0 , 1 ) ; if ( $ pos == '[' || $ pos == '(' || $ pos == '{' ) { $ json = json_decode ( $ value ) ; } else { $ json = $ value ; } $ pos = substr ( $ value , 0 , 1 ) ; if ( $ pos == '[' || $ pos == '(' || $ pos == '{' ) { $ json = json_decode ( $ value ) ; } else { $ json = $ value ; } if ( $ json ) { $ value = $ json ; } } if ( is_object ( $ value ) ) { $ value = ( array ) $ value ; } if ( is_array ( $ value ) ) { array_walk_recursive ( $ value , array ( $ this , 'parseRawToArray' ) ) ; } }
Parse a raw http post to a php array .
42,481
public function run ( ) { $ process = $ this -> getProcessExecutor ( ) ; $ process -> setCommandLine ( $ this -> getCommand ( ) ) ; $ logger = function ( $ error , $ line ) { call_user_func_array ( array ( $ this , 'logLine' ) , array ( $ error , $ line ) ) ; } ; return $ process -> run ( $ logger ) ; }
executes the command .
42,482
protected function logLine ( $ messageType , $ messageText ) { switch ( $ messageType ) { case Process :: ERR : $ typeStr = "[Error]" ; break ; default : $ typeStr = "" ; break ; } echo sprintf ( "\n%s %s\n" , $ typeStr , $ messageText ) ; }
logs a line from the command output
42,483
public function postPersist ( LifecycleEventArgs $ args ) { if ( $ args -> getObject ( ) instanceof CommitInterface ) { $ this -> dispatcher -> dispatch ( NewCommitEvent :: NAME , new NewCommitEvent ( $ args -> getObject ( ) ) ) ; } elseif ( $ args -> getObject ( ) instanceof BranchInterface ) { $ this -> dispatcher -> dispatch ( NewBranchEvent :: NAME , new NewBranchEvent ( $ args -> getObject ( ) ) ) ; } }
Handles postPersist event triggered by doctrine .
42,484
public static function serializeAttr ( array $ data , array $ order = [ ] ) { $ attr = [ ] ; $ sorted = static :: sortedAttr ( $ data , $ order ) ; foreach ( $ sorted as list ( $ key , $ value ) ) { if ( is_array ( $ value ) ) { if ( count ( $ value ) === 0 ) { continue ; } foreach ( static :: _serializeAttrArray ( $ key , $ value ) as $ sub ) { $ value = htmlspecialchars ( $ sub [ 1 ] , ENT_QUOTES | ENT_HTML5 ) ; $ attr [ ] = "{$sub[0]}=\"{$value}\"" ; } } else { if ( $ value === true ) { $ attr [ ] = "$key" ; } else if ( $ value === false ) { } else { $ value = htmlspecialchars ( $ value , ENT_QUOTES | ENT_HTML5 ) ; $ attr [ ] = "$key=\"$value\"" ; } } } return implode ( ' ' , $ attr ) ; }
Takes key - value array and serializes them to a string as key = value foo = bar .
42,485
public static function fromString ( $ constraintExpression ) { if ( ! preg_match ( '/^(==?|\!=?|~|[<>]=?)?((?:\*|[0-9]+)(?:.(?:\*|[0-9]+))*)(?:\@(\w+))?$/' , $ constraintExpression , $ m ) ) { throw new \ InvalidArgumentException ( "Constraint expression '$constraintExpression' could not be parsed" ) ; } return new self ( ! empty ( $ m [ 1 ] ) ? $ m [ 1 ] : '=' , $ m [ 2 ] , ! empty ( $ m [ 3 ] ) ? $ m [ 3 ] : 'stable' ) ; }
Construct a Constraint instance based on the passed string constraint .
42,486
public function match ( Version $ version ) { $ versionStabilityIndex = array_search ( $ version -> getStability ( ) , Version :: $ stabilities ) ; $ constraintStabilityIndex = array_search ( $ this -> stability , Version :: $ stabilities ) ; if ( $ this -> compare ( $ versionStabilityIndex , $ constraintStabilityIndex ) !== 0 ) { return false ; } $ numericValues = $ version -> numeric ( ) ; $ comparisons = array ( ) ; foreach ( $ this -> version as $ i => $ value ) { $ comparisons [ $ i ] = $ this -> compare ( $ numericValues [ $ i ] , $ value ) ; } switch ( $ this -> operator ) { case '=' : case '==' : return array_filter ( $ comparisons ) === array ( ) ; break ; case '!' : case '!=' : return array_filter ( $ comparisons ) !== array ( ) ; break ; case '>=' : case '<=' : case '>' : case '<' : $ mismatches = array_filter ( $ comparisons ) ; if ( ! count ( $ mismatches ) ) { return in_array ( $ this -> operator , array ( '<=' , '>=' ) ) ; } else { $ first = array_shift ( $ mismatches ) ; return ( $ this -> operator === '<' && $ first < 0 ) || ( $ this -> operator === '<=' && $ first < 0 ) || ( $ this -> operator === '>' && $ first > 0 ) || ( $ this -> operator === '>=' && $ first > 0 ) ; } } throw new \ UnexpectedValueException ( "An unknown edge case was encountered. Is the constraint valid?" ) ; }
Match the constraint against the passed version .
42,487
public function setAttribute ( $ attr , $ value ) { if ( strpos ( $ attr , 'data-' ) === 0 || in_array ( $ attr , $ this -> validAttributes ) ) { $ this -> attrs [ $ attr ] = $ value ; } else { throw new Exception \ InvalidAttributeException ( $ attr ) ; } }
Sets an attribute given the name and value .
42,488
public function getAttribute ( $ name ) { if ( key_exists ( $ name , $ this -> attrs ) ) { return $ this -> attrs [ $ name ] ; } else { return null ; } }
Gets an attribute given the attribute name .
42,489
public function getHTML ( ) { $ tag = "<" . $ this -> name ; $ q = $ this -> quoteType ; foreach ( $ this -> attrs as $ name => $ value ) { if ( $ value === true ) { $ tag .= " $name" ; } else if ( is_string ( $ value ) ) { $ tag .= " {$name}={$q}{$value}{$q}" ; } } if ( $ this -> isShortTag ) { $ tag .= ' />' ; return $ tag ; } $ tag .= '>' ; if ( $ this -> hasChildren ( ) ) { foreach ( $ this -> getChildren ( ) as $ child ) { $ tag .= $ child -> getHTML ( ) ; } } $ tag .= "</{$this->name}>" ; return $ tag ; }
Parses the class data and outputs the HTML .
42,490
public function setQuote ( $ type ) { $ this -> quoteType = $ quoteType == self :: SINGLE_QUOTE ? self :: SINGLE_QUOTE : self :: DOUBLE_QUOTE ; }
Sets the type of quote to use . Default quote type is double quotes .
42,491
protected function addValidAttributes ( $ attrs ) { foreach ( $ attrs as $ attr ) { if ( is_string ( $ attr ) ) { $ this -> validAttributes [ ] = $ attr ; } } }
Adds array of attributes to the valid attributes .
42,492
private function _formatOrder ( ) { $ orders = array ( ) ; if ( isset ( $ this -> _order [ DbInterface :: ORDER_RAND ] ) ) { $ orders [ ] = 'RAND()' ; } else { foreach ( $ this -> _order as $ field => $ order ) { $ orders [ ] = "`$field` $order" ; } } return ' ORDER BY ' . implode ( ', ' , $ orders ) ; }
Format the order fields to be included into the query .
42,493
private function _doQuery ( $ pLimitOne ) { try { if ( empty ( $ this -> _fields ) ) { $ fields = '*' ; } else { $ fields = '`' . implode ( '`, `' , $ this -> _fields ) . '`' ; } $ query = " SELECT $fields FROM `" . $ this -> getDbPrefix ( ) . $ this -> _dbContainer . "`" ; if ( $ this -> _conditions -> count ( ) ) { $ query .= " WHERE " . $ this -> _conditions -> getPreparedConditions ( $ this -> _dbContainer ) . "" ; } if ( ! empty ( $ this -> _order ) ) { $ query .= $ this -> _formatOrder ( ) ; } if ( $ pLimitOne ) { $ query .= ' LIMIT 0, 1' ; } else if ( $ this -> _limit !== NULL or $ this -> _skip !== NULL ) { $ query .= $ this -> _formatLimit ( ) ; } $ this -> _stm = Agl :: app ( ) -> getDb ( ) -> getConnection ( ) -> prepare ( $ query , array ( PDO :: ATTR_CURSOR , PDO :: CURSOR_SCROLL ) ) ; if ( ! $ this -> _stm -> execute ( $ this -> _conditions -> getPreparedValues ( ) ) ) { $ error = $ this -> _stm -> errorInfo ( ) ; throw new Exception ( "The select query failed (table '" . $ this -> getDbPrefix ( ) . $ this -> _dbContainer . "') with message '" . $ error [ 2 ] . "'" ) ; } if ( Agl :: app ( ) -> isDebugMode ( ) ) { Agl :: app ( ) -> getDb ( ) -> incrementCounter ( ) ; } return $ this ; } catch ( Exception $ e ) { throw new Exception ( $ e ) ; } }
Commit the select query to the database .
42,494
public function fetchAll ( $ pSingle = false ) { if ( $ this -> _stm === false ) { return array ( ) ; } if ( $ pSingle ) { return $ this -> _stm -> fetch ( PDO :: FETCH_ASSOC ) ; } return $ this -> _stm -> fetchAll ( PDO :: FETCH_ASSOC ) ; }
Fetch all the results as array .
42,495
public function fetchAllAsItems ( $ pSingle = false ) { $ data = array ( ) ; if ( $ this -> _stm === false ) { return $ data ; } while ( $ row = $ this -> _stm -> fetch ( PDO :: FETCH_ASSOC ) ) { if ( $ pSingle ) { return Agl :: getModel ( $ this -> _dbContainer , $ row ) ; } $ data [ ] = Agl :: getModel ( $ this -> _dbContainer , $ row ) ; } return $ data ; }
Fetch all the results as array of items .
42,496
public function add ( $ key , $ value ) { if ( ! array_key_exists ( $ key , $ this -> attributes ) ) { $ this -> attributes [ $ key ] = $ value ; } else { if ( ! \ is_array ( $ this -> attributes [ $ key ] ) ) { $ this -> attributes [ $ key ] = array ( $ this -> attributes [ $ key ] , $ value ) ; } else { $ this -> attributes [ $ key ] [ ] = $ value ; } } }
Add to an new or existing value . This will promote scalar values into an array to contain multiple values .
42,497
public function getAttributes ( ) { if ( $ this -> cachedAttributes != null ) { return $ this -> cachedAttributes ; } $ entries = $ this -> _queryAssertion ( '/saml:AttributeStatement/saml:Attribute' ) ; $ this -> cachedAttributes = array ( ) ; foreach ( $ entries as $ entry ) { $ attributeName = $ entry -> attributes -> getNamedItem ( 'Name' ) -> nodeValue ; foreach ( $ entry -> childNodes as $ childNode ) { if ( is_a ( $ childNode , 'DOMElement' ) && preg_match ( '/AttributeValue/' , $ childNode -> tagName ) ) { $ attributeValue = $ childNode -> nodeValue ; } } $ this -> cachedAttributes [ $ attributeName ] = $ attributeValue ; } return $ this -> cachedAttributes ; }
Return the attributes of a SAML response
42,498
public function getFormattedQuestion ( $ question , $ default , array $ options ) { if ( $ this -> isList ( $ options ) ) { return $ this -> getFormattedListQuestion ( $ question , $ default , $ options ) ; } else { return $ this -> getFormattedSimpleQuestion ( $ question , $ default , $ options ) ; } }
Get formatted question
42,499
protected function getFormattedListQuestion ( $ question , $ default , array $ options ) { $ list = '' ; foreach ( $ options as $ key => $ title ) { $ list .= " $key - $title" . ( $ default == $ key ? ' (Default)' : '' ) . PHP_EOL ; } return $ question . ":\n" . $ list ; }
Get formatted list question