idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
40,800
public static function updateObjectState ( $ objectID , $ objectStateList ) { $ searchEngine = eZSearch :: getEngine ( ) ; if ( $ searchEngine instanceof ezpSearchEngine && method_exists ( $ searchEngine , 'updateObjectState' ) ) { return $ searchEngine -> updateObjectState ( $ objectID , $ objectStateList ) ; } return false ; }
Notifies search engine about updates to object states
40,801
public static function swapNode ( $ nodeID , $ selectedNodeID , $ nodeIdList = array ( ) ) { $ searchEngine = eZSearch :: getEngine ( ) ; if ( $ searchEngine instanceof ezpSearchEngine && method_exists ( $ searchEngine , 'swapNode' ) ) { return $ searchEngine -> swapNode ( $ nodeID , $ selectedNodeID , $ nodeIdList = array ( ) ) ; } return false ; }
Notifies search engine about an swap node operation
40,802
public function render ( ) { $ tpl = eZTemplate :: factory ( ) ; $ ini = eZINI :: instance ( 'rest.ini' ) ; $ nodeViewData = eZNodeviewfunctions :: generateNodeViewData ( $ tpl , $ this -> content -> main_node , $ this -> content -> main_node -> attribute ( 'object' ) , $ this -> content -> activeLanguage , 'rest' , 0 ) ; $ tpl -> setVariable ( 'module_result' , $ nodeViewData ) ; $ routingInfos = $ this -> controller -> getRouter ( ) -> getRoutingInformation ( ) ; $ templateName = $ ini -> variable ( $ routingInfos -> controllerClass . '_' . $ routingInfos -> action . '_OutputSettings' , 'Template' ) ; return $ tpl -> fetch ( 'design:' . $ templateName ) ; }
Returns string with rendered content
40,803
public function appendObject ( $ objectID , $ priority , $ contentObjectAttribute ) { $ object = eZContentObject :: fetch ( $ objectID ) ; if ( null === $ object ) { return ; } $ class = $ object -> attribute ( 'content_class' ) ; $ sectionID = $ object -> attribute ( 'section_id' ) ; $ relationItem = array ( 'identifier' => false , 'priority' => $ priority , 'in_trash' => false , 'contentobject_id' => $ object -> attribute ( 'id' ) , 'contentobject_version' => $ object -> attribute ( 'current_version' ) , 'contentobject_remote_id' => $ object -> attribute ( 'remote_id' ) , 'node_id' => $ object -> attribute ( 'main_node_id' ) , 'parent_node_id' => $ object -> attribute ( 'main_parent_node_id' ) , 'contentclass_id' => $ class -> attribute ( 'id' ) , 'contentclass_identifier' => $ class -> attribute ( 'identifier' ) , 'is_modified' => false ) ; $ relationItem [ 'object' ] = $ object ; return $ relationItem ; }
Generate array with object relation info
40,804
function & getSuggestions ( $ lang , $ word ) { $ sug = array ( ) ; $ osug = array ( ) ; $ matches = $ this -> _getMatches ( $ lang , $ word ) ; if ( count ( $ matches ) > 0 ) $ sug = explode ( "\t" , $ this -> _unhtmlentities ( $ matches [ 0 ] [ 4 ] ) ) ; foreach ( $ sug as $ item ) { if ( $ item ) $ osug [ ] = $ item ; } return $ osug ; }
Returns suggestions of for a specific word .
40,805
private function updateSettings ( array $ settings = array ( ) ) { if ( isset ( $ settings [ 'debug-message' ] ) ) $ this -> DebugMessage = $ settings [ 'debug-message' ] ; if ( isset ( $ settings [ 'debug-output' ] ) ) $ this -> UseDebugOutput = $ settings [ 'debug-output' ] ; if ( isset ( $ settings [ 'debug-levels' ] ) ) $ this -> AllowedDebugLevels = $ settings [ 'debug-levels' ] ; if ( isset ( $ settings [ 'debug-accumulator' ] ) ) $ this -> UseDebugAccumulators = $ settings [ 'debug-accumulator' ] ; if ( isset ( $ settings [ 'debug-timing' ] ) ) $ this -> UseDebugTimingPoints = $ settings [ 'debug-timing' ] ; if ( isset ( $ settings [ 'debug-include' ] ) ) $ this -> UseIncludeFiles = $ settings [ 'debug-include' ] ; if ( isset ( $ settings [ 'use-session' ] ) ) $ this -> UseSession = $ settings [ 'use-session' ] ; if ( isset ( $ settings [ 'use-modules' ] ) ) $ this -> UseModules = $ settings [ 'use-modules' ] ; if ( isset ( $ settings [ 'use-extensions' ] ) ) $ this -> UseExtensions = $ settings [ 'use-extensions' ] ; if ( isset ( $ settings [ 'user' ] ) ) $ this -> User = $ settings [ 'user' ] ; if ( isset ( $ settings [ 'site-access' ] ) ) $ this -> SiteAccess = $ settings [ 'site-access' ] ; if ( isset ( $ settings [ 'description' ] ) ) $ this -> Description = $ settings [ 'description' ] ; if ( isset ( $ settings [ 'min_version' ] ) ) $ this -> MinVersion = $ settings [ 'min_version' ] ; if ( isset ( $ settings [ 'max_version' ] ) ) $ this -> MaxVersion = $ settings [ 'max_version' ] ; }
Updates settings for current script .
40,806
static function instance ( $ settings = array ( ) ) { if ( ! isset ( $ GLOBALS [ 'eZScriptInstance' ] ) || ! ( $ GLOBALS [ 'eZScriptInstance' ] instanceof eZScript ) ) { $ GLOBALS [ 'eZScriptInstance' ] = new eZScript ( $ settings ) ; } else if ( ! empty ( $ settings ) ) { $ GLOBALS [ 'eZScriptInstance' ] -> updateSettings ( $ settings ) ; } return $ GLOBALS [ 'eZScriptInstance' ] ; }
Returns a shared instance of the eZScript class .
40,807
static function fetchByUser ( $ idArray , $ recursive = false ) { if ( count ( $ idArray ) < 1 ) { return array ( ) ; } $ db = eZDB :: instance ( ) ; if ( ! $ recursive ) { $ groupINSQL = $ db -> generateSQLINStatement ( $ idArray , 'ezuser_role.contentobject_id' , false , false , 'int' ) ; $ query = "SELECT DISTINCT ezrole.id, ezrole.name, ezuser_role.limit_identifier, ezuser_role.limit_value, ezuser_role.id as user_role_id FROM ezrole, ezuser_role WHERE $groupINSQL AND ezuser_role.role_id = ezrole.id" ; } else { $ userNodeIDArray = array ( ) ; foreach ( $ idArray as $ id ) { $ nodeDefinition = eZContentObjectTreeNode :: fetchByContentObjectID ( $ id ) ; foreach ( $ nodeDefinition as $ nodeDefinitionElement ) { $ userNodeIDArray = array_merge ( $ nodeDefinitionElement -> attribute ( 'path_array' ) , $ userNodeIDArray ) ; } } if ( count ( $ userNodeIDArray ) < 1 ) { return array ( ) ; } $ roleTreeINSQL = $ db -> generateSQLINStatement ( $ userNodeIDArray , 'role_tree.node_id' , false , false , 'int' ) ; $ query = "SELECT DISTINCT ezrole.id, ezrole.name, ezuser_role.limit_identifier, ezuser_role.limit_value, ezuser_role.id as user_role_id FROM ezrole, ezuser_role, ezcontentobject_tree role_tree WHERE ezuser_role.contentobject_id = role_tree.contentobject_id AND ezuser_role.role_id = ezrole.id AND $roleTreeINSQL" ; } $ roleArray = $ db -> arrayQuery ( $ query ) ; $ roles = array ( ) ; foreach ( $ roleArray as $ roleRow ) { $ role = new eZRole ( $ roleRow ) ; $ roles [ ] = $ role ; } return $ roles ; }
Returns the roles matching the given users eZContentObject ID array
40,808
static function accessArrayByUserID ( $ idArray , $ recursive = false ) { $ roles = eZRole :: fetchByUser ( $ idArray , $ recursive ) ; $ userLimitation = false ; $ accessArray = array ( ) ; foreach ( array_keys ( $ roles ) as $ roleKey ) { $ accessArray = array_merge_recursive ( $ accessArray , $ roles [ $ roleKey ] -> accessArray ( ) ) ; if ( $ roles [ $ roleKey ] -> attribute ( 'limit_identifier' ) ) { $ userLimitation = true ; } } if ( $ userLimitation ) { foreach ( $ accessArray as $ moduleKey => $ functionList ) { foreach ( $ functionList as $ functionKey => $ policyList ) { foreach ( $ policyList as $ policyKey => $ limitationList ) { if ( is_array ( $ limitationList ) ) { foreach ( $ limitationList as $ limitationKey => $ limitKeyArray ) { if ( is_array ( $ limitKeyArray ) ) { $ accessArray [ $ moduleKey ] [ $ functionKey ] [ $ policyKey ] [ $ limitationKey ] = array_unique ( $ limitKeyArray ) ; } } } } } } } return $ accessArray ; }
Return access array by passing in list of groups user belongs to and his user id
40,809
static function roleCount ( $ ignoreNew = true ) { $ conds = array ( 'version' => 0 ) ; if ( $ ignoreNew === true ) { $ conds [ 'is_new' ] = 0 ; } return eZPersistentObject :: count ( eZRole :: definition ( ) , $ conds ) ; }
Fetches the count of created roles
40,810
function rssXmlContent ( ) { try { switch ( $ this -> attribute ( 'rss_version' ) ) { case '1.0' : { return $ this -> generateFeed ( 'rss1' ) ; } break ; case '2.0' : { return $ this -> generateFeed ( 'rss2' ) ; } break ; case 'ATOM' : { return $ this -> generateFeed ( 'atom' ) ; } break ; default : { return null ; } break ; } } catch ( ezcFeedException $ e ) { return '<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang=""><title>The RSS feed you were trying to access contains some errors and cannot be generated: ' . $ e -> getMessage ( ) . ' Please contact the webmaster.</title></feed>' ; } return null ; }
Generates an RSS feed document based on the rss_version attribute .
40,811
static public function setSettings ( $ userID , $ isEnabled , $ maxLogin ) { $ userSetting = eZUserSetting :: fetch ( $ userID ) ; if ( $ userSetting ) { $ userSetting -> setAttribute ( 'max_login' , $ maxLogin ) ; $ isUserEnabled = $ isEnabled != 0 ; if ( $ userSetting -> attribute ( 'is_enabled' ) != $ isUserEnabled ) { eZContentCacheManager :: clearContentCacheIfNeeded ( $ userID ) ; eZContentCacheManager :: generateObjectViewCache ( $ userID ) ; } $ userSetting -> setAttribute ( "is_enabled" , $ isUserEnabled ) ; $ userSetting -> store ( ) ; if ( ! $ isUserEnabled ) { eZUser :: removeSessionData ( $ userID ) ; } else { eZUserAccountKey :: removeByUserID ( $ userID ) ; } return array ( 'status' => true ) ; } else { eZDebug :: writeError ( "Failed to change settings of user $userID " , __METHOD__ ) ; return array ( 'status' => false ) ; } }
Changes user settings
40,812
static public function publishUserContentObject ( $ userID ) { $ object = eZContentObject :: fetch ( $ userID ) ; if ( $ object -> attribute ( 'current_version' ) !== '1' ) { eZDebug :: writeError ( 'Current version is wrong for the user object. User ID: ' . $ userID , 'user/register' ) ; return array ( 'status' => eZModuleOperationInfo :: STATUS_CANCELLED ) ; } eZDebugSetting :: writeNotice ( 'kernel-user' , 'publishing user object' , 'user register' ) ; if ( $ object -> attribute ( 'status' ) ) { eZDebugSetting :: writeNotice ( 'kernel-user' , 'User object publish is published.' , 'user register' ) ; return array ( 'status' => eZModuleOperationInfo :: STATUS_CONTINUE ) ; } $ result = eZOperationHandler :: execute ( 'content' , 'publish' , array ( 'object_id' => $ userID , 'version' => 1 ) ) ; if ( $ result [ 'status' ] === eZModuleOperationInfo :: STATUS_HALTED ) { eZDebugSetting :: writeNotice ( 'kernel-user' , 'User object publish is in pending.' , 'user register' ) ; return array ( 'status' => eZModuleOperationInfo :: STATUS_HALTED ) ; } return $ result ; }
publish the object
40,813
static public function sendUserNotification ( $ userID ) { $ ini = eZINI :: instance ( ) ; if ( $ ini -> variable ( 'UserSettings' , 'EmailRegistrationInfo' ) === "disabled" ) { return array ( 'status' => eZModuleOperationInfo :: STATUS_CONTINUE ) ; } eZDebugSetting :: writeNotice ( 'Sending approval notification to the user.' , 'kernel-user' , 'user register' ) ; $ user = eZUser :: fetch ( $ userID ) ; $ tpl = eZTemplate :: factory ( ) ; $ tpl -> setVariable ( 'user' , $ user ) ; $ templateResult = $ tpl -> fetch ( 'design:user/registrationapproved.tpl' ) ; $ mail = new eZMail ( ) ; if ( $ tpl -> hasVariable ( 'content_type' ) ) $ mail -> setContentType ( $ tpl -> variable ( 'content_type' ) ) ; $ emailSender = $ ini -> variable ( 'MailSettings' , 'EmailSender' ) ; if ( $ tpl -> hasVariable ( 'email_sender' ) ) $ emailSender = $ tpl -> variable ( 'email_sender' ) ; else if ( ! $ emailSender ) $ emailSender = $ ini -> variable ( 'MailSettings' , 'AdminEmail' ) ; if ( $ tpl -> hasVariable ( 'subject' ) ) $ subject = $ tpl -> variable ( 'subject' ) ; else $ subject = ezpI18n :: tr ( 'kernel/user/register' , 'User registration approved' ) ; $ mail -> setSender ( $ emailSender ) ; $ receiver = $ user -> attribute ( 'email' ) ; $ mail -> setReceiver ( $ receiver ) ; $ mail -> setSubject ( $ subject ) ; $ mail -> setBody ( $ templateResult ) ; $ mailResult = eZMailTransport :: send ( $ mail ) ; return array ( 'status' => eZModuleOperationInfo :: STATUS_CONTINUE ) ; }
Send the notification after registeration
40,814
static private function updateUserDraft ( $ user ) { $ userObject = eZContentObject :: fetch ( $ user -> id ( ) ) ; foreach ( $ userObject -> dataMap ( ) as $ attribute ) { if ( $ attribute -> ContentClassAttributeIdentifier == 'user_account' ) { $ attribute -> setAttribute ( 'data_text' , eZUserType :: serializeDraft ( $ user ) ) ; $ attribute -> store ( ) ; break ; } } }
Update the draft of a given user
40,815
static public function forgotpassword ( $ userID , $ passwordHash , $ time ) { $ user = eZUser :: fetch ( $ userID ) ; if ( $ user instanceof eZUser ) { $ forgotPasswdObj = eZForgotPassword :: createNew ( $ userID , $ passwordHash , $ time ) ; $ forgotPasswdObj -> store ( ) ; return array ( 'status' => true ) ; } else { eZDebug :: writeError ( "Failed to generate password hash for user $userID (could not fetch user)" , __METHOD__ ) ; return array ( 'status' => false ) ; } }
Generate forgotpassword object
40,816
function isInline ( $ element ) { if ( is_string ( $ element ) ) $ elementName = $ element ; else $ elementName = $ element -> nodeName ; $ isInline = $ this -> Schema [ $ elementName ] [ 'isInline' ] ; if ( is_array ( $ isInline ) && ! is_string ( $ element ) ) { $ isInline = false ; $ name = $ element -> getAttribute ( 'name' ) ; if ( isset ( $ this -> Schema [ 'custom' ] [ 'isInline' ] [ $ name ] ) ) { if ( $ this -> Schema [ 'custom' ] [ 'isInline' ] [ $ name ] != 'false' ) $ isInline = true ; } } return $ isInline ; }
Determines if the tag is inline
40,817
static function executeCompilation ( $ tpl , & $ textElements , $ key , & $ resourceData , $ rootNamespace , $ currentNamespace ) { if ( ! eZTemplateCompiler :: isCompilationEnabled ( ) ) return false ; if ( ! eZTemplateCompiler :: isExecutionEnabled ( ) ) return false ; $ cacheFileName = eZTemplateCompiler :: compilationFilename ( $ key , $ resourceData ) ; $ resourceData [ 'use-comments' ] = eZTemplateCompiler :: isCommentsEnabled ( ) ; $ directory = eZTemplateCompiler :: compilationDirectory ( ) ; $ phpScript = eZDir :: path ( array ( $ directory , $ cacheFileName ) ) ; if ( file_exists ( $ phpScript ) ) { $ text = false ; $ helperStatus = eZTemplateCompiler :: executeCompilationHelper ( $ phpScript , $ text , $ tpl , $ key , $ resourceData , $ rootNamespace , $ currentNamespace ) ; if ( $ helperStatus ) { $ textElements [ ] = $ text ; return true ; } else { eZDebug :: writeError ( "Failed executing compiled template '$phpScript'," . " if this file is valid, then the error is probably" . " related to APC usage, try restarting the webserver" , __METHOD__ ) ; throw new eZTemplateFailedExecutingCompiledTemplate ( "Failed executing a compiled template, see error.log for details" ) ; } } else eZDebug :: writeError ( "Unknown compiled template '$phpScript'" , __METHOD__ ) ; return false ; }
Tries to execute the compiled template . Returns true if successful returns false if the compilation is disabled or the compiled template does not exist .
40,818
public function doShow ( ) { if ( ( $ this -> exception instanceof ezcMvcRouteNotFoundException ) || ( $ this -> exception instanceof ezpContentNotFoundException ) ) { $ result = new ezcMvcResult ; $ result -> status = new ezpRestHttpResponse ( ezpHttpResponseCodes :: NOT_FOUND , "Not Found" ) ; return $ result ; } else if ( $ this -> exception instanceof ezpOauthBadRequestException ) { $ result = new ezcMvcResult ; $ result -> status = new ezpRestOauthErrorStatus ( $ this -> exception -> errorType , $ this -> exception -> getMessage ( ) ) ; $ result -> variables [ 'message' ] = $ this -> exception -> getMessage ( ) ; return $ result ; } else if ( $ this -> exception instanceof ezpOauthRequiredException ) { $ result = new ezcMvcResult ; $ result -> status = new ezpOauthRequired ( "eZ Publish REST" , $ this -> exception -> errorType , $ this -> exception -> getMessage ( ) ) ; $ result -> variables [ 'message' ] = $ this -> exception -> getMessage ( ) ; return $ result ; } else if ( $ this -> exception instanceof ezpContentAccessDeniedException ) { $ result = new ezcMvcResult ; $ result -> variables [ 'message' ] = $ this -> exception -> getMessage ( ) ; $ result -> status = new ezpRestHttpResponse ( ezpHttpResponseCodes :: FORBIDDEN , $ this -> exception -> getMessage ( ) ) ; return $ result ; } else if ( $ this -> exception instanceof ezpRouteMethodNotAllowedException ) { $ result = new ezpRestMvcResult ; $ result -> status = new ezpRestStatusResponse ( ezpHttpResponseCodes :: METHOD_NOT_ALLOWED , $ this -> exception -> getMessage ( ) , array ( 'Allow' => implode ( ', ' , $ this -> exception -> getAllowedMethods ( ) ) ) ) ; return $ result ; } $ result = new ezcMvcResult ; $ result -> variables [ 'message' ] = $ this -> exception -> getMessage ( ) ; $ result -> status = new ezpRestHttpResponse ( ezpHttpResponseCodes :: SERVER_ERROR , $ this -> exception -> getMessage ( ) ) ; return $ result ; }
Default method currently used for fatal error handling
40,819
static public function fetchRelatedObjectsID ( $ objectID , $ attributeID , $ allRelations ) { if ( ! is_array ( $ allRelations ) || $ allRelations === array ( ) ) { $ allRelations = array ( 'common' , 'xml_embed' , 'attribute' ) ; if ( eZContentObject :: isObjectRelationTyped ( ) ) { $ allRelations [ ] = 'xml_link' ; } } $ relatedObjectsTyped = array ( ) ; foreach ( $ allRelations as $ relationType ) { $ relatedObjectsTyped [ $ relationType ] = eZContentFunctionCollection :: fetchRelatedObjects ( $ objectID , $ attributeID , array ( $ relationType ) , false , array ( ) ) ; } $ relatedObjectsTypedIDArray = array ( ) ; foreach ( $ relatedObjectsTyped as $ relationTypeName => $ relatedObjectsByType ) { $ relatedObjectsTypedIDArray [ $ relationTypeName ] = array ( ) ; foreach ( $ relatedObjectsByType [ 'result' ] as $ relatedObjectByType ) { $ relatedObjectsTypedIDArray [ $ relationTypeName ] [ ] = $ relatedObjectByType -> ID ; } } return array ( 'result' => $ relatedObjectsTypedIDArray ) ; }
Fetches related objects id grouped by relation types
40,820
static public function fetchReverseRelatedObjectsID ( $ objectID , $ attributeID , $ allRelations ) { if ( ! is_array ( $ allRelations ) || $ allRelations === array ( ) ) { $ allRelations = array ( 'common' , 'xml_embed' , 'attribute' ) ; if ( eZContentObject :: isObjectRelationTyped ( ) ) { $ allRelations [ ] = 'xml_link' ; } } $ relatedObjectsTyped = array ( ) ; foreach ( $ allRelations as $ relationType ) { $ relatedObjectsTyped [ $ relationType ] = eZContentFunctionCollection :: fetchReverseRelatedObjects ( $ objectID , $ attributeID , array ( $ relationType ) , false , array ( ) , null ) ; } $ relatedObjectsTypedIDArray = array ( ) ; foreach ( $ relatedObjectsTyped as $ relationTypeName => $ relatedObjectsByType ) { $ relatedObjectsTypedIDArray [ $ relationTypeName ] = array ( ) ; foreach ( $ relatedObjectsByType [ 'result' ] as $ relatedObjectByType ) { $ relatedObjectsTypedIDArray [ $ relationTypeName ] [ ] = $ relatedObjectByType -> ID ; } } return array ( 'result' => $ relatedObjectsTypedIDArray ) ; }
Fetches reverse related objects id grouped by relation types
40,821
static function buildJavascriptFiles ( $ scriptFiles , $ packLevel = 2 , $ indexDirInCacheHash = true ) { return ezjscPacker :: packFiles ( $ scriptFiles , 'javascript/' , '.js' , $ packLevel , $ indexDirInCacheHash ) ; }
Builds javascript files
40,822
static function buildStylesheetFiles ( $ cssFiles , $ packLevel = 3 , $ indexDirInCacheHash = true ) { return ezjscPacker :: packFiles ( $ cssFiles , 'stylesheets/' , '.css' , $ packLevel , $ indexDirInCacheHash , '_all' ) ; }
Builds stylesheet files
40,823
static function fixImgPaths ( $ fileContent , $ file ) { if ( preg_match_all ( "/url\(\s*[\'|\"]?([A-Za-z0-9_\-\/\.\\%?&@#=]+)[\'|\"]?\s*\)/ix" , $ fileContent , $ urlMatches ) ) { $ urlPaths = array ( ) ; $ urlMatches = array_unique ( $ urlMatches [ 1 ] ) ; $ cssPathArray = explode ( '/' , $ file ) ; $ wwwDir = self :: getWwwDir ( ) ; array_pop ( $ cssPathArray ) ; $ cssPathCount = count ( $ cssPathArray ) ; foreach ( $ urlMatches as $ match ) { $ match = str_replace ( '\\' , '/' , $ match ) ; $ relativeCount = substr_count ( $ match , '../' ) ; if ( $ match [ 0 ] !== '/' and strpos ( $ match , 'http:' ) === false ) { $ cssPathSlice = $ relativeCount === 0 ? $ cssPathArray : array_slice ( $ cssPathArray , 0 , $ cssPathCount - $ relativeCount ) ; $ newMatchPath = $ wwwDir ; if ( ! empty ( $ cssPathSlice ) ) { $ newMatchPath .= implode ( '/' , $ cssPathSlice ) . '/' ; } $ newMatchPath .= str_replace ( '../' , '' , $ match ) ; $ urlPaths [ $ match ] = $ newMatchPath ; } } $ fileContent = strtr ( $ fileContent , $ urlPaths ) ; } return $ fileContent ; }
Fix image paths in css .
40,824
static function serverCallHelper ( $ strServerCall ) { $ server = ezjscServerRouter :: getInstance ( $ strServerCall ) ; if ( ! $ server instanceof ezjscServerRouter ) { eZDebug :: writeError ( 'Not a valid ezjscServer function: ' . implode ( '::' , $ strServerCall ) , __METHOD__ ) ; return null ; } if ( ! $ server -> hasFunction ( ) ) { eZDebug :: writeError ( 'Could not find function: ' . $ server -> getName ( ) . '()' , __METHOD__ ) ; return null ; } return $ server ; }
Helper function to get and validate server functions
40,825
static public function printDebugReport ( $ as_html = true ) { if ( ! eZTemplate :: isTemplatesUsageStatisticsEnabled ( ) ) return '' ; $ stats = '' ; if ( $ as_html ) { $ stats .= '<h3>CSS/JS files loaded with "ezjscPacker" during request:</h3>' ; $ stats .= '<table id="ezjscpackerusage" class="debug_resource_usage" title="List of used files, hover over italic text for more info!">' ; $ stats .= '<tr><th>Cache</th><th>Type</th><th>Packlevel</th><th>SourceFiles</th></tr>' ; } else { $ stats .= "CSS/JS files loaded with 'ezjscPacker' during request\n" ; $ stats .= sprintf ( "%-40s%-40s%-40s\n" , 'Cache' , 'Type' , 'Packlevel' ) ; } foreach ( self :: $ log as $ data ) { $ extension = $ data [ 'file_extension' ] === '.js' ? 'JS' : 'CSS' ; if ( $ as_html ) { $ sourceFilesStats = self :: printDebugReportFiles ( $ data , $ as_html ) ; $ cache = $ data [ 'cache_path' ] === '' ? '' : "<span class='debuginfo' title='Full path: {$data['cache_path']}'>{$data['cache_hash']}</span>" ; $ stats .= "<tr class='data'><td>{$cache}</td><td>{$extension}</td><td>{$data['pack_level']}</td><td>{$sourceFilesStats}</td></tr>" ; } else { $ stats .= sprintf ( "%-40s%-40s%-40s\n" , $ data [ 'cache_hash' ] , $ extension , $ data [ 'pack_level' ] ) ; } } if ( $ as_html ) { $ stats .= '</table>' ; } return $ stats ; }
Generate a debug report of packer use
40,826
function preStoreVersionedClassAttribute ( $ classAttribute , $ version ) { switch ( $ version ) { case eZContentClass :: VERSION_STATUS_DEFINED : $ this -> preStoreDefinedClassAttribute ( $ classAttribute ) ; break ; case eZContentClass :: VERSION_STATUS_MODIFIED : $ this -> preStoreModifiedClassAttribute ( $ classAttribute ) ; break ; } }
Hook function which is called before an content class attribute is stored
40,827
function createContentObjectAttributeDOMNode ( $ objectAttribute ) { $ dom = new DOMDocument ( '1.0' , 'utf-8' ) ; $ node = $ dom -> createElementNS ( 'http://ez.no/object/' , 'ezobject:attribute' ) ; $ node -> setAttributeNS ( 'http://ez.no/ezobject' , 'ezremote:id' , $ objectAttribute -> attribute ( 'id' ) ) ; $ node -> setAttributeNS ( 'http://ez.no/ezobject' , 'ezremote:identifier' , $ objectAttribute -> contentClassAttributeIdentifier ( ) ) ; $ node -> setAttribute ( 'name' , $ objectAttribute -> contentClassAttributeName ( ) ) ; $ node -> setAttribute ( 'type' , $ this -> isA ( ) ) ; return $ node ; }
Create empty content object attribute DOM node .
40,828
public static function addAdditionalNodeIDPerObject ( $ contentObjectID , $ additionalNodeID ) { if ( ! isset ( self :: $ additionalNodeIDsPerObject [ $ contentObjectID ] ) ) { self :: $ additionalNodeIDsPerObject [ $ contentObjectID ] = array ( ) ; } self :: $ additionalNodeIDsPerObject [ $ contentObjectID ] [ ] = $ additionalNodeID ; }
Adds an additional NodeID to be appended to the node list for clearing view cache .
40,829
private static function appendAdditionalNodeIDs ( eZContentObject $ contentObject , & $ nodeIDList ) { $ contentObjectId = $ contentObject -> attribute ( 'id' ) ; if ( ! isset ( self :: $ additionalNodeIDsPerObject [ $ contentObjectId ] ) ) return ; foreach ( self :: $ additionalNodeIDsPerObject [ $ contentObjectId ] as $ nodeID ) { $ nodeIDList [ ] = $ nodeID ; } }
Appends additional node IDs .
40,830
public static function clearNodeViewCacheArray ( array $ nodeList , array $ contentObjectList = null ) { if ( count ( $ nodeList ) == 0 ) { return false ; } eZDebugSetting :: writeDebug ( 'kernel-content-edit' , count ( $ nodeList ) , "count in nodeList" ) ; if ( eZINI :: instance ( ) -> variable ( 'ContentSettings' , 'StaticCache' ) === 'enabled' ) { $ staticCacheHandler = eZExtension :: getHandlerClass ( new ezpExtensionOptions ( array ( 'iniFile' => 'site.ini' , 'iniSection' => 'ContentSettings' , 'iniVariable' => 'StaticCacheHandler' , ) ) ) ; $ staticCacheHandler -> generateAlwaysUpdatedCache ( ) ; $ staticCacheHandler -> generateNodeListCache ( $ nodeList ) ; } eZDebug :: accumulatorStart ( 'node_cleanup' , '' , 'Node cleanup' ) ; eZContentObject :: expireComplexViewModeCache ( ) ; $ cleanupValue = eZContentCache :: calculateCleanupValue ( count ( $ nodeList ) ) ; if ( eZContentCache :: inCleanupThresholdRange ( $ cleanupValue ) ) { $ nodeList = ezpEvent :: getInstance ( ) -> filter ( 'content/cache' , $ nodeList , $ contentObjectList ) ; eZContentCache :: cleanup ( $ nodeList ) ; } else { eZDebug :: writeDebug ( "Expiring all view cache since list of nodes({$cleanupValue}) exceeds site.ini\[ContentSettings]\CacheThreshold" , __METHOD__ ) ; ezpEvent :: getInstance ( ) -> notify ( 'content/cache/all' ) ; eZContentObject :: expireAllViewCache ( ) ; } eZDebug :: accumulatorStop ( 'node_cleanup' ) ; return true ; }
Clears view caches for an array of nodes .
40,831
public static function clearTemplateBlockCache ( $ objectID , $ checkViewCacheClassSettings = false ) { eZContentObject :: expireTemplateBlockCache ( ) ; if ( empty ( $ objectID ) ) return ; $ nodeList = false ; if ( is_array ( $ objectID ) ) { $ objects = eZContentObject :: fetchIDArray ( $ objectID ) ; } else { $ objects = array ( $ objectID => eZContentObject :: fetch ( $ objectID ) ) ; } $ ini = eZINI :: instance ( 'viewcache.ini' ) ; foreach ( $ objects as $ object ) { if ( $ object instanceof eZContentObject ) { $ getAssignedNodes = true ; if ( $ checkViewCacheClassSettings ) { $ objectClassIdentifier = $ object -> attribute ( 'class_identifier' ) ; if ( $ ini -> hasVariable ( $ objectClassIdentifier , 'ClearCacheBlocks' ) && $ ini -> variable ( $ objectClassIdentifier , 'ClearCacheBlocks' ) === 'disabled' ) { $ getAssignedNodes = false ; } } if ( $ getAssignedNodes ) { $ nodeList = array_merge ( ( $ nodeList !== false ? $ nodeList : array ( ) ) , $ object -> assignedNodes ( ) ) ; } } } eZSubtreeCache :: cleanup ( $ nodeList ) ; }
Clears template - block cache and template - block with subtree_expiry parameter caches for specified object without checking TemplateCache ini setting .
40,832
function ezSetCmMargins ( $ top , $ bottom , $ left , $ right ) { $ top = ( $ top / 2.54 ) * 72 ; $ bottom = ( $ bottom / 2.54 ) * 72 ; $ left = ( $ left / 2.54 ) * 72 ; $ right = ( $ right / 2.54 ) * 72 ; $ this -> ezSetMargins ( $ top , $ bottom , $ left , $ right ) ; }
Set Margins in centimeters
40,833
function ezShadedRectangle ( $ x1 , $ y1 , $ width , $ height , $ col1 , $ col2 , $ direction = 'vertical' ) { $ this -> shadedRectangle ( $ x1 , $ y1 , $ width , $ height , array ( 'orientation' => $ direction , 'color0' => $ col1 , 'color1' => $ col2 , 'size' => array ( 'x1' => $ x1 , 'y1' => $ y1 , 'width' => $ width , 'height' => $ height ) ) ) ; }
Draw a shaded rectangle
40,834
function loadTemplate ( $ templateFile ) { if ( ! file_exists ( $ templateFile ) ) { return - 1 ; } $ code = implode ( '' , file ( $ templateFile ) ) ; if ( ! strlen ( $ code ) ) { return ; } $ code = trim ( $ code ) ; if ( substr ( $ code , 0 , 5 ) == '<?php' ) { $ code = substr ( $ code , 5 ) ; } if ( substr ( $ code , - 2 ) == '?>' ) { $ code = substr ( $ code , 0 , strlen ( $ code ) - 2 ) ; } if ( isset ( $ this -> ez [ 'numTemplates' ] ) ) { $ newNum = $ this -> ez [ 'numTemplates' ] ; $ this -> ez [ 'numTemplates' ] ++ ; } else { $ newNum = 0 ; $ this -> ez [ 'numTemplates' ] = 1 ; $ this -> ez [ 'templates' ] = array ( ) ; } $ this -> ez [ 'templates' ] [ $ newNum ] [ 'code' ] = $ code ; return $ newNum ; }
out a good way of doing this yet .
40,835
function lineHeight ( $ options = array ( ) ) { if ( is_array ( $ options ) && isset ( $ options [ 'size' ] ) ) { $ size = $ options [ 'size' ] ; } else { $ size = $ this -> ez [ 'fontSize' ] ; } if ( is_array ( $ options ) && isset ( $ options [ 'leading' ] ) ) { $ height = $ options [ 'leading' ] ; } else if ( is_array ( $ options ) && isset ( $ options [ 'spacing' ] ) ) { $ height = $ this -> getFontHeight ( $ size ) * $ options [ 'spacing' ] ; } else { $ height = $ this -> getFontHeight ( $ size ) ; } return $ height ; }
Get current line height
40,836
public function store ( $ id , $ data , $ attributes = array ( ) ) { $ this -> forceStoreRegistry = true ; $ storeResult = parent :: store ( $ id , $ data , $ attributes ) ; $ expiryTime = time ( ) + $ this -> properties [ 'options' ] [ 'ttl' ] ; $ this -> expiryHandler -> setTimestamp ( ezpRestRouter :: ROUTE_CACHE_KEY , $ expiryTime ) ; return $ storeResult ; }
Direct store instruction . Makes the registry to be stored
40,837
public function delete ( $ id = null , $ attributes = array ( ) , $ search = false ) { $ this -> forceStoreRegistry = true ; parent :: delete ( $ id , $ attributes , $ search ) ; }
Direct delete instruction . Registry will be stored
40,838
public static function fetchByAction ( $ action , array $ aCreationDateFilter = array ( ) ) { $ filterConds = array ( 'action' => $ action ) ; if ( ! empty ( $ aCreationDateFilter ) ) { if ( count ( $ aCreationDateFilter ) != 2 ) { eZDebug :: writeError ( __CLASS__ . '::' . __METHOD__ . ' : Wrong number of entries for Creation date filter array' ) ; return null ; } list ( $ filterToken , $ filterValue ) = $ aCreationDateFilter ; $ aAuthorizedFilterTokens = array ( '=' , '<' , '>' , '<=' , '>=' ) ; if ( ! is_string ( $ filterToken ) || ! in_array ( $ filterToken , $ aAuthorizedFilterTokens ) ) { eZDebug :: writeError ( __CLASS__ . '::' . __METHOD__ . ' : Wrong filter type for creation date filter' ) ; return null ; } $ filterConds [ 'created' ] = array ( $ filterToken , $ filterValue ) ; } $ result = parent :: fetchObjectList ( self :: definition ( ) , null , $ filterConds ) ; return $ result ; }
Fetches a pending actions list by action name
40,839
public static function optimize ( $ script , $ packLevel = 2 ) { $ script = str_replace ( array ( "\r\n" , "\r" ) , "\n" , $ script ) ; $ script = preg_replace ( array ( '/\n\s+/' , '/\s+\n/' , '#\n\s*//.*#' , '/\n+/' ) , "\n" , $ script ) ; $ script = preg_replace ( '!(?:\n|\s|^)/\*[^*]*\*+([^/][^*]*\*+)*/!' , '' , $ script ) ; $ script = preg_replace ( '!(?:;)/\*[^*]*\*+([^/][^*]*\*+)*/!' , ';' , $ script ) ; return $ script ; }
compress javascript code by removing whitespace
40,840
function executeTrigger ( & $ bodyReturnValue , $ body , $ operationParameterDefinitions , $ operationParameters , & $ bodyCallCount , $ currentLoopData , $ triggerRestored , $ operationName , & $ operationKeys ) { $ triggerName = $ body [ 'name' ] ; $ triggerKeys = $ body [ 'keys' ] ; $ status = eZTrigger :: runTrigger ( $ triggerName , $ this -> ModuleName , $ operationName , $ operationParameters , $ triggerKeys ) ; if ( $ status [ 'Status' ] == eZTrigger :: WORKFLOW_DONE || $ status [ 'Status' ] == eZTrigger :: NO_CONNECTED_WORKFLOWS ) { ++ $ bodyCallCount [ 'loop_run' ] [ $ triggerName ] ; return eZModuleOperationInfo :: STATUS_CONTINUE ; } else if ( $ status [ 'Status' ] == eZTrigger :: STATUS_CRON_JOB || $ status [ 'Status' ] == eZTrigger :: FETCH_TEMPLATE || $ status [ 'Status' ] == eZTrigger :: FETCH_TEMPLATE_REPEAT || $ status [ 'Status' ] == eZTrigger :: REDIRECT ) { $ bodyMemento = $ this -> storeBodyMemento ( $ triggerName , $ triggerKeys , $ operationKeys , $ operationParameterDefinitions , $ operationParameters , $ bodyCallCount , $ currentLoopData , $ operationName ) ; $ workflowProcess = $ status [ 'WorkflowProcess' ] ; if ( $ workflowProcess !== null ) { $ workflowProcess -> setAttribute ( 'memento_key' , $ bodyMemento -> attribute ( 'memento_key' ) ) ; $ workflowProcess -> store ( ) ; } $ bodyReturnValue [ 'result' ] = $ status [ 'Result' ] ; if ( $ status [ 'Status' ] == eZTrigger :: REDIRECT ) { $ bodyReturnValue [ 'redirect_url' ] = $ status [ 'Result' ] ; } if ( $ status [ 'Status' ] == eZTrigger :: FETCH_TEMPLATE_REPEAT ) { if ( $ operationName == 'publish' && $ this -> ModuleName == 'content' ) { eZContentOperationCollection :: setVersionStatus ( $ operationParameters [ 'object_id' ] , $ operationParameters [ 'version' ] , eZContentObjectVersion :: STATUS_REPEAT ) ; } return eZModuleOperationInfo :: STATUS_REPEAT ; } else { return eZModuleOperationInfo :: STATUS_HALTED ; } } else if ( $ status [ 'Status' ] == eZTrigger :: WORKFLOW_CANCELLED or $ status [ 'Status' ] == eZTrigger :: WORKFLOW_RESET ) { return eZModuleOperationInfo :: STATUS_CANCELLED ; $ bodyReturnValue [ 'result' ] = $ status [ 'Result' ] ; } }
Executes an operation trigger
40,841
function executeClassMethod ( $ includeFile , $ className , $ methodName , $ operationParameterDefinitions , $ operationParameters ) { if ( ! class_exists ( $ className ) ) { include_once ( $ includeFile ) ; if ( ! class_exists ( $ className , false ) ) { return array ( 'internal_error' => eZModuleOperationInfo :: ERROR_NO_CLASS , 'internal_error_class_name' => $ className ) ; } } $ classObject = $ this -> objectForClass ( $ className ) ; if ( $ classObject === null ) { return array ( 'internal_error' => eZModuleOperationInfo :: ERROR_CLASS_INSTANTIATE_FAILED , 'internal_error_class_name' => $ className ) ; } if ( ! method_exists ( $ classObject , $ methodName ) ) { return array ( 'internal_error' => eZModuleOperationInfo :: ERROR_NO_CLASS_METHOD , 'internal_error_class_name' => $ className , 'internal_error_class_method_name' => $ methodName ) ; } $ parameterArray = array ( ) ; foreach ( $ operationParameterDefinitions as $ operationParameterDefinition ) { $ parameterName = $ operationParameterDefinition [ 'name' ] ; if ( isset ( $ operationParameterDefinition [ 'constant' ] ) ) { $ constantValue = $ operationParameterDefinition [ 'constant' ] ; $ parameterArray [ ] = $ constantValue ; } else if ( isset ( $ operationParameters [ $ parameterName ] ) ) { $ parameterArray [ ] = $ operationParameters [ $ parameterName ] ; } else { if ( $ operationParameterDefinition [ 'required' ] ) { return array ( 'internal_error' => eZModuleOperationInfo :: ERROR_MISSING_PARAMETER , 'internal_error_parameter_name' => $ parameterName ) ; } else if ( isset ( $ operationParameterDefinition [ 'default' ] ) ) { $ parameterArray [ ] = $ operationParameterDefinition [ 'default' ] ; } else { $ parameterArray [ ] = null ; } } } return call_user_func_array ( array ( $ classObject , $ methodName ) , $ parameterArray ) ; }
Executes a class method in an operation body
40,842
function objectForClass ( $ className ) { if ( ! isset ( $ GLOBALS [ 'eZModuleOperationClassObjectList' ] ) ) { $ GLOBALS [ 'eZModuleOperationClassObjectList' ] = array ( ) ; } if ( isset ( $ GLOBALS [ 'eZModuleOperationClassObjectList' ] [ $ className ] ) ) { return $ GLOBALS [ 'eZModuleOperationClassObjectList' ] [ $ className ] ; } return $ GLOBALS [ 'eZModuleOperationClassObjectList' ] [ $ className ] = new $ className ( ) ; }
Helper method that keeps and returns the instances of operation objects
40,843
public function generateAlwaysUpdatedCache ( $ quiet = false , $ cli = false , $ delay = true ) { foreach ( $ this -> alwaysUpdate as $ uri ) { if ( ! $ quiet and $ cli ) $ cli -> output ( "caching: $uri " , false ) ; $ this -> storeCache ( $ uri , $ this -> staticStorageDir , array ( ) , false , $ delay ) ; if ( ! $ quiet and $ cli ) $ cli -> output ( "done" ) ; } }
Generates the caches for all URLs that must always be generated .
40,844
public function generateCache ( $ force = false , $ quiet = false , $ cli = false , $ delay = true ) { $ staticURLArray = $ this -> cachedURLArray ( ) ; $ db = eZDB :: instance ( ) ; $ configSettingCount = count ( $ staticURLArray ) ; $ currentSetting = 0 ; $ parentList = array ( ) ; $ generateList = array ( ) ; foreach ( $ staticURLArray as $ url ) { $ currentSetting ++ ; if ( strpos ( $ url , '*' ) === false ) { $ generateList [ ] = $ url ; } else { $ queryURL = ltrim ( str_replace ( '*' , '' , $ url ) , '/' ) ; $ dir = dirname ( $ queryURL ) ; if ( $ dir == '.' ) $ dir = '' ; $ glob = basename ( $ queryURL ) ; $ parentList [ ] = array ( 'url' => $ dir , 'glob' => $ glob , 'org_url' => $ url ) ; } } while ( count ( $ generateList ) > 0 || count ( $ parentList ) > 0 ) { foreach ( $ generateList as $ generateURL ) { if ( ! $ quiet and $ cli ) $ cli -> output ( "caching: $generateURL " , false ) ; $ this -> cacheURL ( $ generateURL , false , ! $ force , $ delay ) ; if ( ! $ quiet and $ cli ) $ cli -> output ( "done" ) ; } $ generateList = array ( ) ; $ newParentList = array ( ) ; foreach ( $ parentList as $ parentURL ) { if ( isset ( $ parentURL [ 'parent_id' ] ) ) { $ elements = eZURLAliasML :: fetchByParentID ( $ parentURL [ 'parent_id' ] , true , true , false ) ; foreach ( $ elements as $ element ) { $ path = '/' . $ element -> getPath ( ) ; $ generateList [ ] = $ path ; $ newParentList [ ] = array ( 'parent_id' => $ element -> attribute ( 'id' ) ) ; } } else { if ( ! $ quiet and $ cli and $ parentURL [ 'glob' ] ) $ cli -> output ( "wildcard cache: " . $ parentURL [ 'url' ] . '/' . $ parentURL [ 'glob' ] . "*" ) ; $ elements = eZURLAliasML :: fetchByPath ( $ parentURL [ 'url' ] , $ parentURL [ 'glob' ] ) ; foreach ( $ elements as $ element ) { $ path = '/' . $ element -> getPath ( ) ; $ generateList [ ] = $ path ; $ newParentList [ ] = array ( 'parent_id' => $ element -> attribute ( 'id' ) ) ; } } } $ parentList = $ newParentList ; } }
Generates the static cache from the configured INI settings .
40,845
private function buildCacheDirPath ( $ siteAccess ) { $ dirParts = array ( ) ; $ ini = eZINI :: instance ( ) ; $ matchOderArray = $ ini -> variableArray ( 'SiteAccessSettings' , 'MatchOrder' ) ; foreach ( $ matchOderArray as $ matchOrderItem ) { switch ( $ matchOrderItem ) { case 'host_uri' : foreach ( $ ini -> variable ( 'SiteAccessSettings' , 'HostUriMatchMapItems' ) as $ hostUriMatchMapItem ) { $ parts = explode ( ';' , $ hostUriMatchMapItem ) ; if ( $ parts [ 2 ] === $ siteAccess ) { $ dirParts [ ] = $ this -> buildCacheDirPart ( ( $ parts [ 0 ] ? '/' . $ parts [ 0 ] : '' ) . ( $ parts [ 1 ] ? '/' . $ parts [ 1 ] : '' ) , $ siteAccess ) ; } } break ; case 'host' : foreach ( $ ini -> variable ( 'SiteAccessSettings' , 'HostMatchMapItems' ) as $ hostMatchMapItem ) { $ parts = explode ( ';' , $ hostMatchMapItem ) ; if ( $ parts [ 1 ] === $ siteAccess ) { $ dirParts [ ] = $ this -> buildCacheDirPart ( ( $ parts [ 0 ] ? '/' . $ parts [ 0 ] : '' ) , $ siteAccess ) ; } } break ; default : $ dirParts [ ] = $ this -> buildCacheDirPart ( '/' . $ siteAccess , $ siteAccess ) ; break ; } } return $ dirParts ; }
Generates a cache directory parts including path siteaccess name site URL depending on the match order type .
40,846
static function executeActions ( ) { if ( empty ( self :: $ actionList ) ) { return ; } $ fileContentCache = array ( ) ; $ doneDestList = array ( ) ; $ ini = eZINI :: instance ( 'staticcache.ini' ) ; $ clearByCronjob = ( $ ini -> variable ( 'CacheSettings' , 'CronjobCacheClear' ) == 'enabled' ) ; if ( $ clearByCronjob ) { $ db = eZDB :: instance ( ) ; } foreach ( self :: $ actionList as $ action ) { list ( $ action , $ parameters ) = $ action ; switch ( $ action ) { case 'store' : list ( $ destination , $ source ) = $ parameters ; if ( isset ( $ doneDestList [ $ destination ] ) ) continue 2 ; if ( $ clearByCronjob ) { $ param = $ db -> escapeString ( $ destination . ',' . $ source ) ; $ db -> query ( 'INSERT INTO ezpending_actions( action, param ) VALUES ( \'static_store\', \'' . $ param . '\' )' ) ; $ doneDestList [ $ destination ] = 1 ; } else { if ( ! isset ( $ fileContentCache [ $ source ] ) ) { if ( eZHTTPTool :: getDataByURL ( $ source , true , eZStaticCache :: USER_AGENT ) ) $ fileContentCache [ $ source ] = eZHTTPTool :: getDataByURL ( $ source , false , eZStaticCache :: USER_AGENT ) ; else $ fileContentCache [ $ source ] = false ; } if ( $ fileContentCache [ $ source ] === false ) { eZDebug :: writeError ( "Could not grab content (from $source), is the hostname correct and Apache running?" , 'Static Cache' ) ; } else { eZStaticCache :: storeCachedFile ( $ destination , $ fileContentCache [ $ source ] ) ; $ doneDestList [ $ destination ] = 1 ; } } break ; } } self :: $ actionList = array ( ) ; }
This function goes over the list of recorded actions and excecutes them .
40,847
public function resolveNamePattern ( $ limit = 0 , $ sequence = '' ) { $ this -> fetchContentAttributes ( ) ; $ objectName = $ this -> translatePattern ( ) ; $ db = eZDB :: instance ( ) ; $ limit = $ limit ? : self :: FIELD_NAME_MAX_SIZE ; if ( $ db -> countStringSize ( $ objectName ) <= $ limit ) { return $ objectName ; } return preg_replace ( "/[\pZ\pC]+$/u" , '' , $ db -> truncateString ( $ objectName , $ limit , 'name' , $ sequence ) ) . $ sequence ; }
Return the real name for an object name pattern
40,848
private function fetchContentAttributes ( ) { $ returnAttributeArray = array ( ) ; $ identifierArray = $ this -> getIdentifiers ( $ this -> origNamePattern ) ; $ attributes = $ this -> contentObject -> fetchAttributesByIdentifier ( $ identifierArray , $ this -> version , array ( $ this -> translation ) ) ; if ( is_array ( $ attributes ) ) { foreach ( $ attributes as $ attribute ) { $ identifier = $ attribute -> contentClassAttributeIdentifier ( ) ; $ returnAttributeArray [ $ identifier ] = $ attribute -> title ( ) ; } } else { $ returnAttributeArray = array ( ) ; } $ this -> attributeArray = $ returnAttributeArray ; }
Fetches the list of available class - identifiers in the token and it will only fetch the attributes which appear amongst the identifiers found in tokens .
40,849
private function translatePattern ( ) { $ tokenArray = $ this -> extractTokens ( $ this -> namePattern ) ; $ objectName = $ this -> namePattern ; foreach ( $ tokenArray as $ token ) { $ string = $ this -> resolveToken ( $ token ) ; $ objectName = str_replace ( $ token , $ string , $ objectName ) ; } return $ objectName ; }
Replaces tokens in the name pattern with their resolved values .
40,850
public function storeFieldData ( VersionInfo $ versionInfo , Field $ field ) { $ connection = $ this -> getConnection ( ) ; foreach ( $ field -> value -> externalData as $ meta ) { $ insertQuery = $ connection -> createInsertQuery ( ) ; $ insertQuery -> insertInto ( $ connection -> quoteTable ( self :: TABLE ) ) -> set ( $ connection -> quoteColumn ( "meta_name" ) , $ insertQuery -> bindValue ( $ meta [ "meta_name" ] , null , PDO :: PARAM_STR ) ) -> set ( $ connection -> quoteColumn ( "meta_content" ) , $ insertQuery -> bindValue ( $ meta [ "meta_content" ] , null , PDO :: PARAM_STR ) ) -> set ( $ connection -> quoteColumn ( "objectattribute_id" ) , $ insertQuery -> bindValue ( $ field -> id , null , PDO :: PARAM_INT ) ) -> set ( $ connection -> quoteColumn ( "objectattribute_version" ) , $ insertQuery -> bindValue ( $ versionInfo -> versionNo , null , PDO :: PARAM_INT ) ) ; $ insertQuery -> prepare ( ) -> execute ( ) ; } }
Stores the metas in the database based on the given field data
40,851
public function getFieldData ( VersionInfo $ versionInfo , Field $ field ) { $ field -> value -> externalData = $ this -> loadFieldData ( $ versionInfo , $ field ) ; }
Gets the metas stored in the field
40,852
public function process ( ContainerBuilder $ container ) { $ configs = $ container -> getExtensionConfig ( 'nova_ezseo' ) ; if ( isset ( $ configs [ 0 ] [ 'system' ] [ 'default' ] [ 'custom_fallback_service' ] ) ) { $ fallbackService = $ configs [ 0 ] [ 'system' ] [ 'default' ] [ 'custom_fallback_service' ] ; if ( $ fallbackService !== null ) { $ container -> getDefinition ( 'novactive.novaseobundle.twig_extension' ) -> addMethodCall ( "setCustomFallbackService" , [ new Reference ( $ fallbackService ) ] ) ; } } }
Process the configuration
40,853
public function mapFieldValueForm ( FormInterface $ fieldForm , FieldData $ data ) { $ fieldDefinition = $ data -> fieldDefinition ; $ formConfig = $ fieldForm -> getConfig ( ) ; $ metasConfig = $ this -> configResolver -> getParameter ( 'fieldtype_metas' , 'nova_ezseo' ) ; if ( empty ( $ data -> value -> metas ) ) { foreach ( $ metasConfig as $ key => $ meta ) { $ data -> value -> metas [ $ key ] = new Meta ( $ key , '' ) ; } } $ fieldForm -> add ( $ formConfig -> getFormFactory ( ) -> createBuilder ( ) -> create ( 'value' , MetasFieldType :: class , [ 'required' => $ fieldDefinition -> isRequired , 'label' => $ fieldDefinition -> getName ( $ formConfig -> getOption ( 'languageCode' ) ) , ] ) -> setAutoInitialize ( false ) -> getForm ( ) ) ; }
Maps Field form to current FieldType . Allows to add form fields for content edition .
40,854
public function addToContentType ( $ fieldName , ContentType $ contentType ) { try { $ contentTypeDraft = $ this -> contentTypeService -> loadContentTypeDraft ( $ contentType -> id ) ; } catch ( NotFoundException $ e ) { $ contentTypeDraft = $ this -> contentTypeService -> createContentTypeDraft ( $ contentType ) ; } $ typeUpdate = $ this -> contentTypeService -> newContentTypeUpdateStruct ( ) ; $ typeUpdate -> modificationDate = new DateTime ( ) ; $ knowLanguage = array_keys ( $ contentType -> getDescriptions ( ) ) ; if ( ! in_array ( $ contentType -> mainLanguageCode , $ knowLanguage ) ) { $ knowLanguage [ ] = $ contentType -> mainLanguageCode ; } $ fieldCreateStruct = $ this -> contentTypeService -> newFieldDefinitionCreateStruct ( $ fieldName , 'novaseometas' ) ; $ fieldCreateStruct -> names = array_fill_keys ( $ knowLanguage , $ this -> metaFieldName ) ; $ fieldCreateStruct -> descriptions = array_fill_keys ( $ knowLanguage , $ this -> metaFieldDescription ) ; $ fieldCreateStruct -> fieldGroup = $ this -> metaFieldGroup ; $ fieldCreateStruct -> position = 100 ; $ fieldCreateStruct -> isTranslatable = true ; $ fieldCreateStruct -> isRequired = false ; $ fieldCreateStruct -> isSearchable = false ; $ fieldCreateStruct -> isInfoCollector = false ; try { $ this -> contentTypeService -> updateContentTypeDraft ( $ contentTypeDraft , $ typeUpdate ) ; if ( $ contentTypeDraft -> getFieldDefinition ( $ fieldName ) == null ) { $ this -> contentTypeService -> addFieldDefinition ( $ contentTypeDraft , $ fieldCreateStruct ) ; } $ this -> contentTypeService -> publishContentTypeDraft ( $ contentTypeDraft ) ; return true ; } catch ( Exception $ e ) { $ this -> errorMessage = $ e -> getMessage ( ) ; return false ; } }
Adds metas field to existing ContentType .
40,855
public function fieldExists ( $ fieldName , ContentType $ contentType ) { $ fieldDefinition = $ contentType -> getFieldDefinition ( $ fieldName ) ; if ( empty ( $ fieldDefinition ) ) { return false ; } return true ; }
Checks if metas field exists in specified ContentType .
40,856
public function computeMetas ( Field $ field , ContentInfo $ contentInfo ) { $ fallback = false ; $ languages = $ this -> configResolver -> getParameter ( 'languages' ) ; $ contentType = $ this -> eZRepository -> getContentTypeService ( ) -> loadContentType ( $ contentInfo -> contentTypeId ) ; $ content = $ this -> eZRepository -> getContentService ( ) -> loadContentByContentInfo ( $ contentInfo , $ languages ) ; $ contentMetas = $ this -> innerComputeMetas ( $ content , $ field , $ contentType , $ fallback ) ; if ( $ fallback && ! $ this -> customFallBackService ) { $ rootNode = $ this -> eZRepository -> getLocationService ( ) -> loadLocation ( $ this -> configResolver -> getParameter ( "content.tree_root.location_id" ) ) ; $ rootContent = $ this -> eZRepository -> getContentService ( ) -> loadContentByContentInfo ( $ rootNode -> contentInfo , $ languages ) ; $ rootContentType = $ this -> eZRepository -> getContentTypeService ( ) -> loadContentType ( $ rootContent -> contentInfo -> contentTypeId ) ; $ metasIdentifier = $ this -> configResolver -> getParameter ( 'fieldtype_metas_identifier' , 'nova_ezseo' ) ; $ rootMetas = $ this -> innerComputeMetas ( $ rootContent , $ metasIdentifier , $ rootContentType , $ fallback ) ; foreach ( $ contentMetas as $ key => $ metaContent ) { if ( array_key_exists ( $ key , $ rootMetas ) ) { $ metaContent -> setContent ( $ metaContent -> isEmpty ( ) ? $ rootMetas [ $ key ] -> getContent ( ) : $ metaContent -> getContent ( ) ) ; } } } return '' ; }
Compute Metas of the Field thanks to its Content and the Fallback
40,857
protected function innerComputeMetas ( Content $ content , $ fieldDefIdentifier , ContentType $ contentType , & $ needFallback = false ) { if ( $ fieldDefIdentifier instanceof Field ) { $ metasFieldValue = $ fieldDefIdentifier -> value ; $ fieldDefIdentifier = $ fieldDefIdentifier -> fieldDefIdentifier ; } else { $ metasFieldValue = $ content -> getFieldValue ( $ fieldDefIdentifier ) ; } if ( $ metasFieldValue instanceof MetasFieldValue ) { $ metasConfig = $ this -> configResolver -> getParameter ( 'fieldtype_metas' , 'nova_ezseo' ) ; foreach ( $ metasConfig as $ metaName => $ metasSettings ) { if ( $ metasFieldValue -> nameExists ( $ metaName ) ) { $ meta = $ metasFieldValue -> metas [ $ metaName ] ; } else { $ meta = new Meta ( $ metaName ) ; $ metasFieldValue -> metas [ $ metaName ] = $ meta ; } if ( $ meta -> isEmpty ( ) ) { $ meta -> setContent ( $ metasConfig [ $ meta -> getName ( ) ] [ 'default_pattern' ] ) ; $ fieldDefinition = $ contentType -> getFieldDefinition ( $ fieldDefIdentifier ) ; $ configuration = $ fieldDefinition -> getFieldSettings ( ) [ 'configuration' ] ; if ( isset ( $ configuration [ $ meta -> getName ( ) ] ) && ! empty ( $ configuration [ $ meta -> getName ( ) ] ) ) { $ meta -> setContent ( $ configuration [ $ meta -> getName ( ) ] ) ; } } if ( ! $ this -> metaNameSchema -> resolveMeta ( $ meta , $ content , $ contentType ) ) { $ needFallback = true ; } } return $ metasFieldValue -> metas ; } return [ ] ; }
Compute Meta by reference
40,858
public function robotsAction ( ) { $ response = new Response ( ) ; $ response -> setSharedMaxAge ( 24 * 3600 ) ; $ robots = [ "User-agent: *" ] ; if ( $ this -> get ( 'kernel' ) -> getEnvironment ( ) != "prod" ) { $ robots [ ] = "Disallow: /" ; } $ rules = $ this -> getConfigResolver ( ) -> getParameter ( 'robots_disallow' , 'nova_ezseo' ) ; if ( is_array ( $ rules ) ) { foreach ( $ rules as $ rule ) { $ robots [ ] = "Disallow: {$rule}" ; } } $ response -> setContent ( implode ( "\n" , $ robots ) ) ; $ response -> headers -> set ( "Content-Type" , "text/plain" ) ; return $ response ; }
Robots . txt route
40,859
public function googleVerifAction ( $ key ) { if ( $ this -> getConfigResolver ( ) -> getParameter ( 'google_verification' , 'nova_ezseo' ) != $ key ) { throw new NotFoundHttpException ( "Google Verification Key not found" ) ; } $ response = new Response ( ) ; $ response -> setSharedMaxAge ( 24 * 3600 ) ; $ response -> setContent ( "google-site-verification: google{$key}.html" ) ; return $ response ; }
Google Verification route
40,860
public function bingVerifAction ( ) { if ( ! $ this -> getConfigResolver ( ) -> hasParameter ( 'bing_verification' , 'nova_ezseo' ) ) { throw new NotFoundHttpException ( "Bing Verification Key not found" ) ; } $ key = $ this -> getConfigResolver ( ) -> getParameter ( 'bing_verification' , 'nova_ezseo' ) ; $ xml = new DOMDocument ( "1.0" , "UTF-8" ) ; $ xml -> formatOutput = true ; $ root = $ xml -> createElement ( "users" ) ; $ root -> appendChild ( $ xml -> createElement ( "user" , $ key ) ) ; $ xml -> appendChild ( $ root ) ; $ response = new Response ( $ xml -> saveXML ( ) ) ; $ response -> setSharedMaxAge ( 24 * 3600 ) ; $ response -> headers -> set ( "Content-Type" , "text/xml" ) ; return $ response ; }
Bing Verification route
40,861
public function resolveMeta ( Meta $ meta , Content $ content , ContentType $ contentType = null ) { if ( $ contentType === null ) { $ contentType = $ this -> repository -> getContentTypeService ( ) -> loadContentType ( $ content -> contentInfo -> contentTypeId ) ; } $ resolveMultilingue = $ this -> resolve ( $ meta -> getContent ( ) , $ contentType , $ content -> fields , $ content -> versionInfo -> languageCodes ) ; if ( ( array_key_exists ( $ this -> languages [ 0 ] , $ resolveMultilingue ) ) && ( $ resolveMultilingue [ $ this -> languages [ 0 ] ] != '' ) ) { $ meta -> setContent ( $ resolveMultilingue [ $ this -> languages [ 0 ] ] ) ; return true ; } $ meta -> setContent ( "" ) ; return false ; }
Resolve a Meta Value
40,862
protected function handleRichTextValue ( RichTextValue $ value ) { return trim ( strip_tags ( $ this -> richTextConverter -> convert ( $ value -> xml ) -> saveHTML ( ) ) ) ; }
Get a Text from a Rich text field type
40,863
protected function handleRelationValue ( RelationValue $ value , $ languageCode ) { if ( ! $ value -> destinationContentId ) { return '' ; } $ relatedContent = $ this -> repository -> getContentService ( ) -> loadContent ( $ value -> destinationContentId ) ; if ( $ fieldImageValue = $ relatedContent -> getFieldValue ( 'image' ) ) { if ( $ fieldImageValue -> uri ) { return $ this -> getVariation ( $ fieldImageValue , "image" , $ languageCode , "social_network_image" ) ; } } return $ this -> translationHelper -> getTranslatedContentName ( $ relatedContent , $ languageCode ) ; }
Get the Relation in text or URL
40,864
protected function handleImageValue ( ImageValue $ value , $ fieldDefinitionIdentifier , $ languageCode ) { if ( ! $ value -> uri ) { return '' ; } return $ this -> getVariation ( $ value , $ fieldDefinitionIdentifier , $ languageCode , "social_network_image" ) ; }
Handle a Image attribute
40,865
protected function handleImageAssetValue ( ImageAssetValue $ value , $ fieldDefinitionIdentifier , $ languageCode ) { if ( ! $ value -> destinationContentId ) { return '' ; } $ content = $ this -> repository -> getContentService ( ) -> loadContent ( $ value -> destinationContentId ) ; foreach ( $ content -> getFields ( ) as $ field ) { if ( $ field -> value instanceof ImageValue ) { return $ this -> handleImageValue ( $ field -> value , $ fieldDefinitionIdentifier , $ languageCode ) ; } } return '' ; }
Handle a Image Asset attribute
40,866
protected function getQuery ( ) { $ locationService = $ this -> get ( "ezpublish.api.repository" ) -> getLocationService ( ) ; $ limitToRootLocation = $ this -> getConfigResolver ( ) -> getParameter ( 'limit_to_rootlocation' , 'nova_ezseo' ) ; $ excludes = $ this -> getConfigResolver ( ) -> getParameter ( 'sitemap_excludes' , 'nova_ezseo' ) ; $ query = new Query ( ) ; $ criterion [ ] = new Criterion \ Visibility ( Criterion \ Visibility :: VISIBLE ) ; if ( true === $ limitToRootLocation ) { $ criterion [ ] = new Criterion \ Subtree ( $ this -> getRootLocation ( ) -> pathString ) ; } foreach ( $ excludes [ 'contentTypeIdentifiers' ] as $ contentTypeIdentifier ) { $ criterion [ ] = new Criterion \ LogicalNot ( new Criterion \ ContentTypeIdentifier ( $ contentTypeIdentifier ) ) ; } foreach ( $ excludes [ 'subtrees' ] as $ locationId ) { $ excludedLocation = $ this -> getRepository ( ) -> sudo ( function ( ) use ( $ locationService , $ locationId ) { try { return $ locationService -> loadLocation ( $ locationId ) ; } catch ( \ Exception $ e ) { return false ; } } ) ; if ( $ excludedLocation ) { $ criterion [ ] = new Criterion \ LogicalNot ( new Criterion \ Subtree ( $ excludedLocation -> pathString ) ) ; } } foreach ( $ excludes [ 'locations' ] as $ locationId ) { $ criterion [ ] = new Criterion \ LogicalNot ( new Criterion \ LocationId ( $ locationId ) ) ; } $ query -> query = new Criterion \ LogicalAnd ( $ criterion ) ; $ query -> sortClauses = [ new SortClause \ DatePublished ( Query :: SORT_DESC ) ] ; return $ query ; }
Get the common Query
40,867
public function indexAction ( ) { $ searchService = $ this -> get ( "ezpublish.api.repository" ) -> getSearchService ( ) ; $ query = $ this -> getQuery ( ) ; $ query -> limit = 0 ; $ resultCount = $ searchService -> findLocations ( $ query ) -> totalCount ; $ sitemap = new DOMDocument ( "1.0" , "UTF-8" ) ; $ sitemap -> formatOutput = true ; if ( $ resultCount > static :: PACKET_MAX ) { $ root = $ sitemap -> createElement ( "sitemapindex" ) ; $ root -> setAttribute ( "xmlns" , "http://www.sitemaps.org/schemas/sitemap/0.9" ) ; $ sitemap -> appendChild ( $ root ) ; $ this -> fillSitemapIndex ( $ sitemap , $ resultCount , $ root ) ; return new Response ( $ sitemap -> saveXML ( ) , 200 , [ "Content-type" => "text/xml" ] ) ; } $ query -> limit = $ resultCount ; $ results = $ searchService -> findLocations ( $ query ) ; $ root = $ sitemap -> createElement ( "urlset" ) ; $ root -> setAttribute ( "xmlns" , "http://www.sitemaps.org/schemas/sitemap/0.9" ) ; $ this -> fillSitemap ( $ sitemap , $ root , $ results ) ; $ sitemap -> appendChild ( $ root ) ; $ response = new Response ( $ sitemap -> saveXML ( ) , 200 , [ "Content-type" => "text/xml" ] ) ; $ response -> setSharedMaxAge ( 24 * 3600 ) ; return $ response ; }
Sitemaps . xml route
40,868
protected function fillSitemap ( $ sitemap , $ root , SearchResult $ results ) { foreach ( $ results -> searchHits as $ searchHit ) { $ location = $ searchHit -> valueObject ; $ url = $ this -> generateUrl ( $ location , [ ] , UrlGeneratorInterface :: ABSOLUTE_URL ) ; $ modified = $ location -> contentInfo -> modificationDate -> format ( "c" ) ; $ loc = $ sitemap -> createElement ( "loc" , $ url ) ; $ lastmod = $ sitemap -> createElement ( "lastmod" , $ modified ) ; $ urlElt = $ sitemap -> createElement ( "url" ) ; $ urlElt -> appendChild ( $ loc ) ; $ urlElt -> appendChild ( $ lastmod ) ; $ root -> appendChild ( $ urlElt ) ; } }
Fill a sitemap
40,869
protected function fillSitemapIndex ( $ sitemap , $ numberOfResults , $ root ) { $ numberOfPage = ( int ) ceil ( $ numberOfResults / static :: PACKET_MAX ) ; for ( $ sitemapNumber = 1 ; $ sitemapNumber <= $ numberOfPage ; $ sitemapNumber ++ ) { $ sitemapElt = $ sitemap -> createElement ( "sitemap" ) ; $ locUrl = $ this -> generateUrl ( "_novaseo_sitemap_page" , [ "page" => $ sitemapNumber ] , UrlGeneratorInterface :: ABSOLUTE_URL ) ; $ loc = $ sitemap -> createElement ( "loc" , $ locUrl ) ; $ date = new DateTime ( ) ; $ modificationDate = $ date -> format ( 'c' ) ; $ mod = $ sitemap -> createElement ( 'lastmod' , $ modificationDate ) ; $ sitemapElt -> appendChild ( $ loc ) ; $ sitemapElt -> appendChild ( $ mod ) ; $ root -> appendChild ( $ sitemapElt ) ; } }
Fill the sitemap index
40,870
public function getContentTypesByIdentifier ( $ identifier ) { if ( strstr ( $ identifier , ',' ) ) { $ contentTypeArray = explode ( ',' , $ identifier ) ; } else { $ contentTypeArray [ ] = $ identifier ; } $ contentTypesCollection = array ( ) ; foreach ( $ contentTypeArray as $ contentTypeIdentifier ) { if ( ! empty ( $ contentTypeIdentifier ) ) { $ contentTypesCollection [ ] = $ this -> contentTypeService -> loadContentTypeByIdentifier ( $ contentTypeIdentifier ) ; } } return $ contentTypesCollection ; }
Returns ContentTypes array by ContentType identifier .
40,871
public function getContentTypesByGroup ( $ identifier ) { $ contentTypesCollection = array ( ) ; if ( $ contentTypeGroupIdentifier = $ identifier ) { $ contentTypeGroup = $ this -> contentTypeService -> loadContentTypeGroupByIdentifier ( $ contentTypeGroupIdentifier ) ; $ contentTypesCollection = $ this -> contentTypeService -> loadContentTypes ( $ contentTypeGroup ) ; } return $ contentTypesCollection ; }
Returns ContentTypes array by ContentType group .
40,872
public function frontpage ( ) { $ build = [ ] ; if ( $ this -> currentUser ( ) -> isAnonymous ( ) ) { $ build [ 'heading' ] = [ '#type' => 'markup' , '#markup' => $ this -> t ( 'Please log in for access to the content repository.' ) , ] ; $ build [ 'form' ] = $ this -> formBuilder ( ) -> getForm ( UserLoginForm :: class ) ; } else { if ( $ this -> currentUser ( ) -> hasPermission ( 'access content overview' ) ) { return $ this -> redirect ( 'view.content.page_1' ) ; } $ build [ 'heading' ] = [ '#type' => 'markup' , '#markup' => $ this -> t ( 'This site has no homepage content.' ) , ] ; } return $ build ; }
Displays the login form on the homepage and redirects authenticated users .
40,873
public function output ( \ stdClass $ object , ResponseInterface $ response ) { $ response -> setContentType ( 'application/json' ) ; $ response -> setJsonContent ( $ object ) ; $ response -> send ( ) ; }
This takes in object and outputs it in the respective format including sending the headers
40,874
private function validateError ( UploadedFile $ uploadedFile ) { switch ( $ uploadedFile -> getError ( ) ) { case UPLOAD_ERR_OK : break ; case UPLOAD_ERR_INI_SIZE : throw new Exception ( 'File too large, must not be greater than ' . ini_get ( 'upload_max_filesize' ) , 401 ) ; break ; case UPLOAD_ERR_NO_FILE : throw new Exception ( 'No File Uploaded' , 401 ) ; break ; default : throw new Exception ( $ uploadedFile -> getError ( ) , 401 ) ; break ; } }
Validates if there are any errors
40,875
private function validateExtension ( UploadedFile $ uploadedFile ) { $ pathInfo = pathinfo ( $ uploadedFile -> getName ( ) ) ; if ( ! isset ( $ pathInfo [ 'extension' ] ) ) { throw new Exception ( 'No Extension Found(' . $ uploadedFile -> getName ( ) . ')' , 401 ) ; } $ extension = strtolower ( $ pathInfo [ 'extension' ] ) ; if ( ! in_array ( $ extension , $ this -> getAllowedExtensions ( ) ) ) { throw new Exception ( 'Invalid Type of File Uploaded, valid types: ' . implode ( ', ' , $ this -> getAllowedExtensions ( ) ) , 401 ) ; } }
Validates the file extension
40,876
public function handle ( UploadedFile $ uploadedFile ) { $ this -> setUsed ( true ) ; $ this -> validateError ( $ uploadedFile ) ; $ this -> validateExtension ( $ uploadedFile ) ; $ handler = $ this -> getHandler ( ) ; $ handler ( $ uploadedFile ) ; }
Handles the file being uploaded
40,877
private function addToWhiteList ( array $ whiteList ) { $ current = $ this -> getWhiteList ( ) ; $ current = array_merge ( $ current , $ whiteList ) ; $ this -> setWhiteList ( $ current ) ; }
Add Fields to the white list so they are ignored
40,878
private function buildSearchCriteria ( ) { $ this -> buildSearchFieldsRecursive ( $ this -> getIndexCriteria ( ) -> getSearch ( ) , $ this -> getEntityFactory ( ) ) ; if ( ! is_null ( $ this -> getIndexCriteria ( ) -> getSearchTerm ( ) ) ) { $ this -> buildSearchTerm ( ) ; } }
Builds the search criteria
40,879
private function buildSearchFieldsRecursive ( Search $ search , ApiInterface $ entity ) { $ isRoot = false ; $ alias = $ search -> getAlias ( ) ; if ( is_null ( $ alias ) ) { $ isRoot = true ; $ alias = get_class ( $ entity ) ; } foreach ( $ search -> getFields ( ) as $ field => $ value ) { if ( in_array ( preg_replace ( "/[<|>]$/" , "" , $ field ) , $ entity -> getModelsMetaData ( ) -> getColumnMap ( $ entity ) ) ) { $ this -> addSearchField ( $ field , $ value , $ entity , $ alias ) ; } else { if ( ! $ isRoot || ! in_array ( $ field , $ this -> getWhiteList ( ) ) ) { throw new Exception ( 'Could not find the field: ' . ( $ isRoot ? '' : $ alias . '.' ) . $ field , 400 ) ; } } } foreach ( $ search -> getChildren ( ) as $ child ) { if ( in_array ( $ child -> getAlias ( ) , $ entity -> getParentRelationships ( ) ) ) { $ subEntity = $ this -> addJoin ( $ entity , $ child -> getAlias ( ) , false ) ; $ this -> buildSearchFieldsRecursive ( $ child , $ subEntity ) ; } elseif ( in_array ( $ child -> getAlias ( ) , $ entity -> getChildrenRelationships ( ) ) ) { throw new Exception ( 'Cannot search on children: ' . ( $ isRoot ? '' : $ alias . '.' ) . $ child -> getAlias ( ) , 400 ) ; } else { throw new Exception ( 'Could not find the parent: ' . ( $ isRoot ? '' : $ alias . '.' ) . $ child -> getAlias ( ) , 400 ) ; } } $ this -> addSoftDelete ( $ entity , $ alias ) ; }
Builds the search fields
40,880
public function addSoftDelete ( ApiInterface $ entity , $ alias ) { $ reflectionClass = new \ ReflectionClass ( SoftDelete :: class ) ; $ reflectionMethod = $ reflectionClass -> getMethod ( "getOptions" ) ; $ reflectionMethod -> setAccessible ( true ) ; $ softDeleteBehaviors = $ entity -> getAllBehaviorsByClassName ( SoftDelete :: class ) ; foreach ( $ softDeleteBehaviors as $ softDeleteBehavior ) { $ options = $ reflectionMethod -> invoke ( $ softDeleteBehavior ) ; $ sql = $ alias . '.' . $ options [ "field" ] . '!=?0' ; $ params = [ $ options [ "value" ] ] ; $ this -> getCriteriaHelper ( ) -> andWhere ( $ sql , $ params ) ; } }
Add soft delete to the where clause if the entity supports it
40,881
private function addSearchField ( $ name , $ value , ApiInterface $ entity , $ alias ) { $ operator = "=" ; if ( preg_match ( "/[<|>]$/" , $ name ) ) { $ operator = substr ( $ name , - 1 ) . "=" ; $ name = substr ( $ name , 0 , - 1 ) ; $ fieldTypes = $ entity -> getFieldTypes ( ) ; $ fieldTypesWhiteList = [ ApiInterface :: FIELD_TYPE_DATE , ApiInterface :: FIELD_TYPE_DATE_TIME , ApiInterface :: FIELD_TYPE_DOUBLE , ApiInterface :: FIELD_TYPE_INT ] ; if ( ! in_array ( $ fieldTypes [ $ name ] , $ fieldTypesWhiteList ) ) { throw new Exception ( 'Cannot perform ' . $ operator . ' search on any fields that are not in ' . implode ( ", " , $ fieldTypesWhiteList ) . ': ' . $ name . ' has a type of ' . $ fieldTypes [ $ name ] , 400 ) ; } } $ sql = $ alias . '.' . $ name ; if ( is_array ( $ value ) ) { $ attributes = [ ] ; foreach ( $ value as $ subValue ) { $ entity -> writeAttribute ( $ name , $ subValue ) ; $ attributes [ ] = $ entity -> readAttribute ( $ name ) ; } $ this -> getCriteria ( ) -> inWhere ( $ sql , $ attributes ) ; } else { $ entity -> writeAttribute ( $ name , $ value ) ; $ attribute = $ entity -> readAttribute ( $ name ) ; $ params = [ ] ; if ( is_null ( $ attribute ) ) { $ sql .= " IS NULL" ; } else { $ attribute .= '' ; if ( preg_match ( '@(^|[^\\\])%@' , $ attribute ) ) { $ operator = ' LIKE ' ; } $ sql .= $ operator . '?0' ; $ params [ ] = $ attribute ; } $ this -> getCriteriaHelper ( ) -> andWhere ( $ sql , $ params ) ; } }
Adds a specific field
40,882
private function addJoin ( ApiInterface $ entity , $ alias , $ forceFind ) { if ( in_array ( $ alias , $ entity -> getParentRelationships ( ) ) ) { $ referencedModel = $ entity -> addJoin ( $ this -> getCriteriaHelper ( ) , $ alias ) ; return new $ referencedModel ( ) ; } else { if ( $ forceFind ) { throw new Exception ( 'Could Not Find Part in current entity: ' . $ alias , 400 ) ; } return false ; } }
Adds a join
40,883
protected function buildSortParameter ( ) { $ sorts = $ this -> getIndexCriteria ( ) -> getSorts ( ) ; if ( ! empty ( $ sorts ) ) { $ orderBy = '' ; foreach ( $ sorts as $ sort ) { $ this -> buildSortRecursive ( $ this -> getEntityFactory ( ) , $ sort -> getFields ( ) , $ sort -> isAsc ( ) , $ orderBy ) ; } $ this -> getCriteria ( ) -> orderBy ( $ orderBy ) ; } }
Gets sort parameters from the URL .
40,884
private function buildSortRecursive ( ApiInterface $ entity , $ parts , $ isAsc , & $ orderBy , $ alias = null ) { if ( is_null ( $ alias ) ) { $ alias = get_class ( $ entity ) ; } $ part = array_shift ( $ parts ) ; if ( sizeOf ( $ parts ) == 0 ) { if ( in_array ( $ part , $ entity -> getModelsMetaData ( ) -> getColumnMap ( $ entity ) ) ) { if ( $ orderBy != '' ) { $ orderBy .= ',' ; } $ orderBy .= $ alias . '.' . $ part . ' ' . ( $ isAsc ? 'ASC' : 'DESC' ) ; } else { throw new Exception ( 'Could Not Find sort part: ' . $ part , 400 ) ; } } else { $ subAlias = ucfirst ( $ part ) ; $ subEntity = $ this -> addJoin ( $ entity , $ subAlias , true ) ; $ this -> buildSortRecursive ( $ subEntity , $ parts , $ isAsc , $ orderBy , $ subAlias ) ; } }
Builds the order by
40,885
private function buildLimit ( ) { $ this -> getCriteria ( ) -> limit ( $ this -> getIndexCriteria ( ) -> getLimit ( ) , $ this -> getIndexCriteria ( ) -> getOffset ( ) ) ; }
Builds the limit query
40,886
private function generateUrl ( $ queryParams ) { $ params = $ this -> getRequest ( ) -> getQuery ( ) ; if ( array_key_exists ( '_url' , $ params ) ) { unset ( $ params [ '_url' ] ) ; } foreach ( $ queryParams as $ name => $ value ) { $ params [ $ name ] = $ value ; } $ url = new Url ( ) ; return 'https://' . $ this -> getRequest ( ) -> getHttpHost ( ) . substr ( $ url -> get ( $ this -> getRequest ( ) -> getQuery ( '_url' ) , $ params ) , 1 ) ; }
Gets the url
40,887
public function generateLinks ( ) { return '<' . $ this -> generateUrl ( $ this -> getNextPageQueryCriteria ( ) ) . '>; rel="next",' . '<' . $ this -> generateUrl ( $ this -> getLastPageQueryCriteria ( ) ) . '>; rel="last",' . '<' . $ this -> generateUrl ( $ this -> getFirstPageQueryCriteria ( ) ) . '>; rel="first",' . '<' . $ this -> generateUrl ( $ this -> getPreviousPageQueryCriteria ( ) ) . '>; rel="prev"' ; }
Generates the links for the link header
40,888
private function buildTableComment ( ) { $ results = $ this -> getConfiguration ( ) -> getConnection ( ) -> query ( 'SHOW TABLE STATUS WHERE Name="' . $ this -> getTableName ( ) . '"' ) ; $ result = ( object ) $ results -> fetch ( ) ; $ this -> setComment ( $ result -> Comment ) ; }
Builds the table comment
40,889
private function buildIndexes ( ) { $ indexes = array ( ) ; $ results = $ this -> getConfiguration ( ) -> getConnection ( ) -> query ( 'SHOW INDEX FROM `' . $ this -> getTableName ( ) . '`' ) ; while ( $ result = $ results -> fetch ( ) ) { $ result = ( object ) $ result ; if ( ! array_key_exists ( $ result -> Key_name , $ indexes ) ) { $ indexes [ $ result -> Key_name ] = new Index ( ) ; } $ index = $ indexes [ $ result -> Key_name ] ; $ index -> setUnique ( ! $ result -> Non_unique ) ; $ index -> addColumn ( $ result -> Column_name ) ; $ index -> setPrimary ( $ result -> Key_name == 'PRIMARY' ) ; } $ this -> setIndexes ( $ indexes ) ; }
Builds the indexes
40,890
public static function writeAll ( Configuration $ configuration , $ ignoredTablesRegex = null ) { $ results = $ configuration -> getConnection ( ) -> query ( 'SHOW FULL TABLES WHERE Table_Type!="VIEW"' ) ; while ( $ result = $ results -> fetch ( ) ) { $ result = ( object ) $ result ; $ table = null ; foreach ( $ result as $ column ) { $ table = $ column ; break ; } if ( ! is_null ( $ ignoredTablesRegex ) && preg_match ( $ ignoredTablesRegex , $ table ) ) { continue ; } echo 'Writing: ' . $ table . "\n" ; $ index = new self ( $ configuration , $ table ) ; $ index -> write ( ) ; } }
Writes all of the models
40,891
private function buildFields ( ) { $ fields = array ( ) ; $ results = $ this -> getConfiguration ( ) -> getConnection ( ) -> query ( 'SHOW COLUMNS FROM `' . $ this -> getTableName ( ) . '`' ) ; $ dbName = $ this -> getCurrentDatabaseName ( ) ; while ( $ result = $ results -> fetch ( ) ) { $ result = ( object ) $ result ; $ params = array ( $ dbName , $ this -> getTableName ( ) , $ result -> Field ) ; $ informationResults = $ this -> getConfiguration ( ) -> getInformationSchemaConnection ( ) -> query ( 'SELECT * FROM `COLUMNS` WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME=?' , $ params ) ; $ informationResult = ( object ) $ informationResults -> fetch ( ) ; $ field = new Field ( $ result , $ this -> getTableName ( ) , $ informationResult ) ; switch ( $ field -> getType ( ) ) { case 'Date' : $ this -> getAbstractClass ( ) -> addUse ( $ this -> getConfiguration ( ) -> getDateClassName ( ) ) ; break ; case 'DateTime' : $ this -> getAbstractClass ( ) -> addUse ( $ this -> getConfiguration ( ) -> getDateTimeClassName ( ) ) ; break ; } $ fields [ ] = $ field ; } usort ( $ fields , function ( Field $ fieldA , Field $ fieldB ) { return strcasecmp ( $ fieldA -> getShortName ( ) , $ fieldB -> getShortName ( ) ) ; } ) ; $ this -> setFields ( $ fields ) ; }
Builds the fields and types
40,892
private function buildRelationshipsBuffer ( ) { $ buffer = '' ; foreach ( $ this -> getRelationships ( ) as $ relationship ) { $ buffer .= ' $this->' . $ relationship -> getRelationshipType ( ) . '( \'' . $ this -> getField ( $ relationship -> getLocalColumn ( ) ) -> getShortName ( ) . '\', \'' . $ relationship -> getRemoteModel ( ) . '\', \'' . $ relationship -> getRemoteShortColumn ( ) . '\', array( \'alias\' => \'' . $ relationship -> getAlias ( ) . '\', \'foreignKey\' => array( \'message\' => \'The ' . $ this -> getTableName ( ) . ' cannot be deleted because other ' . $ relationship -> getRemoteTable ( ) . '(s) are attached\', \'action\' => Relation::' . $ relationship -> getAction ( ) . ' ), \'reusable\' => true ) );' . "\n" ; } return $ buffer ; }
Builds the relationship buffer
40,893
private function getField ( $ columnName ) { foreach ( $ this -> getFields ( ) as $ field ) { if ( $ field -> getName ( ) == $ columnName ) { return $ field ; } } echo 'Could Not Find Field ' . $ this -> getTableName ( ) . '.' . $ columnName . "\n" ; return false ; }
Gets a field by it s original name
40,894
private function buildVariableDefinitions ( ) { foreach ( $ this -> getFields ( ) as $ field ) { $ variable = new Object \ Variable ( ) ; $ variable -> setName ( $ field -> getShortName ( ) ) ; $ variable -> setAccess ( 'protected' ) ; $ variable -> setAutoIncrementing ( $ field -> isAutoIncrementing ( ) ) ; $ variable -> setDescription ( $ field -> getDescription ( ) ) ; $ variable -> setLength ( $ field -> getLength ( ) ) ; $ variable -> setNullable ( $ field -> isNullable ( ) ) ; $ variable -> setPrimary ( $ field -> isPrimary ( ) ) ; $ variable -> setType ( $ field -> getType ( ) ) ; $ this -> getAbstractClass ( ) -> addVariable ( $ variable ) ; } }
Builds the variable definitions
40,895
private function buildColumnMap ( ) { $ content = ' return $this->columnMapMissingColumnsFix(array(' . "\n" ; foreach ( $ this -> getFields ( ) as $ field ) { $ content .= ' \'' . $ field -> getName ( ) . '\' => \'' . $ field -> getShortName ( ) . '\',' . "\n" ; } $ content = substr ( $ content , 0 , - 2 ) . "\n" ; $ content .= ' ));' ; $ method = new Object \ Method ( ) ; $ method -> setAccess ( 'public' ) ; $ method -> setDescription ( 'Updates so we can use the shortened names, without changing the database' ) ; $ method -> setName ( 'columnMap' ) ; $ method -> setReturnType ( 'string[] keys are the real names, values are the names in the application' ) ; $ method -> setContent ( $ content ) ; $ this -> getAbstractClass ( ) -> addMethod ( $ method ) ; $ this -> getAbstractClass ( ) -> addUse ( 'Phalcon\Db\Column' ) ; $ content = ' return [' ; foreach ( $ this -> getFields ( ) as $ field ) { $ content .= ' \'' . $ field -> getShortName ( ) . '\' => Column::' . $ field -> getPhalconColumnType ( ) . ',' . "\n" ; } $ content .= ' ];' ; $ method = new Object \ Method ( ) ; $ method -> setAccess ( 'public' ) ; $ method -> setDescription ( 'Used for determining the database type' ) ; $ method -> setName ( 'getDatabaseTypes' ) ; $ method -> setReturnType ( 'string[] keys are the column names, values are the DB\Column' ) ; $ method -> setContent ( $ content ) ; $ this -> getAbstractClass ( ) -> addMethod ( $ method ) ; }
Builds the column maps
40,896
private function buildRelationshipsList ( ) { $ content = ' return array(' . "\n" ; $ added = false ; foreach ( $ this -> getRelationships ( ) as $ relationship ) { if ( ! $ relationship -> isPlural ( ) ) { $ added = true ; $ content .= ' \'' . $ relationship -> getAlias ( ) . '\',' . "\n" ; } } if ( $ added ) { $ content = substr ( $ content , 0 , - 2 ) . "\n" ; } $ content .= ' );' ; $ method = new Object \ Method ( ) ; $ method -> setAccess ( 'public' ) ; $ method -> setDescription ( 'Returns a list of all parent relationships, these will all return a Base Model instance' ) ; $ method -> setName ( 'getParentRelationships' ) ; $ method -> setReturnType ( 'string[] values are the alias of the relationship' ) ; $ method -> setContent ( $ content ) ; $ this -> getAbstractClass ( ) -> addMethod ( $ method ) ; $ content = ' return array(' . "\n" ; $ added = false ; foreach ( $ this -> getRelationships ( ) as $ relationship ) { if ( $ relationship -> isPlural ( ) ) { $ added = true ; $ content .= ' \'' . $ relationship -> getAlias ( ) . '\',' . "\n" ; } } if ( $ added ) { $ content = substr ( $ content , 0 , - 2 ) . "\n" ; } $ content .= ' );' ; $ method = new Object \ Method ( ) ; $ method -> setAccess ( 'public' ) ; $ method -> setDescription ( 'Returns a list of all children relationships, these will all return a ResultSet' ) ; $ method -> setName ( 'getChildrenRelationships' ) ; $ method -> setReturnType ( 'string[] values are the alias of the relationship' ) ; $ method -> setContent ( $ content ) ; $ this -> getAbstractClass ( ) -> addMethod ( $ method ) ; }
Builds the relationships list methods
40,897
private function buildEnumConstants ( ) { foreach ( $ this -> getFields ( ) as $ field ) { $ options = $ field -> getEnumOptions ( ) ; if ( ! is_null ( $ options ) ) { $ enumClass = new Object \ Index ( $ this -> getConfiguration ( ) ) ; $ enumClass -> setNamespace ( $ this -> getAbstractClass ( ) -> getNamespace ( ) . '\\' . $ this -> getAbstractClass ( ) -> getName ( ) ) ; $ enumClass -> setName ( ucfirst ( $ field -> getShortName ( ) ) ) ; $ enumClass -> addUse ( 'Bullhorn\FastRest\Api\Services\SplEnum' ) ; $ enumClass -> setExtends ( 'SplEnum' ) ; foreach ( $ options as $ option ) { $ optionName = lcfirst ( $ option ) ; if ( $ optionName == '' ) { $ optionName = 'EMPTY' ; } $ this -> getAbstractClass ( ) -> addConstant ( $ this -> filterConstant ( $ field -> getShortName ( ) . '_' . $ optionName ) , $ option ) ; $ enumClass -> addConstant ( $ this -> filterConstant ( $ optionName ) , $ option ) ; } $ enumClass -> write ( ) ; } } }
Builds the enum constants
40,898
private function buildOnConstruct ( ) { $ content = '' ; foreach ( $ this -> getFields ( ) as $ field ) { if ( in_array ( $ field -> getType ( ) , array ( 'Date' , 'DateTime' ) ) ) { $ content .= ' $this->set' . ucfirst ( $ field -> getShortName ( ) ) . '(new ' . $ field -> getType ( ) . '($this->get' . ucfirst ( $ field -> getShortName ( ) ) . '()));' ; } } $ content .= ' parent::onConstruct();' ; $ method = new Object \ Method ( ) ; $ method -> setAccess ( 'public' ) ; $ method -> setDescription ( 'Used to Construct an instance' ) ; $ method -> setName ( 'onConstruct' ) ; $ method -> setReturnType ( 'void' ) ; $ method -> setContent ( $ content ) ; $ this -> getAbstractClass ( ) -> addMethod ( $ method ) ; }
Builds the on construct method
40,899
private function buildGetSource ( ) { $ method = new Object \ Method ( ) ; $ method -> setAccess ( 'public' ) ; $ method -> setDescription ( 'This returns the table name' ) ; $ method -> setName ( 'getSource' ) ; $ method -> setReturnType ( 'string' ) ; $ method -> setContent ( 'return \'' . $ this -> getTableName ( ) . '\';' ) ; $ this -> getAbstractClass ( ) -> addMethod ( $ method ) ; }
Builds the getSource