idx
int64
0
60.3k
question
stringlengths
92
4.62k
target
stringlengths
7
635
16,300
private function assertHttpMethod ( $ method ) { if ( ! $ this -> assertString ( $ method ) ) return false ; $ validHttpMethods = array ( 'GET' , 'POST' , 'PUT' , 'DELETE' , 'HEAD' , 'OPTIONS' , 'TRACE' , 'CONNECT' , 'PATCH' , 'LINK' , 'UNLINK' ) ; if ( ! in_array ( $ method , $ validHttpMethods ) ) return false ; retu...
asserts a http method
16,301
static public function getInstance ( ) { if ( ! isset ( self :: $ _instance ) ) { if ( ! sfConfig :: get ( 'app_amg_sentry_dsn' ) ) { throw new Exception ( 'Please configure amgSentryPlugin in your app.yml (use model in "amgSentryPlugin/config/app.yml")' ) ; } self :: $ _instance = new amgSentry ( sfConfig :: get ( 'ap...
Retrieves the singleton instance of this class .
16,302
static public function sendMessage ( $ title , $ description = '' , $ level = self :: INFO ) { if ( ! sfConfig :: get ( 'app_amg_sentry_enabled' , false ) ) { return true ; } return self :: getInstance ( ) -> captureMessage ( $ title , array ( 'description' => $ description ) , $ level ) ; }
Send a message to Sentry .
16,303
static public function sendException ( $ exception , $ description = '' ) { if ( ! sfConfig :: get ( 'app_amg_sentry_enabled' , false ) ) { return true ; } return self :: getInstance ( ) -> captureException ( $ exception , $ description ) ; }
Send an exception to Sentry .
16,304
protected function _getSentryLevelFromLoggerPriority ( $ priority ) { switch ( $ priority ) { case self :: EMERG : case self :: ALERT : case self :: CRIT : return amgSentry :: FATAL ; case self :: ERR : return amgSentry :: ERROR ; case self :: WARNING : return amgSentry :: WARNING ; case self :: NOTICE : case self :: I...
Map symfony logger error priority to Sentry level .
16,305
public function setProtectionPolicy ( $ protectionPolicy ) { if ( $ protectionPolicy !== GuardInterface :: POLICY_ALLOW && $ protectionPolicy !== GuardInterface :: POLICY_DENY ) { throw new Exception \ RuntimeException ( sprintf ( 'An invalid protection policy was set. Can only be "deny" or "allow", "%s" given' , $ pro...
Set the protection policy for guards
16,306
public function compileGin ( Blueprint $ blueprint , Fluent $ command ) { $ columns = $ this -> columnize ( $ command -> columns ) ; return sprintf ( 'CREATE INDEX %s ON %s USING GIN(%s)' , $ command -> index , $ this -> wrapTable ( $ blueprint ) , $ columns ) ; }
Compile a gin index key command .
16,307
public function compileCreate ( BaseBlueprint $ blueprint , Fluent $ command ) { $ sql = parent :: compileCreate ( $ blueprint , $ command ) ; if ( isset ( $ blueprint -> inherits ) ) { $ sql .= ' INHERITS ("' . $ blueprint -> inherits . '")' ; } return $ sql ; }
Compile create table query .
16,308
public function isGranted ( $ permission , $ context = null ) { $ roles = $ this -> roleService -> getIdentityRoles ( ) ; if ( empty ( $ roles ) ) { return false ; } if ( ! $ this -> rbac -> isGranted ( $ roles , $ permission ) ) { return false ; } if ( $ this -> hasAssertion ( $ permission ) ) { return $ this -> asser...
Check if the permission is granted to the current identity
16,309
protected function getRole ( $ roleName ) { if ( isset ( $ this -> roles [ $ roleName ] ) ) { return $ this -> roles [ $ roleName ] ; } if ( ! isset ( $ this -> rolesConfig [ $ roleName ] ) ) { $ role = new Role ( $ roleName ) ; $ this -> roles [ $ roleName ] = $ role ; return $ role ; } $ roleConfig = $ this -> rolesC...
Get role by role name
16,310
public function getIdentityRoles ( ) { if ( ! $ identity = $ this -> getIdentity ( ) ) { return $ this -> convertRoles ( [ $ this -> guestRole ] ) ; } if ( ! $ identity instanceof IdentityInterface ) { throw new Exception \ RuntimeException ( sprintf ( 'ZfcRbac expects your identity to implement ZfcRbac\Identity\Identi...
Get the identity roles from the current identity applying some more logic
16,311
protected function flattenRoles ( array $ roles ) { $ roleNames = [ ] ; $ iterator = $ this -> traversalStrategy -> getRolesIterator ( $ roles ) ; foreach ( $ iterator as $ role ) { $ roleNames [ ] = $ role -> getName ( ) ; } return array_unique ( $ roleNames ) ; }
Flatten an array of role with role names
16,312
protected function provideUuidKey ( $ model ) { if ( $ model -> incrementing === false ) { $ key = $ model -> getKeyName ( ) ; if ( empty ( $ model -> $ key ) ) { $ model -> $ key = ( string ) Uuid :: uuid4 ( ) ; } } else { throw new RuntimeException ( sprintf ( '$incrementing must be false on class "%s" to support uui...
Provide a UUID
16,313
public function setRules ( array $ rules ) { $ this -> rules = [ ] ; foreach ( $ rules as $ rule ) { $ controller = strtolower ( $ rule [ 'controller' ] ) ; $ actions = isset ( $ rule [ 'actions' ] ) ? ( array ) $ rule [ 'actions' ] : [ ] ; $ permissions = ( array ) $ rule [ 'permissions' ] ; if ( empty ( $ actions ) )...
Set the rules
16,314
private function collectIdentityRolesAndPermissions ( RoleService $ roleService ) { $ identityRoles = $ roleService -> getIdentityRoles ( ) ; foreach ( $ identityRoles as $ role ) { $ roleName = $ role -> getName ( ) ; if ( ! $ role instanceof HierarchicalRoleInterface ) { $ this -> collectedRoles [ ] = $ roleName ; } ...
Collect roles and permissions
16,315
private function collectPermissions ( RoleInterface $ role ) { if ( method_exists ( $ role , 'getPermissions' ) ) { $ permissions = $ role -> getPermissions ( ) ; } else { $ reflectionProperty = new ReflectionProperty ( $ role , 'permissions' ) ; $ reflectionProperty -> setAccessible ( true ) ; $ permissions = $ reflec...
Collect permissions for the given role
16,316
public function getHTMLFragments ( $ gridField ) { $ singleton = singleton ( $ gridField -> getModelClass ( ) ) ; if ( ! $ singleton -> canCreate ( ) ) { return array ( ) ; } if ( ! $ this -> buttonName ) { $ objectName = $ singleton -> i18n_singular_name ( ) ; $ this -> buttonName = _t ( 'GridField.Add' , 'Add {name}'...
Overriding the parent method to change the template that the DMS add button will be rendered with
16,317
private function validateResponse ( $ response ) { if ( $ response -> getStatusCode ( ) !== 200 ) { $ statusCode = $ response -> getStatusCode ( ) ; throw new ServerException ( 'Server responded with HTTP status ' . $ statusCode , $ statusCode ) ; } else if ( strpos ( $ response -> getHeader ( 'Content-Type' ) [ 0 ] , ...
Validate the HTTP response and throw exceptions on errors
16,318
private function parse ( ) { $ data = json_decode ( $ this -> httpResponse -> getBody ( ) , true ) ; foreach ( $ data [ 'messages' ] as $ message ) { $ msg = new Message ( $ message ) ; $ this -> messages [ ] = $ msg ; if ( $ message [ 'type' ] === 'error' || $ message [ 'type' ] === 'non-document-error' ) { $ this -> ...
Parse the received response into a usable format
16,319
public function format ( $ useHTML = false ) { $ msgs = array ( ) ; foreach ( $ this -> messages as $ msg ) { $ msgs [ ] = $ msg -> format ( $ useHTML ) ; } return implode ( PHP_EOL . PHP_EOL , $ msgs ) ; }
Returns a string - representation of all messages encountered
16,320
public static function create_version ( DMSDocument $ doc ) { $ success = false ; $ existingPath = $ doc -> getFullPath ( ) ; if ( is_file ( $ existingPath ) ) { $ docData = $ doc -> toMap ( ) ; unset ( $ docData [ 'ID' ] ) ; $ version = new DMSDocument_versions ( $ docData ) ; $ previousVersionCounter = 0 ; $ newestEx...
Creates a new version of a document by moving the current file and renaming it to the versioned filename .
16,321
public function getFullPath ( $ filename = null ) { if ( ! $ filename ) { $ filename = $ this -> Filename ; } return DMS :: inst ( ) -> getStoragePath ( ) . DIRECTORY_SEPARATOR . $ this -> Folder . DIRECTORY_SEPARATOR . $ filename ; }
Returns the full filename of the document stored in this object . Can optionally specify which filename to use at the end .
16,322
protected function generateVersionedFilename ( DMSDocument $ doc , $ versionCounter ) { $ filename = $ doc -> Filename ; do { $ versionPaddingString = str_pad ( $ versionCounter , 4 , '0' , STR_PAD_LEFT ) ; $ newVersionFilename = preg_replace ( '/([0-9]+~)(.*?)/' , '$1~' . $ versionPaddingString . '~$2' , $ filename ) ...
Creates a new filename for the current Document s file when replacing the current file with a new file .
16,323
public function getAllDocuments ( ) { $ documents = ArrayList :: create ( ) ; foreach ( $ this -> owner -> DocumentSets ( ) as $ documentSet ) { $ documents -> merge ( $ documentSet -> getDocuments ( ) ) ; } $ documents -> removeDuplicates ( ) ; return $ documents ; }
Get a list of all documents from all document sets for the owner page
16,324
protected function addRequirements ( ) { Requirements :: javascript ( DMS_DIR . '/javascript/DMSGridField.js' ) ; Requirements :: css ( DMS_DIR . '/dist/css/dmsbundle.css' ) ; Requirements :: javascript ( DMS_DIR . '/javascript/DocumentHtmlEditorFieldToolbar.js' ) ; return $ this ; }
Add required CSS and Javascript requirements for managing documents
16,325
public function addQueryFields ( $ fields ) { $ doc = singleton ( 'DMSDocument' ) ; $ dmsDocFields = $ doc -> scaffoldSearchFields ( array ( 'fieldClasses' => true ) ) ; $ membersMap = Member :: get ( ) -> map ( 'ID' , 'Name' ) -> toArray ( ) ; asort ( $ membersMap ) ; foreach ( $ dmsDocFields as $ field ) { if ( $ fie...
Adds the query fields to build the document logic to the DMSDocumentSet .
16,326
public function saveLinkedDocuments ( ) { if ( empty ( $ this -> KeyValuePairs ) || ! $ this -> isChanged ( 'KeyValuePairs' ) ) { return ; } $ keyValuesPair = Convert :: json2array ( $ this -> KeyValuePairs ) ; $ dmsDoc = singleton ( 'DMSDocument' ) ; $ context = $ dmsDoc -> getDefaultSearchContext ( ) ; $ sortBy = $ t...
Retrieve a list of the documents in this set . An extension hook is provided before the result is returned .
16,327
protected function addQueryBuilderSearchResults ( DataList $ documents ) { $ originals = $ this -> Documents ( ) ; $ originals -> removeByFilter ( '"ManuallyAdded" = 0' ) ; foreach ( $ documents as $ document ) { $ originals -> add ( $ document , array ( 'ManuallyAdded' => 0 ) ) ; } return $ originals ; }
Remove all ManuallyAdded = 0 original results and add in the new documents returned by the search context
16,328
public function trackView ( ) { if ( $ this -> ID > 0 ) { $ count = $ this -> ViewCount + 1 ; $ this -> ViewCount = $ count ; DB :: query ( "UPDATE \"DMSDocument\" SET \"ViewCount\"='$count' WHERE \"ID\"={$this->ID}" ) ; $ this -> extend ( 'trackView' ) ; } return $ this ; }
Increase ViewCount by 1 without update any other record fields such as LastEdited .
16,329
public function getLink ( ) { $ urlSegment = sprintf ( '%d-%s' , $ this -> ID , URLSegmentFilter :: create ( ) -> filter ( $ this -> getTitle ( ) ) ) ; $ result = Controller :: join_links ( Director :: baseURL ( ) , 'dmsdocument/' . $ urlSegment ) ; if ( ! $ this -> canView ( ) ) { $ result = sprintf ( "javascript:aler...
Returns a link to download this document from the DMS store . Alternatively a basic javascript alert will be shown should the user not have view permissions . An extension point for this was also added .
16,330
public function embargoUntilPublished ( $ write = true ) { $ this -> EmbargoedUntilPublished = true ; if ( $ write ) { $ this -> write ( ) ; } return $ this ; }
Hides the document until any page it is linked to is published
16,331
public function isHidden ( ) { $ hidden = $ this -> isEmbargoed ( ) || $ this -> isExpired ( ) ; $ readingMode = Versioned :: get_reading_mode ( ) ; if ( $ readingMode == "Stage.Stage" ) { if ( $ this -> EmbargoedUntilPublished == true ) { $ hidden = false ; } } return $ hidden ; }
Returns if this is Document is embargoed or expired .
16,332
public function isEmbargoed ( ) { if ( is_object ( $ this -> EmbargoedUntilDate ) ) { $ this -> EmbargoedUntilDate = $ this -> EmbargoedUntilDate -> Value ; } $ embargoed = false ; if ( $ this -> EmbargoedIndefinitely ) { $ embargoed = true ; } elseif ( $ this -> EmbargoedUntilPublished ) { $ embargoed = true ; } elsei...
Returns if this is Document is embargoed .
16,333
public function clearEmbargo ( $ write = true ) { $ this -> EmbargoedIndefinitely = false ; $ this -> EmbargoedUntilPublished = false ; $ this -> EmbargoedUntilDate = null ; if ( $ write ) { $ this -> write ( ) ; } return $ this ; }
Clears any previously set embargos so the Document always shows up in all queries .
16,334
public function isExpired ( ) { if ( is_object ( $ this -> ExpireAtDate ) ) { $ this -> ExpireAtDate = $ this -> ExpireAtDate -> Value ; } $ expired = false ; if ( ! empty ( $ this -> ExpireAtDate ) ) { if ( SS_Datetime :: now ( ) -> Value >= $ this -> ExpireAtDate ) { $ expired = true ; } } return $ expired ; }
Returns if this is Document is expired .
16,335
public function clearExpiry ( $ write = true ) { $ this -> ExpireAtDate = null ; if ( $ write ) { $ this -> write ( ) ; } return $ this ; }
Clears any previously set expiry .
16,336
public function getFullPath ( ) { if ( $ this -> Filename ) { return DMS :: inst ( ) -> getStoragePath ( ) . DIRECTORY_SEPARATOR . $ this -> Folder . DIRECTORY_SEPARATOR . $ this -> Filename ; } return null ; }
Returns the full filename of the document stored in this object .
16,337
public function delete ( ) { $ filesToDelete = array ( ) ; $ storageFolder = $ this -> getStorageFolder ( ) ; if ( file_exists ( $ storageFolder ) ) { if ( $ handle = opendir ( $ storageFolder ) ) { while ( false !== ( $ entry = readdir ( $ handle ) ) ) { if ( strpos ( $ entry , $ this -> ID . '~' ) === 0 ) { $ filesTo...
Deletes the DMSDocument and its underlying file . Also calls the parent DataObject s delete method in order to complete an cascade .
16,338
public function storeDocument ( $ filePath ) { if ( empty ( $ this -> ID ) ) { user_error ( "Document must be written to database before it can store documents" , E_USER_ERROR ) ; } $ fromFilename = basename ( $ filePath ) ; $ toFilename = $ this -> ID . '~' . $ fromFilename ; $ toFolder = DMS :: inst ( ) -> getStorage...
Relate an existing file on the filesystem to the document .
16,339
public function getPermissionsActionPanel ( ) { $ fields = FieldList :: create ( ) ; $ showFields = array ( 'CanViewType' => '' , 'ViewerGroups' => 'hide' , 'CanEditType' => '' , 'EditorGroups' => 'hide' , ) ; $ siteTree = singleton ( 'SiteTree' ) ; $ settingsFields = $ siteTree -> getSettingsFields ( ) ; foreach ( $ s...
Adds permissions selection fields to a composite field and returns so it can be used in the actions panel
16,340
public function getRelatedPages ( ) { $ pages = ArrayList :: create ( ) ; foreach ( $ this -> Sets ( ) as $ documentSet ) { $ pages -> add ( $ documentSet -> Page ( ) ) ; } $ pages -> removeDuplicates ( ) ; $ this -> extend ( 'updateRelatedPages' , $ pages ) ; return $ pages ; }
Get a list of related pages for this document by going through the associated document sets
16,341
protected function getRelatedDocumentsGridField ( ) { $ gridField = GridField :: create ( 'RelatedDocuments' , _t ( 'DMSDocument.RELATEDDOCUMENTS' , 'Related Documents' ) , $ this -> RelatedDocuments ( ) , new GridFieldConfig_RelationEditor ) ; $ gridFieldConfig = $ gridField -> getConfig ( ) ; $ gridFieldConfig -> rem...
Get a GridField for managing related documents
16,342
protected function getRelatedDocumentsForAutocompleter ( ) { $ documents = DMSDocument :: get ( ) -> exclude ( 'ID' , $ this -> ID ) ; $ this -> extend ( 'updateRelatedDocumentsForAutocompleter' , $ documents ) ; return $ documents ; }
Get the list of documents to show in related documents . This can be modified via the extension point for example if you wanted to exclude embargoed documents or something similar .
16,343
protected function validate ( ) { $ valid = parent :: validate ( ) ; if ( $ this -> CanViewType == 'OnlyTheseUsers' && ! $ this -> ViewerGroups ( ) -> count ( ) ) { $ valid -> error ( _t ( 'DMSDocument.VALIDATIONERROR_NOVIEWERSELECTED' , "Selecting 'Only these people' from a viewers list needs at least one group select...
Checks at least one group is selected if CanViewType || CanEditType == OnlyTheseUsers
16,344
public function getPermissionDeniedReason ( ) { $ result = '' ; if ( $ this -> CanViewType == 'LoggedInUsers' ) { $ result = _t ( 'DMSDocument.PERMISSIONDENIEDREASON_LOGINREQUIRED' , 'Please log in to view this document' ) ; } if ( $ this -> CanViewType == 'OnlyTheseUsers' ) { $ result = _t ( 'DMSDocument.PERMISSIONDEN...
Returns a reason as to why this document cannot be viewed .
16,345
public function getActionTaskHtml ( ) { $ html = '<div class="field dmsdocment-actions">' . '<label class="left">' . _t ( 'DMSDocument.ACTIONS_LABEL' , 'Actions' ) . '</label>' . '<ul>' ; foreach ( $ this -> actionTasks as $ panelKey => $ title ) { $ panelKey = Convert :: raw2xml ( $ panelKey ) ; $ title = Convert :: r...
Returns a HTML representation of the action tasks for the CMS
16,346
public function removeActionPanelTask ( $ panelKey ) { if ( array_key_exists ( $ panelKey , $ this -> actionTasks ) ) { unset ( $ this -> actionTasks [ $ panelKey ] ) ; } return $ this ; }
Removes an action panel tasks
16,347
public function getCurrentDocumentSet ( ) { if ( $ id = $ this -> getRequest ( ) -> getVar ( 'dsid' ) ) { return DMSDocumentSet :: get ( ) -> byId ( $ id ) ; } return singleton ( 'DMSDocumentSet' ) ; }
Get the current document set if a document set ID was provided
16,348
protected function getPageEditLink ( $ pageId , $ documentSetId ) { return Controller :: join_links ( CMSPageEditController :: singleton ( ) -> getEditForm ( $ pageId ) -> FormAction ( ) , 'field/DocumentSets/item' , ( int ) $ documentSetId ) ; }
Return a link to edit a page deep linking into the document set given
16,349
public function linkdocument ( ) { $ return = array ( 'error' => _t ( 'UploadField.FIELDNOTSET' , 'Could not add document to page' ) ) ; $ documentSet = $ this -> getCurrentDocumentSet ( ) ; if ( ! empty ( $ documentSet ) ) { $ document = DMSDocument :: get ( ) -> byId ( $ this -> getRequest ( ) -> getVar ( 'documentID...
Link an existing document to the given document set ID
16,350
public function documentlist ( ) { if ( ! $ this -> getRequest ( ) -> getVar ( 'pageID' ) ) { return $ this -> httpError ( 400 ) ; } $ page = SiteTree :: get ( ) -> byId ( $ this -> getRequest ( ) -> getVar ( 'pageID' ) ) ; if ( $ page && $ page -> getAllDocuments ( ) -> count ( ) > 0 ) { $ list = '<ul>' ; foreach ( $ ...
Returns HTML representing a list of documents that are associated with the given page ID across all document sets .
16,351
public function canView ( $ member = null ) { if ( ! $ member || ! ( is_a ( $ member , 'Member' ) ) || is_numeric ( $ member ) ) { $ member = Member :: currentUser ( ) ; } if ( $ member && Permission :: checkMember ( $ member , array ( 'CMS_ACCESS_DMSDocumentAdmin' , ) ) ) { return true ; } return parent :: canView ( $...
Overrides the parent method to allow users with access to DMS admin to access this controller
16,352
public function getColumnContent ( $ gridField , $ record , $ columnName ) { $ data = new ArrayData ( array ( 'Link' => Controller :: join_links ( $ gridField -> Link ( 'item' ) , $ record -> ID , 'edit' ) ) ) ; $ template = $ record -> canEdit ( ) ? 'GridFieldEditButton' : 'GridFieldViewButton' ; return $ data -> rend...
Overriding the parent method to change the template that the DMS edit button will be rendered with based on whether or not the user has edit permissions .
16,353
private function highlight ( $ str , $ start , $ length ) { $ parts = array ( substr ( $ str , 0 , $ start ) , substr ( $ str , $ start , $ length ) , substr ( $ str , $ start + $ length ) ) ; $ parts = array_map ( 'htmlentities' , $ parts ) ; $ highlighted = $ parts [ 0 ] . '<span class="' . $ this -> highlightClassNa...
Highlight the given string enclosing it in a span
16,354
public function format ( $ html = false ) { $ format = '%s: %s' ; if ( $ this -> lastLine > 0 ) { $ format .= PHP_EOL ; $ format .= 'From line %d, column %d; ' ; $ format .= 'to line %d, column %d' ; } $ message = sprintf ( $ format , $ html ? '<strong>' . $ this -> type . '</strong>' : $ this -> type , $ html ? htmlen...
Format the message in readable format
16,355
protected function getDocumentFromID ( $ request ) { $ doc = null ; $ id = Convert :: raw2sql ( $ request -> param ( 'ID' ) ) ; if ( strpos ( $ id , 'version' ) === 0 ) { $ id = $ this -> getDocumentIdFromSlug ( str_replace ( 'version' , '' , $ id ) ) ; $ doc = DataObject :: get_by_id ( 'DMSDocument_versions' , $ id ) ...
Returns the document object from the request object s ID parameter . Returns null if no document found
16,356
protected function getDocumentIdFromSlug ( $ slug ) { $ parts = ( array ) sscanf ( $ slug , '%d-%s' ) ; $ id = array_shift ( $ parts ) ; if ( is_numeric ( $ id ) ) { return ( int ) $ id ; } throw new InvalidArgumentException ( $ slug . ' is not a valid DMSDocument URL' ) ; }
Get a document s ID from a friendly URL slug containing a numeric ID and slugged title
16,357
public function getEditForm ( $ id = null , $ fields = null ) { $ form = parent :: getEditForm ( $ id , $ fields ) ; $ gridField = $ form -> Fields ( ) -> fieldByName ( $ this -> sanitiseClassName ( $ this -> modelClass ) ) ; return $ this -> modifyGridField ( $ form , $ gridField ) ; }
Remove the default add button and replace it with a customised version for DMS
16,358
protected function modifyGridField ( CMSForm $ form , GridField $ gridField ) { $ gridFieldConfig = $ gridField -> getConfig ( ) ; $ gridFieldConfig -> removeComponentsByType ( 'GridFieldEditButton' ) ; $ gridFieldConfig -> addComponent ( new DMSGridFieldEditButton ( ) , 'GridFieldDeleteAction' ) ; if ( $ this -> model...
If the GridField is for DMSDocument then add a custom add button . If it s for DMSDocumentSet then update the display fields to include some extra columns that are only for this ModelAdmin so cannot be added directly to the model s display fields .
16,359
public function updateCMSFields ( FieldList $ fields ) { $ tags = $ this -> getAllTagsMap ( ) ; $ tagField = ListboxField :: create ( 'Tags' , _t ( 'DMSDocumentTaxonomyExtension.TAGS' , 'Tags' ) ) -> setMultiple ( true ) -> setSource ( $ tags ) ; if ( empty ( $ tags ) ) { $ tagField -> setAttribute ( 'data-placeholder'...
Push an autocomplete dropdown for the available tags in documents
16,360
public function getShortcodeFields ( $ class ) { $ fields = array ( ) ; $ ancestry = array_values ( ClassInfo :: dataClassesFor ( $ class ) ) ; foreach ( $ ancestry as $ ancestor ) { if ( ClassInfo :: classImplements ( $ ancestor , 'TestOnly' ) ) { continue ; } $ ancFields = DataObject :: custom_database_fields ( $ anc...
Returns a filtered list of fields which could contain shortcodes .
16,361
public function dataValue ( ) { $ result = null ; if ( is_array ( $ this -> value ) ) { $ this -> value = $ this -> arrayFilterEmptyRecursive ( $ this -> value ) ; $ result = ( ! empty ( $ this -> value ) ) ? Convert :: array2json ( $ this -> value ) : $ result ; } else { $ result = parent :: dataValue ( ) ; } return $...
Overrides parent behaviour to remove empty elements
16,362
public static function inst ( ) { if ( ! self :: $ instance ) { self :: $ instance = new static ( ) ; $ dmsPath = self :: $ instance -> getStoragePath ( ) ; if ( ! is_dir ( $ dmsPath ) ) { self :: $ instance -> createStorageFolder ( $ dmsPath ) ; } if ( ! file_exists ( $ dmsPath . DIRECTORY_SEPARATOR . '.htaccess' ) ) ...
Factory method that returns an instance of the DMS . This could be any class that implements the DMSInterface .
16,363
public function transformFileToFilePath ( $ file ) { $ filePath = null ; if ( is_string ( $ file ) ) { $ filePath = $ file ; } elseif ( is_object ( $ file ) && $ file -> is_a ( "File" ) ) { $ filePath = $ file -> Filename ; } if ( ! $ filePath ) { throw new FileNotFoundException ( ) ; } return $ filePath ; }
Gets a file path from either a File or a string
16,364
public function wrap ( $ parser , $ nodes , $ charset = null ) { switch ( $ parser ) { case Validator :: PARSER_XML : case Validator :: PARSER_XMLDTD : return $ this -> wrapInXmlDocument ( $ nodes , $ charset ) ; case Validator :: PARSER_HTML : case Validator :: PARSER_HTML5 : return $ this -> wrapInHtml5Document ( $ n...
Attempts to wrap a document in a surrounding document
16,365
protected function wrapInXmlDocument ( $ nodes , $ charset = null ) { $ charset = strtoupper ( $ charset ? : Validator :: CHARSET_UTF_8 ) ; $ document = '<?xml version="1.0" encoding="' . $ charset . '"?>' . PHP_EOL ; $ document .= '<root>' . $ nodes . '</root>' ; return $ document ; }
Wraps a set of XML nodes in an XML - document
16,366
protected function wrapInHtml5Document ( $ nodes , $ charset = null ) { $ charset = strtolower ( $ charset ? : Validator :: CHARSET_UTF_8 ) ; $ document = '<!DOCTYPE html>' . PHP_EOL ; $ document .= '<html><head>' . PHP_EOL ; $ document .= '<meta charset="' . $ charset . '">' . PHP_EOL ; $ document .= '<title>Validatio...
Wraps a set of HTML nodes in an HTML5 - document
16,367
protected function wrapInHtml4Document ( $ nodes , $ charset = null , $ parser = null ) { if ( $ parser === Validator :: PARSER_HTML4TR ) { $ doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">' ; } else { $ doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML...
Wraps a set of HTML nodes in an HTML4 - document
16,368
public function setParser ( $ parser ) { switch ( $ parser ) { case self :: PARSER_XML : case self :: PARSER_XMLDTD : case self :: PARSER_HTML : case self :: PARSER_HTML5 : case self :: PARSER_HTML4 : case self :: PARSER_HTML4TR : $ this -> parser = $ parser ; return $ this ; default : throw new UnknownParserException ...
Set parser to use for the given markup
16,369
private function getMimeTypeForParser ( $ parser ) { switch ( $ parser ) { case self :: PARSER_XML : return 'application/xml' ; case self :: PARSER_XMLDTD : return 'application/xml-dtd' ; case self :: PARSER_HTML : case self :: PARSER_HTML5 : case self :: PARSER_HTML4 : case self :: PARSER_HTML4TR : return 'text/html' ...
Get the correct mime - type for the given parser
16,370
public function validateUrl ( $ url , $ options = [ ] ) { try { $ query = [ 'out' => 'json' , 'parser' => $ this -> parser , 'doc' => ( string ) $ url , ] ; if ( isset ( $ options [ 'checkErrorPages' ] ) && $ options [ 'checkErrorPages' ] === true ) { $ query [ 'checkerrorpages' ] = true ; } $ response = $ this -> http...
Validate a URL
16,371
protected function createDefaultSet ( ) { $ pages = SiteTree :: get ( ) ; foreach ( $ pages as $ page ) { if ( ! $ page -> config ( ) -> get ( 'documents_enabled' ) ) { $ this -> addResult ( 'Skipped: documents disabled' ) ; continue ; } if ( $ page -> DocumentSets ( ) -> count ( ) ) { $ this -> addResult ( 'Skipped: a...
Creates a default document set for any valid page that doesn t have one
16,372
protected function reassignDocuments ( ) { $ countCheck = SQLSelect :: create ( '*' , 'DMSDocument_Pages' ) ; if ( ! $ countCheck -> count ( ) ) { $ this -> output ( 'There was no data to migrate. Finishing.' ) ; return $ this ; } $ query = SQLSelect :: create ( array ( 'DMSDocumentID' , 'SiteTreeID' ) , 'DMSDocument_P...
Reassign documents to the default document set where they d previously have been assigned to pages
16,373
protected function addDocumentToSet ( DMSDocument $ document , DMSDocumentSet $ set ) { if ( $ this -> isDryrun ( ) ) { return $ this ; } $ set -> Documents ( ) -> add ( $ document ) ; return $ this ; }
Add the given document to the given document set
16,374
protected function outputResults ( ) { $ this -> output ( ) ; $ this -> output ( 'Finished:' ) ; foreach ( $ this -> results as $ metric => $ count ) { $ this -> output ( '+ ' . $ metric . ': ' . $ count ) ; } return $ this ; }
Output a finished notice and the results of what was done
16,375
private function updateEcho ( ) { $ this -> isEcho = ( ! is_null ( Helper :: array_find ( $ this -> _message , 'is_echo' ) ) ) ; if ( $ this -> isEcho ) { if ( isset ( $ this -> message ) ) { $ this -> message -> app_id = Helper :: array_find ( $ this -> _message , 'app_id' ) ; $ this -> message -> metadata = Helper ::...
ONLY run after message
16,376
public function textMessages ( ) { $ result = [ ] ; foreach ( $ this -> entries as $ entry ) { foreach ( $ entry -> messages as $ entryMessage ) { if ( $ entryMessage -> isMessage ) { if ( $ entryMessage -> message -> isText && ! $ entryMessage -> message -> isQuickReply ) { $ result [ ] = $ entryMessage ; } } } } retu...
Not Quick Replies
16,377
protected function calculateSize ( array $ params , array $ imageSize ) { if ( empty ( $ params [ 'width' ] ) && empty ( $ params [ 'height' ] ) ) { throw new TransformationException ( 'Missing both width and height. You need to specify at least one of them' , 400 ) ; } $ width = ! empty ( $ params [ 'width' ] ) ? ( in...
Calculate output size of image
16,378
public function setBlob ( $ blob ) { $ this -> blob = $ blob ; $ this -> setFilesize ( strlen ( $ blob ) ) ; $ this -> setChecksum ( md5 ( $ blob ) ) ; return $ this ; }
Set the blob and update filesize and checksum properties
16,379
public function hasBeenTransformed ( $ flag = null ) { if ( $ flag === null ) { return $ this -> hasBeenTransformed ; } $ this -> hasBeenTransformed = ( bool ) $ flag ; return $ this ; }
Set or get the hasBeenTransformed flag
16,380
private function getConnection ( ) { if ( $ this -> connection === null ) { $ this -> connection = DriverManager :: getConnection ( $ this -> params , new Configuration ( ) ) ; } return $ this -> connection ; }
Get the Doctrine connection
16,381
public function prepareImage ( EventInterface $ event ) { $ request = $ event -> getRequest ( ) ; $ imageBlob = $ request -> getContent ( ) ; if ( empty ( $ imageBlob ) ) { $ e = new ImageException ( 'No image attached' , 400 ) ; $ e -> setImboErrorCode ( Exception :: IMAGE_NO_IMAGE_ATTACHED ) ; throw $ e ; } $ mime = ...
Prepare an image
16,382
public function bestMatch ( array $ mimeTypes , array $ acceptable ) { $ maxQ = 0 ; $ match = false ; foreach ( $ mimeTypes as $ mime ) { if ( ( $ q = $ this -> isAcceptable ( $ mime , $ acceptable ) ) && ( $ q > $ maxQ ) ) { $ maxQ = $ q ; $ match = $ mime ; } } return $ match ; }
Pick the best match from a set of mime types matched against acceptable types
16,383
public function isAcceptable ( $ mimeType , array $ acceptable ) { foreach ( $ acceptable as $ type => $ q ) { $ pattern = '#^' . str_replace ( '*' , '.*' , $ type ) . '#' ; if ( preg_match ( $ pattern , $ mimeType ) ) { return $ q ; } } return false ; }
See if a mime type is accepted
16,384
private function getKeysFromAcl ( ) { $ keys = [ ] ; foreach ( $ this -> accessList as $ access ) { $ keys [ $ access [ 'publicKey' ] ] = $ access [ 'privateKey' ] ; } return $ keys ; }
Get an array of public = > private key pairs defined in the ACL
16,385
private function validateAccessList ( ) { $ declaredPublicKeys = array_map ( function ( $ acl ) { return $ acl [ 'publicKey' ] ; } , $ this -> accessList ) ; $ publicKeys = [ ] ; foreach ( $ declaredPublicKeys as $ key ) { if ( in_array ( $ key , $ publicKeys ) ) { throw new InvalidArgumentException ( 'Public key decla...
Validate access list data
16,386
public function insert ( $ datum , $ priority ) { if ( is_int ( $ priority ) ) { $ priority = [ $ priority , $ this -> queueOrder -- ] ; } parent :: insert ( $ datum , $ priority ) ; }
Add an entry to the queue
16,387
public function getImage ( EventInterface $ event ) { $ request = $ event -> getRequest ( ) ; $ route = $ request -> getRoute ( ) ; $ params = $ event -> getDatabase ( ) -> getShortUrlParams ( $ route -> get ( 'shortUrlId' ) ) ; if ( ! $ params ) { throw new ResourceException ( 'Image not found' , 404 ) ; } $ route -> ...
Fetch an image via a short URL
16,388
private function getCollection ( ) { if ( $ this -> collection === null ) { try { $ this -> collection = $ this -> getMongoClient ( ) -> selectCollection ( $ this -> params [ 'databaseName' ] , 'imagevariation' ) ; } catch ( MongoException $ e ) { throw new DatabaseException ( 'Could not select collection' , 500 , $ e ...
Get the mongo collection
16,389
private function getMongoClient ( ) { if ( $ this -> mongoClient === null ) { try { $ this -> mongoClient = new MongoClient ( $ this -> params [ 'server' ] , $ this -> params [ 'options' ] ) ; } catch ( MongoException $ e ) { throw new DatabaseException ( 'Could not connect to database' , 500 , $ e ) ; } } return $ thi...
Get the mongo client instance
16,390
public function put ( EventInterface $ event ) { $ request = $ event -> getRequest ( ) ; $ metadata = json_decode ( $ request -> getContent ( ) , true ) ; $ event -> getManager ( ) -> trigger ( 'db.metadata.delete' ) -> trigger ( 'db.metadata.update' , [ 'metadata' => $ metadata , ] ) ; $ model = new Model \ Metadata (...
Handle PUT requests
16,391
public function validateMetadata ( EventInterface $ event ) { $ request = $ event -> getRequest ( ) ; $ metadata = $ request -> getContent ( ) ; if ( empty ( $ metadata ) ) { throw new InvalidArgumentException ( 'Missing JSON data' , 400 ) ; } else { $ metadata = json_decode ( $ metadata , true ) ; if ( $ metadata === ...
Validate metadata found in the request body
16,392
protected function getClient ( ) { if ( $ this -> client === null ) { $ this -> client = new Client ( $ this -> getParam ( 'accountId' ) , $ this -> getParam ( 'applicationKey' ) ) ; } return $ this -> client ; }
Get the current B2 client
16,393
private function getCollection ( $ type ) { if ( $ this -> collections [ $ type ] === null ) { try { $ this -> collections [ $ type ] = $ this -> getMongoClient ( ) -> selectCollection ( $ this -> params [ 'databaseName' ] , $ type ) ; } catch ( MongoException $ e ) { throw new DatabaseException ( 'Could not select col...
Get the mongo collection instance
16,394
final public static function getReadOnlyResources ( ) { return [ self :: USER_GET , self :: USER_HEAD , self :: USER_OPTIONS , self :: IMAGE_GET , self :: IMAGE_HEAD , self :: IMAGE_OPTIONS , self :: IMAGES_GET , self :: IMAGES_HEAD , self :: IMAGES_OPTIONS , self :: METADATA_GET , self :: METADATA_HEAD , self :: METAD...
Returns a list of resources which should be accessible for read - only public keys
16,395
final public static function getReadWriteResources ( ) { return array_merge ( self :: getReadOnlyResources ( ) , [ self :: IMAGE_DELETE , self :: IMAGES_POST , self :: METADATA_POST , self :: METADATA_DELETE , self :: METADATA_PUT , self :: SHORTURL_DELETE , self :: SHORTURLS_POST , self :: SHORTURLS_DELETE , ] ) ; }
Returns a list of resources which should be accessible for read + write public keys
16,396
final public static function getAllResources ( ) { return array_merge ( self :: getReadWriteResources ( ) , [ self :: KEYS_PUT , self :: KEYS_HEAD , self :: KEYS_DELETE , self :: KEYS_OPTIONS , self :: ACCESS_RULE_GET , self :: ACCESS_RULE_HEAD , self :: ACCESS_RULE_DELETE , self :: ACCESS_RULE_OPTIONS , self :: ACCESS...
Returns a list of all resources available including those which involves access control
16,397
public function loadFromCache ( EventInterface $ event ) { $ request = $ event -> getRequest ( ) ; $ response = $ event -> getResponse ( ) ; $ path = $ this -> getCacheFilePath ( $ request ) ; if ( is_file ( $ path ) ) { $ data = @ unserialize ( file_get_contents ( $ path ) ) ; if ( is_array ( $ data ) && isset ( $ dat...
Load transformed images from the cache
16,398
public function storeInCache ( EventInterface $ event ) { $ request = $ event -> getRequest ( ) ; $ response = $ event -> getResponse ( ) ; $ model = $ response -> getModel ( ) ; if ( ! $ model instanceof Image || $ this -> isCacheHit ( ) ) { return ; } $ path = $ this -> getCacheFilePath ( $ request ) ; $ dir = dirnam...
Store transformed images in the cache
16,399
public function deleteFromCache ( EventInterface $ event ) { $ request = $ event -> getRequest ( ) ; $ cacheDir = $ this -> getCacheDir ( $ request -> getUser ( ) , $ request -> getImageIdentifier ( ) ) ; if ( is_dir ( $ cacheDir ) ) { $ this -> rmdir ( $ cacheDir ) ; } }
Delete cached images from the cache