idx int64 0 60.3k | question stringlengths 99 4.85k | target stringlengths 5 718 |
|---|---|---|
500 | public function visitExpressionNode ( ExpressionNode $ node ) { $ leftValue = $ node -> getLeft ( ) -> accept ( $ this ) ; $ operator = $ node -> getOperator ( ) ; if ( ! $ operator ) return "$leftValue" ; $ right = $ node -> getRight ( ) ; if ( $ right ) { $ rightValue = $ node -> getRight ( ) -> accept ( $ this ) ; return "($operator, $leftValue, $rightValue)" ; } else { return "($operator, $leftValue)" ; } } | Print an ExpressionNode . |
501 | public function visitFunctionNode ( FunctionNode $ node ) { $ functionName = $ node -> getName ( ) ; $ operand = $ node -> getOperand ( ) -> accept ( $ this ) ; return "$functionName($operand)" ; } | Print a FunctionNode . |
502 | public function parse ( array $ tokens ) { $ tokens = $ this -> filterTokens ( $ tokens ) ; if ( static :: allowImplicitMultiplication ( ) ) { $ tokens = $ this -> parseImplicitMultiplication ( $ tokens ) ; } $ this -> tokens = $ tokens ; return $ this -> shuntingYard ( $ tokens ) ; } | Parse list of tokens |
503 | private function shuntingYard ( array $ tokens ) { $ this -> operatorStack = new Stack ( ) ; $ this -> operandStack = new Stack ( ) ; $ lastNode = null ; for ( $ index = 0 ; $ index < count ( $ tokens ) ; $ index ++ ) { $ token = $ tokens [ $ index ] ; if ( $ this -> rationalFactory ) { $ node = Node :: rationalFactory ( $ token ) ; } else { $ node = Node :: factory ( $ token ) ; } if ( $ token -> getType ( ) == TokenType :: CloseParenthesis ) { $ this -> handleSubExpression ( ) ; } elseif ( $ node -> isTerminal ( ) ) { $ this -> operandStack -> push ( $ node ) ; } elseif ( $ node instanceof FunctionNode ) { $ this -> operatorStack -> push ( $ node ) ; } elseif ( $ node instanceof SubExpressionNode ) { $ this -> operatorStack -> push ( $ node ) ; } elseif ( $ node instanceof PostfixOperatorNode ) { $ op = $ this -> operandStack -> pop ( ) ; if ( $ op == NULL ) throw new SyntaxErrorException ( ) ; $ this -> operandStack -> push ( new FunctionNode ( $ node -> getOperator ( ) , $ op ) ) ; } elseif ( $ node instanceof ExpressionNode ) { $ unary = $ this -> isUnary ( $ node , $ lastNode ) ; if ( $ unary ) { switch ( $ token -> getType ( ) ) { case TokenType :: AdditionOperator : $ node = null ; break ; case TokenType :: SubtractionOperator : $ node -> setOperator ( '~' ) ; break ; } } else { while ( $ node -> lowerPrecedenceThan ( $ this -> operatorStack -> peek ( ) ) ) { $ popped = $ this -> operatorStack -> pop ( ) ; $ popped = $ this -> handleExpression ( $ popped ) ; $ this -> operandStack -> push ( $ popped ) ; } } if ( $ node ) $ this -> operatorStack -> push ( $ node ) ; } if ( $ node ) $ lastNode = $ node ; } while ( ! $ this -> operatorStack -> isEmpty ( ) ) { $ node = $ this -> operatorStack -> pop ( ) ; $ node = $ this -> handleExpression ( $ node ) ; $ this -> operandStack -> push ( $ node ) ; } if ( $ this -> operandStack -> count ( ) > 1 ) { throw new SyntaxErrorException ( ) ; } return $ this -> operandStack -> pop ( ) ; } | Implementation of the shunting yard parsing algorithm |
504 | protected function handleExpression ( $ node ) { if ( $ node instanceof FunctionNode ) throw new ParenthesisMismatchException ( $ node -> getOperator ( ) ) ; if ( $ node instanceof SubExpressionNode ) throw new ParenthesisMismatchException ( $ node -> getOperator ( ) ) ; if ( ! $ this -> simplifyingParser ) return $ this -> naiveHandleExpression ( $ node ) ; if ( $ node -> getOperator ( ) == '~' ) { $ left = $ this -> operandStack -> pop ( ) ; if ( $ left === null ) { throw new SyntaxErrorException ( ) ; } if ( $ left instanceof NumberNode ) { return new NumberNode ( - $ left -> getValue ( ) ) ; } if ( $ left instanceof IntegerNode ) { return new IntegerNode ( - $ left -> getValue ( ) ) ; } if ( $ left instanceof RationalNode ) { return new RationalNode ( - $ left -> getNumerator ( ) , $ left -> getDenominator ( ) ) ; } $ node -> setOperator ( '-' ) ; $ node -> setLeft ( $ left ) ; return $ this -> nodeFactory -> simplify ( $ node ) ; } $ right = $ this -> operandStack -> pop ( ) ; $ left = $ this -> operandStack -> pop ( ) ; if ( $ right === null || $ left === null ) { throw new SyntaxErrorException ( ) ; } $ node -> setLeft ( $ left ) ; $ node -> setRight ( $ right ) ; return $ this -> nodeFactory -> simplify ( $ node ) ; } | Populate node with operands . |
505 | protected function naiveHandleExpression ( $ node ) { if ( $ node -> getOperator ( ) == '~' ) { $ left = $ this -> operandStack -> pop ( ) ; if ( $ left === null ) { throw new SyntaxErrorException ( ) ; } $ node -> setOperator ( '-' ) ; $ node -> setLeft ( $ left ) ; return $ node ; } $ right = $ this -> operandStack -> pop ( ) ; $ left = $ this -> operandStack -> pop ( ) ; if ( $ right === null || $ left === null ) { throw new SyntaxErrorException ( ) ; } $ node -> setLeft ( $ left ) ; $ node -> setRight ( $ right ) ; return $ node ; } | Populate node with operands without any simplification . |
506 | protected function filterTokens ( array $ tokens ) { $ filteredTokens = array_filter ( $ tokens , function ( Token $ t ) { return $ t -> getType ( ) !== TokenType :: Whitespace ; } ) ; return array_values ( $ filteredTokens ) ; } | Remove Whitespace from the token list . |
507 | protected function handleSubExpression ( ) { $ clean = false ; while ( $ popped = $ this -> operatorStack -> pop ( ) ) { if ( $ popped instanceof SubExpressionNode ) { $ clean = true ; break ; } $ node = $ this -> handleExpression ( $ popped ) ; $ this -> operandStack -> push ( $ node ) ; } if ( ! $ clean ) { throw new ParenthesisMismatchException ( ) ; } $ previous = $ this -> operatorStack -> peek ( ) ; if ( $ previous instanceof FunctionNode ) { $ node = $ this -> operatorStack -> pop ( ) ; $ operand = $ this -> operandStack -> pop ( ) ; $ node -> setOperand ( $ operand ) ; $ this -> operandStack -> push ( $ node ) ; } } | Handle a closing parenthesis popping operators off the operator stack until we find a matching opening parenthesis . |
508 | private function numericExponent ( $ leftOperand , $ rightOperand ) { if ( $ this -> isNumeric ( $ leftOperand ) && $ this -> isNumeric ( $ rightOperand ) ) { if ( $ leftOperand -> getValue ( ) == 0 && $ rightOperand -> getValue ( ) == 0 ) throw new DivisionByZeroException ( ) ; } if ( $ rightOperand -> getValue ( ) == 0 ) return new IntegerNode ( 1 ) ; if ( $ rightOperand -> getValue ( ) == 1 ) return $ leftOperand ; if ( ! $ this -> isNumeric ( $ leftOperand ) || ! $ this -> isNumeric ( $ rightOperand ) ) { return null ; } $ type = $ this -> resultingType ( $ leftOperand , $ rightOperand ) ; switch ( $ type ) { case Node :: NumericFloat : return new NumberNode ( pow ( $ leftOperand -> getValue ( ) , $ rightOperand -> getValue ( ) ) ) ; case Node :: NumericInteger : if ( $ rightOperand -> getValue ( ) > 0 ) { return new IntegerNode ( pow ( $ leftOperand -> getValue ( ) , $ rightOperand -> getValue ( ) ) ) ; } } return null ; } | Simplify an expression x^y when y is numeric . |
509 | public static function rationalFactory ( Token $ token ) { switch ( $ token -> getType ( ) ) { case TokenType :: PosInt : case TokenType :: Integer : $ x = intval ( $ token -> getValue ( ) ) ; return new IntegerNode ( $ x ) ; case TokenType :: RealNumber : $ x = floatval ( str_replace ( ',' , '.' , $ token -> getValue ( ) ) ) ; return new NumberNode ( $ x ) ; case TokenType :: Identifier : return new VariableNode ( $ token -> getValue ( ) ) ; case TokenType :: Constant : return new ConstantNode ( $ token -> getValue ( ) ) ; case TokenType :: FunctionName : return new FunctionNode ( $ token -> getValue ( ) , null ) ; case TokenType :: OpenParenthesis : return new SubExpressionNode ( $ token -> getValue ( ) ) ; case TokenType :: AdditionOperator : case TokenType :: SubtractionOperator : case TokenType :: MultiplicationOperator : case TokenType :: DivisionOperator : case TokenType :: ExponentiationOperator : return new ExpressionNode ( null , $ token -> getValue ( ) , null ) ; case TokenType :: FactorialOperator : return new PostfixOperatorNode ( $ token -> getValue ( ) , null ) ; default : return null ; } } | Node factory creating an appropriate Node from a Token . |
510 | public function complexity ( ) { if ( $ this instanceof IntegerNode || $ this instanceof VariableNode || $ this instanceof ConstantNode ) { return 1 ; } elseif ( $ this instanceof RationalNode || $ this instanceof NumberNode ) { return 2 ; } elseif ( $ this instanceof FunctionNode ) { return 5 + $ this -> getOperand ( ) -> complexity ( ) ; } elseif ( $ this instanceof ExpressionNode ) { $ operator = $ this -> getOperator ( ) ; $ left = $ this -> getLeft ( ) ; $ right = $ this -> getRight ( ) ; switch ( $ operator ) { case '+' : case '-' : case '*' : return 1 + $ left -> complexity ( ) + ( ( $ right === null ) ? 0 : $ right -> complexity ( ) ) ; case '/' : return 3 + $ left -> complexity ( ) + ( ( $ right === null ) ? 0 : $ right -> complexity ( ) ) ; case '^' : return 8 + $ left -> complexity ( ) + ( ( $ right === null ) ? 0 : $ right -> complexity ( ) ) ; } } return 1000 ; } | Rough estimate of the complexity of the AST . |
511 | public function isTerminal ( ) { if ( $ this instanceof NumberNode ) { return true ; } if ( $ this instanceof IntegerNode ) { return true ; } if ( $ this instanceof RationalNode ) { return true ; } if ( $ this instanceof VariableNode ) { return true ; } if ( $ this instanceof ConstantNode ) { return true ; } return false ; } | Returns true if the node is a terminal node i . e . a NumerNode VariableNode or ConstantNode . |
512 | public function match ( $ input ) { $ result = preg_match ( $ this -> pattern , $ input , $ matches , PREG_OFFSET_CAPTURE ) ; if ( $ result === false ) throw new \ Exception ( preg_last_error ( ) ) ; if ( $ result === 0 ) return null ; return $ this -> getTokenFromMatch ( $ matches [ 0 ] ) ; } | Try to match the given input to the current TokenDefinition . |
513 | private function getTokenFromMatch ( $ match ) { $ value = $ match [ 0 ] ; $ offset = $ match [ 1 ] ; if ( $ offset !== 0 ) return null ; if ( $ this -> value ) $ value = $ this -> value ; return new Token ( $ value , $ this -> tokenType , $ match [ 0 ] ) ; } | Convert matching string to an actual Token . |
514 | public function parse ( $ text ) { $ this -> tokens = $ this -> lexer -> tokenize ( $ text ) ; $ this -> tree = $ this -> parser -> parse ( $ this -> tokens ) ; return $ this -> tree ; } | Parse the given mathematical expression into an abstract syntax tree . |
515 | public function makeNode ( $ leftOperand , $ rightOperand ) { if ( $ rightOperand === null ) return $ this -> createUnaryMinusNode ( $ leftOperand ) ; $ leftOperand = $ this -> sanitize ( $ leftOperand ) ; $ rightOperand = $ this -> sanitize ( $ rightOperand ) ; $ node = $ this -> numericTerms ( $ leftOperand , $ rightOperand ) ; if ( $ node ) return $ node ; if ( $ leftOperand -> compareTo ( $ rightOperand ) ) { return new IntegerNode ( 0 ) ; } return new ExpressionNode ( $ leftOperand , '-' , $ rightOperand ) ; } | Create a Node representing leftOperand - rightOperand |
516 | public function visitExpressionNode ( ExpressionNode $ node ) { $ operator = $ node -> getOperator ( ) ; $ left = $ node -> getLeft ( ) ; $ right = $ node -> getRight ( ) ; switch ( $ operator ) { case '+' : $ leftValue = $ left -> accept ( $ this ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node ) ; return "$leftValue+$rightValue" ; case '-' : if ( $ right ) { $ leftValue = $ left -> accept ( $ this ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node ) ; return "$leftValue-$rightValue" ; } else { $ leftValue = $ this -> parenthesize ( $ left , $ node ) ; return "-$leftValue" ; } case '*' : $ operator = '' ; if ( $ this -> MultiplicationNeedsCdot ( $ left , $ right ) ) { $ operator = '\cdot ' ; } $ leftValue = $ this -> parenthesize ( $ left , $ node ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node ) ; return "$leftValue$operator$rightValue" ; case '/' : if ( $ this -> solidus ) { $ leftValue = $ this -> parenthesize ( $ left , $ node ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node ) ; return "$leftValue$operator$rightValue" ; } return '\frac{' . $ left -> accept ( $ this ) . '}{' . $ right -> accept ( $ this ) . '}' ; case '^' : $ leftValue = $ this -> parenthesize ( $ left , $ node , '' , true ) ; $ this -> solidus = true ; $ result = $ leftValue . '^' . $ this -> bracesNeeded ( $ right ) ; $ this -> solidus = false ; return $ result ; } } | Generate LaTeX code for an ExpressionNode |
517 | private function MultiplicationNeedsCdot ( $ left , $ right ) { if ( $ left instanceof FunctionNode ) { return true ; } if ( $ this -> isNumeric ( $ right ) ) { return true ; } if ( $ right instanceof ExpressionNode && $ this -> isNumeric ( $ right -> getLeft ( ) ) ) { return true ; } return false ; } | Check if a multiplication needs an inserted \ cdot or if it can be safely written with implicit multiplication . |
518 | private function visitFactorialNode ( FunctionNode $ node ) { $ functionName = $ node -> getName ( ) ; $ op = $ node -> getOperand ( ) ; $ operand = $ op -> accept ( $ this ) ; if ( $ this -> isNumeric ( $ op ) ) { if ( $ op -> getValue ( ) < 0 ) { $ operand = "($operand)" ; } } elseif ( $ op instanceof VariableNode || $ op instanceof ConstantNode ) { } else { $ operand = "($operand)" ; } return "$operand$functionName" ; } | Generate LaTeX code for factorials |
519 | public function visitFunctionNode ( FunctionNode $ node ) { $ functionName = $ node -> getName ( ) ; $ operand = $ node -> getOperand ( ) -> accept ( $ this ) ; switch ( $ functionName ) { case 'sqrt' : return "\\$functionName{" . $ node -> getOperand ( ) -> accept ( $ this ) . '}' ; case 'exp' : $ operand = $ node -> getOperand ( ) ; if ( $ operand -> complexity ( ) < 10 ) { $ this -> solidus = true ; $ result = 'e^' . $ this -> bracesNeeded ( $ operand ) ; $ this -> solidus = false ; return $ result ; } return '\exp(' . $ operand -> accept ( $ this ) . ')' ; case 'ln' : case 'log' : case 'sin' : case 'cos' : case 'tan' : case 'arcsin' : case 'arccos' : case 'arctan' : break ; case 'abs' : $ operand = $ node -> getOperand ( ) ; return '\lvert ' . $ operand -> accept ( $ this ) . '\rvert ' ; case '!' : case '!!' : return $ this -> visitFactorialNode ( $ node ) ; default : $ functionName = 'operatorname{' . $ functionName . '}' ; } return "\\$functionName($operand)" ; } | Generate LaTeX code for a FunctionNode |
520 | public function visitExpressionNode ( ExpressionNode $ node ) { $ operator = $ node -> getOperator ( ) ; $ left = $ node -> getLeft ( ) ; $ right = $ node -> getRight ( ) ; switch ( $ operator ) { case '+' : $ leftValue = $ left -> accept ( $ this ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node ) ; return "$leftValue+$rightValue" ; case '-' : if ( $ right ) { $ leftValue = $ left -> accept ( $ this ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node ) ; return "$leftValue-$rightValue" ; } else { $ leftValue = $ this -> parenthesize ( $ left , $ node ) ; return "-$leftValue" ; } case '*' : case '/' : $ leftValue = $ this -> parenthesize ( $ left , $ node , '' , false ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node , '' , true ) ; return "$leftValue$operator$rightValue" ; case '^' : $ leftValue = $ this -> parenthesize ( $ left , $ node , '' , true ) ; $ rightValue = $ this -> parenthesize ( $ right , $ node , '' , false ) ; return "$leftValue$operator$rightValue" ; } } | Generate ASCII output code for an ExpressionNode |
521 | public static function canFactorsInImplicitMultiplication ( $ token1 , $ token2 ) { if ( $ token1 === null || $ token2 === null ) return false ; $ check1 = ( $ token1 -> type == TokenType :: PosInt || $ token1 -> type == TokenType :: Integer || $ token1 -> type == TokenType :: RealNumber || $ token1 -> type == TokenType :: Constant || $ token1 -> type == TokenType :: Identifier || $ token1 -> type == TokenType :: FunctionName || $ token1 -> type == TokenType :: CloseParenthesis || $ token1 -> type == TokenType :: FactorialOperator || $ token1 -> type == TokenType :: SemiFactorialOperator ) ; if ( ! $ check1 ) return false ; $ check2 = ( $ token2 -> type == TokenType :: PosInt || $ token2 -> type == TokenType :: Integer || $ token2 -> type == TokenType :: RealNumber || $ token2 -> type == TokenType :: Constant || $ token2 -> type == TokenType :: Identifier || $ token2 -> type == TokenType :: FunctionName || $ token2 -> type == TokenType :: OpenParenthesis ) ; if ( ! $ check2 ) return false ; if ( $ token1 -> type == TokenType :: FunctionName && $ token2 -> type == TokenType :: OpenParenthesis ) return false ; return true ; } | Helper function determining whether a pair of tokens can form an implicit multiplication . |
522 | private function normalize ( ) { $ gcd = Math :: gcd ( $ this -> p , $ this -> q ) ; if ( $ gcd == 0 ) throw new DivisionByZeroException ( ) ; $ this -> p = $ this -> p / $ gcd ; $ this -> q = $ this -> q / $ gcd ; if ( $ this -> q < 0 ) { $ this -> p = - $ this -> p ; $ this -> q = - $ this -> q ; } } | Normalize i . e . make sure the denominator is positive and that the numerator and denominator have no common factors |
523 | public function signed ( ) { if ( $ this -> q == 1 ) { return sprintf ( "%+d" , $ this -> p ) ; } return sprintf ( "%+d/%d" , $ this -> p , $ this -> q ) ; } | convert rational number to string adding a + if the number is positive |
524 | public function is_nan ( ) { if ( $ this -> q == 0 ) return true ; return is_nan ( $ this -> p ) || is_nan ( $ this -> q ) ; } | test if the rational number is NAN |
525 | public static function fromFloat ( $ float , $ tolerance = 1e-7 ) { if ( is_string ( $ float ) && preg_match ( '~^\-?\d+([,|.]\d+)?$~' , $ float ) ) { $ float = floatval ( str_replace ( ',' , '.' , $ float ) ) ; } if ( $ float == 0.0 ) { return new Rational ( 0 , 1 ) ; } $ negative = ( $ float < 0 ) ; if ( $ negative ) { $ float = abs ( $ float ) ; } $ num1 = 1 ; $ num2 = 0 ; $ den1 = 0 ; $ den2 = 1 ; $ oneOver = 1 / $ float ; do { $ oneOver = 1 / $ oneOver ; $ floor = floor ( $ oneOver ) ; $ aux = $ num1 ; $ num1 = $ floor * $ num1 + $ num2 ; $ num2 = $ aux ; $ aux = $ den1 ; $ den1 = $ floor * $ den1 + $ den2 ; $ den2 = $ aux ; $ oneOver = $ oneOver - $ floor ; } while ( abs ( $ float - $ num1 / $ den1 ) > $ float * $ tolerance ) ; if ( $ negative ) { $ num1 *= - 1 ; } return new Rational ( intval ( $ num1 ) , intval ( $ den1 ) ) ; } | convert float to Rational |
526 | public function makeNode ( $ leftOperand , $ rightOperand ) { $ leftOperand = $ this -> sanitize ( $ leftOperand ) ; $ rightOperand = $ this -> sanitize ( $ rightOperand ) ; $ node = $ this -> numericTerms ( $ leftOperand , $ rightOperand ) ; if ( $ node ) return $ node ; return new ExpressionNode ( $ leftOperand , '+' , $ rightOperand ) ; } | Create a Node representing leftOperand + rightOperand |
527 | public function fileAction ( $ objectId , $ fileId ) { if ( empty ( $ objectId ) || empty ( $ fileId ) ) { return $ this -> accessDenied ( ) ; } $ contactClient = $ this -> checkContactClientAccess ( $ objectId , 'view' ) ; if ( $ contactClient instanceof Response ) { return $ contactClient ; } $ file = $ this -> checkContactClientFileAccess ( $ fileId , 'view' ) ; if ( $ file instanceof Response ) { return $ file ; } if ( ! $ file || ! $ file -> getLocation ( ) || ! file_exists ( $ file -> getLocation ( ) ) ) { return $ this -> accessDenied ( ) ; } $ response = new BinaryFileResponse ( $ file -> getLocation ( ) ) ; $ response -> setPrivate ( ) ; $ response -> setContentDisposition ( ResponseHeaderBag :: DISPOSITION_ATTACHMENT ) ; return $ response ; } | Downloads a file securely . |
528 | public function addEvent ( array $ data ) { if ( $ this -> countOnly ) { if ( $ this -> groupUnit && $ this -> chartQuery ) { $ countData = [ [ 'date' => $ data [ 'timestamp' ] , 'count' => 1 , ] , ] ; $ count = $ this -> chartQuery -> completeTimeData ( $ countData ) ; $ this -> addToCounter ( $ data [ 'event' ] , $ count ) ; } else { if ( ! isset ( $ this -> totalEvents [ $ data [ 'event' ] ] ) ) { $ this -> totalEvents [ $ data [ 'event' ] ] = 0 ; } ++ $ this -> totalEvents [ $ data [ 'event' ] ] ; } } else { if ( ! isset ( $ this -> events [ $ data [ 'event' ] ] ) ) { $ this -> events [ $ data [ 'event' ] ] = [ ] ; } if ( ! $ this -> isForTimeline ( ) ) { $ keepThese = [ 'event' => true , 'eventId' => true , 'eventLabel' => true , 'eventType' => true , 'timestamp' => true , 'message' => true , 'integratonEntityId' => true , 'contactId' => true , 'extra' => true , ] ; $ data = array_intersect_key ( $ data , $ keepThese ) ; if ( isset ( $ data [ 'extra' ] ) ) { $ data [ 'details' ] = $ data [ 'extra' ] ; $ data [ 'details' ] = $ this -> prepareDetailsForAPI ( $ data [ 'details' ] ) ; unset ( $ data [ 'extra' ] ) ; } if ( $ this -> siteDomain && isset ( $ data [ 'eventLabel' ] ) && is_array ( $ data [ 'eventLabel' ] ) && isset ( $ data [ 'eventLabel' ] [ 'href' ] ) ) { if ( false === strpos ( $ data [ 'eventLabel' ] [ 'href' ] , '://' ) ) { $ data [ 'eventLabel' ] [ 'href' ] = $ this -> siteDomain . $ data [ 'eventLabel' ] [ 'href' ] ; } } } if ( empty ( $ data [ 'eventId' ] ) ) { $ data [ 'eventId' ] = $ this -> generateEventId ( $ data ) ; } $ this -> events [ $ data [ 'event' ] ] [ ] = $ data ; } } | Add an event to the container . |
529 | public function addToCounter ( $ eventType , $ count ) { if ( ! isset ( $ this -> totalEvents [ $ eventType ] ) ) { $ this -> totalEvents [ $ eventType ] = 0 ; } if ( is_array ( $ count ) ) { if ( isset ( $ count [ 'total' ] ) ) { $ this -> totalEvents [ $ eventType ] += $ count [ 'total' ] ; } elseif ( $ this -> isEngagementCount ( ) && $ this -> groupUnit ) { foreach ( $ count as $ key => $ data ) { if ( ! isset ( $ this -> totalEventsByUnit [ $ key ] ) ) { $ this -> totalEventsByUnit [ $ key ] = 0 ; } $ this -> totalEventsByUnit [ $ key ] += ( int ) $ data ; $ this -> totalEvents [ $ eventType ] += ( int ) $ data ; } } else { $ this -> totalEvents [ $ eventType ] = array_sum ( $ count ) ; } } else { $ this -> totalEvents [ $ eventType ] += ( int ) $ count ; } } | Add to the event counters . |
530 | public function getEvents ( ) { if ( empty ( $ this -> events ) ) { return [ ] ; } $ events = call_user_func_array ( 'array_merge' , $ this -> events ) ; foreach ( $ events as & $ e ) { if ( ! $ e [ 'timestamp' ] instanceof \ DateTime ) { $ dt = new DateTimeHelper ( $ e [ 'timestamp' ] , 'Y-m-d H:i:s' , 'UTC' ) ; $ e [ 'timestamp' ] = $ dt -> getDateTime ( ) ; unset ( $ dt ) ; } } if ( ! empty ( $ this -> orderBy ) ) { usort ( $ events , function ( $ a , $ b ) { switch ( $ this -> orderBy [ 0 ] ) { case 'eventLabel' : $ aLabel = '' ; if ( isset ( $ a [ 'eventLabel' ] ) ) { $ aLabel = ( is_array ( $ a [ 'eventLabel' ] ) ) ? $ a [ 'eventLabel' ] [ 'label' ] : $ a [ 'eventLabel' ] ; } $ bLabel = '' ; if ( isset ( $ b [ 'eventLabel' ] ) ) { $ bLabel = ( is_array ( $ b [ 'eventLabel' ] ) ) ? $ b [ 'eventLabel' ] [ 'label' ] : $ b [ 'eventLabel' ] ; } return strnatcmp ( $ aLabel , $ bLabel ) ; case 'date_added' : if ( $ a [ 'timestamp' ] == $ b [ 'timestamp' ] ) { $ aPriority = isset ( $ a [ 'eventPriority' ] ) ? ( int ) $ a [ 'eventPriority' ] : 0 ; $ bPriority = isset ( $ b [ 'eventPriority' ] ) ? ( int ) $ b [ 'eventPriority' ] : 0 ; return $ aPriority - $ bPriority ; } return $ a [ 'timestamp' ] < $ b [ 'timestamp' ] ? - 1 : 1 ; case 'contact_id' : if ( $ a [ 'contactId' ] == $ b [ 'contactId' ] ) { return 0 ; } return $ a [ 'contactId' ] < $ b [ 'contactId' ] ? - 1 : 1 ; case 'type' : return strnatcmp ( $ a [ 'eventType' ] , $ b [ 'eventType' ] ) ; default : return strnatcmp ( $ a [ $ this -> orderBy [ 0 ] ] , $ b [ $ this -> orderBy [ 0 ] ] ) ; } } ) ; if ( 'DESC' == $ this -> orderBy [ 1 ] ) { $ events = array_reverse ( $ events ) ; } } return $ events ; } | Fetch the events . |
531 | public function getEventCounter ( ) { foreach ( $ this -> events as $ type => $ events ) { if ( ! isset ( $ this -> totalEvents [ $ type ] ) ) { $ this -> totalEvents [ $ type ] = count ( $ events ) ; } } $ counter = [ 'total' => array_sum ( $ this -> totalEvents ) , ] ; if ( $ this -> countOnly && $ this -> groupUnit ) { $ counter [ 'byUnit' ] = $ this -> totalEventsByUnit ; } return $ counter ; } | Get total number of events for pagination . |
532 | public function setCountOnly ( \ DateTime $ dateFrom , \ DateTime $ dateTo , $ groupUnit = '' , ChartQuery $ chartQuery = null ) { $ this -> countOnly = true ; $ this -> dateFrom = $ dateFrom ; $ this -> dateTo = $ dateTo ; $ this -> groupUnit = $ groupUnit ; $ this -> chartQuery = $ chartQuery ; } | Calculate engagement counts only . |
533 | public function addSerializerGroup ( $ group ) { if ( is_array ( $ group ) ) { $ this -> serializerGroups = array_merge ( $ this -> serializerGroups , $ group ) ; } else { $ this -> serializerGroups [ $ group ] = $ group ; } } | Add a serializer group for API formatting . |
534 | public function getTokens ( $ string ) { $ tokens = [ ] ; $ scanResults = $ this -> engine -> getTokenizer ( ) -> scan ( $ string ) ; foreach ( $ scanResults as $ scanResult ) { if ( isset ( $ scanResult [ 'type' ] ) && isset ( $ scanResult [ 'name' ] ) && \ Mustache_Tokenizer :: T_ESCAPED === $ scanResult [ 'type' ] ) { $ tokens [ $ scanResult [ 'name' ] ] = true ; } } return array_keys ( $ tokens ) ; } | Scan a string for tokens using the same engine . |
535 | public function getFormats ( ) { return [ 'date' => $ this -> getDateFormatHelper ( ) -> getFormatsDate ( ) , 'datetime' => $ this -> getDateFormatHelper ( ) -> getFormatsDateTime ( ) , 'time' => $ this -> getDateFormatHelper ( ) -> getFormatsTime ( ) , 'number' => $ this -> formatNumber , 'boolean' => $ this -> formatBoolean , 'string' => $ this -> formatString , 'region' => $ this -> formatString , 'tel' => $ this -> formatTel , 'text' => $ this -> formatText , 'email' => $ this -> formatEmail , ] ; } | Outputs an array of formats by field type for the front - end tokenization . |
536 | private function findPivotDataTokens ( $ string ) { if ( ! $ this -> needsDeviceData && 1 === preg_match ( '/{{\s?device\..*\s?}}/' , $ string ) ) { $ this -> needsDeviceData = true ; } if ( ! $ this -> needsUtmData && 1 === preg_match ( '/{{\s?utm\..*\s?}}/' , $ string ) ) { $ this -> needsUtmData = true ; } if ( ! $ this -> needsDncData && 1 === preg_match ( '/{{\s?doNotContact\..*\s?}}/' , $ string ) ) { $ this -> needsDncData = true ; } } | Check for the need for device data to keep queries low later . |
537 | public function addContextEvent ( $ event = [ ] ) { $ contactId = isset ( $ this -> context [ 'id' ] ) ? $ this -> context [ 'id' ] : 0 ; $ this -> context [ 'event' ] [ 'id' ] = ! empty ( $ event [ 'id' ] ) ? ( int ) $ event [ 'id' ] : null ; $ this -> context [ 'event' ] [ 'name' ] = ! empty ( $ event [ 'name' ] ) ? $ event [ 'name' ] : null ; $ this -> context [ 'event' ] [ 'token' ] = null ; if ( $ contactId || $ this -> context [ 'event' ] [ 'id' ] || $ this -> context [ 'campaign' ] [ 'id' ] ) { $ this -> context [ 'event' ] [ 'token' ] = $ this -> eventTokenEncode ( [ $ this -> context [ 'campaign' ] [ 'id' ] , $ this -> context [ 'event' ] [ 'id' ] , $ contactId , ] ) ; } } | Take an event array and use it to enhance the context for later dispositional callback . Campaign context should be added before this as it is used for the token . |
538 | private function eventTokenEncode ( $ values ) { list ( $ campaignId , $ eventId , $ contactId ) = $ values ; $ campaignIdString = $ this -> baseEncode ( ( int ) $ campaignId ) ; $ eventIdString = $ this -> baseEncode ( ( int ) $ eventId ) ; $ contactIdString = $ this -> baseEncode ( ( int ) $ contactId ) ; return $ campaignIdString . '0' . $ eventIdString . '0' . $ contactIdString ; } | Encode Campaign ID Event ID and Contact ID into a short base62 string . Zeros are used as delimiters reducing the subsequent integers to base61 . |
539 | public function render ( $ template = '' ) { $ result = $ template ; if ( is_array ( $ template ) || is_object ( $ template ) ) { foreach ( $ result as & $ val ) { $ val = $ this -> render ( $ val ) ; } } elseif ( is_string ( $ template ) && strlen ( $ template ) >= self :: TEMPLATE_MIN_LENGTH && false !== strpos ( $ template , self :: TOKEN_KEY_START ) && false !== strpos ( $ template , self :: TOKEN_KEY_END ) ) { if ( isset ( $ this -> renderCache [ $ template ] ) ) { $ result = $ this -> renderCache [ $ template ] ; } else { $ this -> lastTemplate = $ template ; set_error_handler ( [ $ this , 'handleMustacheErrors' ] , E_WARNING | E_NOTICE ) ; $ result = $ this -> engine -> render ( $ template , $ this -> context ) ; restore_error_handler ( ) ; if ( null !== $ result && '' !== $ result ) { $ this -> renderCache [ $ template ] = $ result ; } } } return $ result ; } | Replace Tokens in a simple string using an array for context . |
540 | public function getContextLabeled ( $ sort = true ) { $ result = [ ] ; $ labels = $ this -> describe ( $ this -> context ) ; $ this -> flattenArray ( $ labels , $ result ) ; $ result [ 'file_count' ] = 'File: Number of contacts in this file' ; $ result [ 'file_test' ] = 'File: Inserts ".test" if testing' ; $ result [ 'file_date' ] = 'File: Date/time of file creation' ; $ result [ 'file_type' ] = 'File: Type of file, such as csv/xsl' ; $ result [ 'file_compression' ] = 'File: Compression of the file, such as zip/gz' ; $ result [ 'file_extension' ] = 'File: Automatic extension such as xsl/zip/csv' ; $ result [ 'api_date' ] = 'API: Date/time of the API request' ; if ( $ sort ) { asort ( $ result , SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL ) ; } return $ result ; } | Get the context array labels instead of values for use in token suggestions . |
541 | private function describe ( $ array = [ ] , $ keys = '' , $ sort = true , $ payload = false ) { foreach ( $ array as $ key => & $ value ) { if ( is_array ( $ value ) ) { if ( 0 === count ( $ value ) ) { unset ( $ array [ $ key ] ) ; continue ; } else { $ value = $ this -> describe ( $ value , $ keys . ' ' . $ key , $ sort , ( $ payload || 'payload' === $ key ) ) ; } } else { if ( $ payload ) { $ value = $ key ; } elseif ( is_bool ( $ value ) || null === $ value || 0 === $ value ) { $ totalKey = str_replace ( '_' , ' ' , $ keys . ' ' . trim ( $ key ) ) ; preg_match_all ( '/(?:|[A-Z])[a-z]*/' , $ totalKey , $ words ) ; foreach ( $ words [ 0 ] as & $ word ) { if ( strlen ( $ word ) > 1 ) { $ word = strtoupper ( substr ( $ word , 0 , 1 ) ) . substr ( $ word , 1 ) ; } } $ value = trim ( preg_replace ( '/\s+/' , ' ' , implode ( ' ' , $ words [ 0 ] ) ) ) ; $ value = str_replace ( 'Utm ' , 'UTM ' , $ value ) ; } } } if ( $ sort ) { ksort ( $ array , SORT_NATURAL ) ; } return $ array ; } | Given a token array set the values to the labels for the context if possible . |
542 | private function handleMustacheErrors ( $ errno , $ errstr , $ errfile , $ errline ) { if ( ! empty ( $ this -> lastTemplate ) ) { if ( function_exists ( 'newrelic_add_custom_parameter' ) ) { call_user_func ( 'newrelic_add_custom_parameter' , 'contactclientToken' , $ this -> lastTemplate ) ; } } if ( ! empty ( $ this -> context ) ) { if ( function_exists ( 'newrelic_add_custom_parameter' ) ) { call_user_func ( 'newrelic_add_custom_parameter' , 'contactclientContext' , json_encode ( $ this -> context ) ) ; } } $ this -> logger -> error ( 'Contact Client ' . $ this -> contactClient -> getId ( ) . ': Warning issued with Template: ' . $ this -> lastTemplate . ' Context: ' . json_encode ( $ this -> context ) ) ; return true ; } | Capture Mustache warnings to be logged for debugging . |
543 | private function eventTokenDecode ( $ string ) { list ( $ campaignIdString , $ eventIdString , $ contactIdString ) = explode ( '0' , $ string ) ; return [ $ this -> baseDecode ( $ campaignIdString ) , $ this -> baseDecode ( $ eventIdString ) , $ this -> baseDecode ( $ contactIdString ) , ] ; } | Take a string from eventTokenEncode and reverse it to an array . |
544 | private function parse ( $ date , $ timezone = null ) { if ( ! ( $ date instanceof \ DateTime ) ) { if ( false === strtotime ( $ date ) ) { throw new \ Exception ( 'Invalid date not parsed.' ) ; } if ( ! $ timezone ) { $ timezone = $ this -> timezoneSource ; } $ date = new \ DateTime ( $ date , new \ DateTimeZone ( $ timezone ) ) ; } return $ date ; } | Parse a string into a DateTime . |
545 | private function setSettings ( $ settings ) { if ( $ settings ) { foreach ( $ this -> settings as $ key => & $ value ) { if ( ! empty ( $ settings -> { $ key } ) && $ settings -> { $ key } ) { $ value = $ settings -> { $ key } ; } } } } | Retrieve API settings from the payload to override our defaults . |
546 | public function evaluateSchedule ( ) { $ this -> scheduleModel -> reset ( ) -> setContactClient ( $ this -> contactClient ) -> setTimezone ( ) -> evaluateDay ( ) -> evaluateTime ( ) -> evaluateExclusions ( ) ; return new \ DateTime ( ) ; } | Returns the expected send time for limit evaluation . Throws an exception if an open slot is not available . |
547 | public function run ( ) { $ this -> validateOperations ( ) ; $ this -> prepareTransport ( ) ; $ this -> prepareTokenHelper ( ) ; $ this -> preparePayloadAuth ( ) ; try { $ this -> runApiOperations ( ) ; } catch ( \ Exception $ e ) { if ( $ this -> start && $ e instanceof ContactClientException && Stat :: TYPE_AUTH === $ e -> getStatType ( ) ) { $ this -> prepareTokenHelper ( ) ; $ this -> start = 0 ; $ this -> runApiOperations ( ) ; } else { throw $ e ; } } return $ this ; } | Step through all operations defined . |
548 | private function prepareTokenHelper ( ) { $ this -> tokenHelper -> newSession ( $ this -> contactClient , $ this -> contact , $ this -> payload , $ this -> campaign , $ this -> event ) ; $ this -> tokenHelper -> addContext ( [ 'api_date' => $ this -> tokenHelper -> getDateFormatHelper ( ) -> format ( new \ DateTime ( ) ) , ] ) ; } | Apply our context to create a new tokenhelper session . |
549 | private function preparePayloadAuth ( ) { $ this -> apiPayloadAuth -> reset ( ) -> setTest ( $ this -> test ) -> setContactClient ( $ this -> contactClient ) -> setOperations ( $ this -> payload -> operations ) ; $ this -> start = $ this -> apiPayloadAuth -> getStartOperation ( ) ; if ( $ this -> start ) { $ context = $ this -> apiPayloadAuth -> getPreviousPayloadAuthTokens ( ) ; $ this -> tokenHelper -> addContext ( $ context ) ; } } | Prepare the APIPayloadAuth model and get the starting operation ID it reccomends . |
550 | private function savePayloadAuthTokens ( $ operationId ) { if ( $ this -> valid && $ this -> apiPayloadAuth -> hasAuthRequest ( $ operationId ) ) { $ fieldSets = $ this -> getAggregateActualResponses ( null , $ operationId ) ; $ this -> apiPayloadAuth -> savePayloadAuthTokens ( $ operationId , $ fieldSets ) ; } } | If we just made a successful run with an auth operation without skipping said operation preserve the applicable auth tokens for future use . |
551 | public function getAggregateActualResponses ( $ key = null , $ operationId = null , $ types = [ 'headers' , 'body' ] ) { if ( $ this -> valid && isset ( $ this -> aggregateActualResponses ) ) { if ( null !== $ key ) { foreach ( $ types as $ type ) { if ( null !== $ operationId ) { if ( isset ( $ this -> aggregateActualResponses [ $ operationId ] [ $ type ] [ $ key ] ) ) { return $ this -> aggregateActualResponses [ $ operationId ] [ $ type ] [ $ key ] ; } } else { foreach ( array_reverse ( $ this -> aggregateActualResponses ) as $ values ) { if ( isset ( $ values [ $ type ] [ $ key ] ) ) { return $ values [ $ type ] [ $ key ] ; } } } } } else { $ result = [ ] ; foreach ( $ types as $ type ) { if ( isset ( $ this -> aggregateActualResponses [ $ operationId ] [ $ type ] ) ) { $ result [ $ type ] = $ this -> aggregateActualResponses [ $ operationId ] [ $ type ] ; } } return $ result ; } } return null ; } | Get the most recent non - empty response value by field name ignoring validity . Provide key or operationId or both . |
552 | public function applyResponseMap ( $ updateTokens = false ) { $ responseMap = $ this -> getResponseMap ( ) ; if ( count ( $ responseMap ) ) { foreach ( $ responseMap as $ alias => $ value ) { $ oldValue = $ this -> contact -> getFieldValue ( $ alias ) ; if ( $ oldValue !== $ value ) { $ this -> contact -> addUpdatedField ( $ alias , $ value , $ oldValue ) ; if ( $ updateTokens ) { $ this -> tokenHelper -> addContext ( [ $ alias => $ value ] ) ; } $ this -> setLogs ( 'Updating Contact: ' . $ alias . ' = ' . $ value , 'fieldsUpdated' ) ; $ this -> updatedFields = true ; } } } return $ this -> updatedFields ; } | Apply the responsemap to update a contact entity . |
553 | private function updatePayload ( ) { if ( $ this -> contactClient ) { $ this -> sortPayloadFields ( ) ; $ jsonHelper = new JSONHelper ( ) ; $ payloadJSON = $ jsonHelper -> encode ( $ this -> payload , 'Payload' ) ; $ this -> contactClient -> setAPIPayload ( $ payloadJSON ) ; } } | Update the payload with the parent ContactClient because we ve updated the response expectation . |
554 | private function sortPayloadFields ( ) { if ( isset ( $ this -> payload -> operations ) ) { foreach ( $ this -> payload -> operations as $ id => $ operation ) { foreach ( [ 'request' , 'response' ] as $ opType ) { if ( isset ( $ operation -> { $ opType } ) ) { foreach ( [ 'headers' , 'body' ] as $ fieldType ) { if ( is_array ( $ operation -> { $ opType } -> { $ fieldType } ) ) { usort ( $ operation -> { $ opType } -> { $ fieldType } , function ( $ a , $ b ) { return strnatcmp ( isset ( $ a -> key ) ? $ a -> key : null , isset ( $ b -> key ) ? $ b -> key : null ) ; } ) ; } } } } } } } | Sort the fields by keys so that the user doesn t have to . Only applies when AutoUpdate is enabled . |
555 | private function decodeJSON ( $ json ) { $ query = json_decode ( $ json ) ; if ( json_last_error ( ) ) { throw new \ Exception ( 'JSON parsing threw an error: ' . json_last_error_msg ( ) ) ; } if ( ! is_object ( $ query ) ) { throw new \ Exception ( 'The query is not valid JSON' ) ; } return $ query ; } | Decode the given JSON . |
556 | protected function checkRuleCorrect ( $ rule ) { if ( ! isset ( $ rule -> value ) ) { $ rule -> value = null ; } if ( ! isset ( $ rule -> id , $ rule -> field , $ rule -> type , $ rule -> input , $ rule -> operator ) ) { return false ; } if ( ! isset ( $ this -> operators [ $ rule -> operator ] ) ) { return false ; } return true ; } | Check if a given rule is correct . Just before making a query for a rule we want to make sure that the field operator and value are set . |
557 | protected function enforceArrayOrString ( $ requireArray , $ value , $ field ) { $ this -> checkFieldIsAnArray ( $ requireArray , $ value , $ field ) ; if ( ! $ requireArray && is_array ( $ value ) ) { return $ this -> convertArrayToFlatValue ( $ field , $ value ) ; } return $ value ; } | Enforce whether the value for a given field is the correct type . |
558 | protected function isNested ( $ rule ) { if ( isset ( $ rule -> rules ) && is_array ( $ rule -> rules ) && count ( $ rule -> rules ) > 0 ) { return true ; } return false ; } | Determine if we have nested rules to evaluate . |
559 | public function oldestDateAdded ( $ duration , string $ timezone = null , \ DateTime $ dateSend = null ) { if ( ! $ timezone ) { $ timezone = date_default_timezone_get ( ) ; } if ( is_string ( $ timezone ) ) { $ timezone = new \ DateTimeZone ( $ timezone ) ; } if ( $ dateSend ) { $ oldest = clone $ dateSend ; $ oldest -> setTimezone ( $ timezone ) ; } else { $ oldest = new \ DateTime ( 'now' , $ timezone ) ; } if ( 0 !== strpos ( $ duration , 'P' ) ) { switch ( strtoupper ( substr ( $ duration , - 1 ) ) ) { case 'Y' : $ oldest -> modify ( 'next year jan 1 midnight' ) ; break ; case 'M' : $ oldest -> modify ( 'first day of next month midnight' ) ; break ; case 'W' : $ oldest -> modify ( 'sunday next week midnight' ) ; break ; case 'D' : $ oldest -> modify ( 'tomorrow midnight' ) ; break ; } $ duration = 'P' . $ duration ; } try { $ interval = new \ DateInterval ( $ duration ) ; } catch ( \ Exception $ e ) { $ interval = new \ DateInterval ( 'P1M' ) ; } $ oldest -> sub ( $ interval ) ; return $ oldest ; } | Support non - rolling durations when P is not prefixing . |
560 | private function bitwiseIn ( $ max , $ matching ) { $ result = [ ] ; for ( $ i = 1 ; $ i <= $ max ; ++ $ i ) { if ( $ i & $ matching ) { $ result [ ] = $ i ; } } return $ result ; } | Given bitwise operators and the value we want to match against generate a minimal array for an IN query . |
561 | private function addExpiration ( & $ filters = [ ] , \ DateTime $ dateSend = null ) { if ( $ filters ) { $ expiration = $ dateSend ? $ dateSend : new \ DateTime ( ) ; $ expiration = $ expiration -> getTimestamp ( ) ; foreach ( $ filters as & $ filter ) { $ filter [ 'exclusive_expire_date' ] = $ expiration ; } } } | Add Exclusion Expiration date . |
562 | public function reduceExclusivityIndex ( ) { $ q = $ this -> getEntityManager ( ) -> getConnection ( ) -> createQueryBuilder ( ) ; $ q -> update ( MAUTIC_TABLE_PREFIX . $ this -> getTableName ( ) ) ; $ q -> where ( $ q -> expr ( ) -> isNotNull ( 'exclusive_expire_date' ) , $ q -> expr ( ) -> lte ( 'exclusive_expire_date' , 'NOW()' ) ) ; $ q -> set ( 'exclusive_expire_date' , 'NULL' ) ; $ q -> set ( 'exclusive_pattern' , 'NULL' ) ; $ q -> set ( 'exclusive_scope' , 'NULL' ) ; $ q -> execute ( ) ; } | Update exclusivity rows to reduce the index size and thus reduce processing required to check exclusivity . |
563 | public function getEntities ( array $ args = [ ] ) { $ alias = $ this -> getTableAlias ( ) ; $ q = $ this -> _em -> createQueryBuilder ( ) -> select ( $ alias ) -> from ( 'MauticContactClientBundle:ContactClient' , $ alias , $ alias . '.id' ) ; if ( empty ( $ args [ 'iterator_mode' ] ) ) { $ q -> leftJoin ( $ alias . '.category' , 'c' ) ; } $ args [ 'qb' ] = $ q ; return parent :: getEntities ( $ args ) ; } | Get a list of entities . |
564 | public function getStats ( $ contactClientId , $ type , $ fromDate = null , $ toDate = null ) { $ q = $ this -> createQueryBuilder ( 's' ) ; $ expr = $ q -> expr ( ) -> andX ( $ q -> expr ( ) -> eq ( 'IDENTITY(s.contactclient)' , ( int ) $ contactClientId ) , $ q -> expr ( ) -> eq ( 's.type' , ':type' ) ) ; if ( $ fromDate ) { $ expr -> add ( $ q -> expr ( ) -> gte ( 's.dateAdded' , ':fromDate' ) ) ; $ q -> setParameter ( 'fromDate' , $ fromDate ) ; } if ( $ toDate ) { $ expr -> add ( $ q -> expr ( ) -> lte ( 's.dateAdded' , ':toDate' ) ) ; $ q -> setParameter ( 'toDate' , $ toDate ) ; } $ q -> where ( $ expr ) -> setParameter ( 'type' , $ type ) ; return $ q -> getQuery ( ) -> getArrayResult ( ) ; } | Fetch the base stat data from the database . |
565 | protected function checkContactClientAccess ( $ contactClientId , $ action , $ isPlugin = false , $ integration = '' ) { if ( ! $ contactClientId instanceof ContactClient ) { $ contactClientModel = $ this -> getModel ( 'contactClient' ) ; $ contactClient = $ contactClientModel -> getEntity ( ( int ) $ contactClientId ) ; } else { $ contactClient = $ contactClientId ; $ contactClientId = $ contactClient -> getId ( ) ; } if ( null === $ contactClient || ! $ contactClient -> getId ( ) ) { if ( method_exists ( $ this , 'postActionRedirect' ) ) { $ page = $ this -> get ( 'session' ) -> get ( $ isPlugin ? 'mautic.' . $ integration . '.page' : 'mautic.contactClient.page' , 1 ) ; $ returnUrl = $ this -> generateUrl ( $ isPlugin ? 'mautic_plugin_timeline_index' : 'mautic_contact_index' , [ 'page' => $ page ] ) ; return $ this -> postActionRedirect ( [ 'returnUrl' => $ returnUrl , 'viewParameters' => [ 'page' => $ page ] , 'contentTemplate' => $ isPlugin ? 'MauticContactClientBundle:ContactClient:pluginIndex' : 'MauticContactClientBundle:ContactClient:index' , 'passthroughVars' => [ 'activeLink' => $ isPlugin ? '#mautic_plugin_timeline_index' : '#mautic_contact_index' , 'mauticContent' => 'contactClientTimeline' , ] , 'flashes' => [ [ 'type' => 'error' , 'msg' => 'mautic.contactClient.contactClient.error.notfound' , 'msgVars' => [ '%id%' => $ contactClientId ] , ] , ] , ] ) ; } else { return $ this -> notFound ( 'mautic.contact.error.notfound' ) ; } } elseif ( ! $ this -> get ( 'mautic.security' ) -> hasEntityAccess ( 'contactclient:items:' . $ action . 'own' , 'contactclient:items:' . $ action . 'other' , $ contactClient -> getPermissionUser ( ) ) ) { return $ this -> accessDenied ( ) ; } else { return $ contactClient ; } } | Determines if the user has access to the contactClient . |
566 | protected function checkContactClientFileAccess ( $ fileId , $ action , $ isPlugin = false , $ integration = '' ) { if ( ! $ fileId instanceof File ) { $ fileRepository = $ this -> getDoctrine ( ) -> getEntityManager ( ) -> getRepository ( 'MauticContactClientBundle:File' ) ; $ file = $ fileRepository -> getEntity ( ( int ) $ fileId ) ; } else { $ file = $ fileId ; $ fileId = $ file -> getId ( ) ; } if ( null === $ file || ! $ file -> getId ( ) ) { if ( method_exists ( $ this , 'postActionRedirect' ) ) { $ page = $ this -> get ( 'session' ) -> get ( $ isPlugin ? 'mautic.' . $ integration . '.page' : 'mautic.contactClient.page' , 1 ) ; $ returnUrl = $ this -> generateUrl ( $ isPlugin ? 'mautic_plugin_timeline_index' : 'mautic_contact_index' , [ 'page' => $ page ] ) ; return $ this -> postActionRedirect ( [ 'returnUrl' => $ returnUrl , 'viewParameters' => [ 'page' => $ page ] , 'contentTemplate' => $ isPlugin ? 'MauticContactClientBundle:ContactClient:pluginIndex' : 'MauticContactClientBundle:ContactClient:index' , 'passthroughVars' => [ 'activeLink' => $ isPlugin ? '#mautic_plugin_timeline_index' : '#mautic_contact_index' , 'mauticContent' => 'contactClientTimeline' , ] , 'flashes' => [ [ 'type' => 'error' , 'msg' => 'mautic.contactClient.contactClient.error.notfound' , 'msgVars' => [ '%id%' => $ fileId ] , ] , ] , ] ) ; } else { return $ this -> notFound ( 'mautic.contact.error.notfound' ) ; } } elseif ( ! $ this -> get ( 'mautic.security' ) -> hasEntityAccess ( 'contactclient:files:' . $ action . 'own' , 'contactclient:files:' . $ action . 'other' , 0 ) ) { return $ this -> accessDenied ( ) ; } else { return $ file ; } } | Determines if the user has access to a File . |
567 | protected function checkAllAccess ( $ action , $ limit ) { $ model = $ this -> getModel ( 'contactClient' ) ; $ repo = $ model -> getRepository ( ) ; $ contactClients = $ repo -> getEntities ( [ 'filter' => [ ] , 'oderBy' => 'r.last_active' , 'orderByDir' => 'DESC' , 'limit' => $ limit , 'hydration_mode' => 'HYDRATE_ARRAY' , ] ) ; if ( null === $ contactClients ) { return $ this -> accessDenied ( ) ; } foreach ( $ contactClients as $ contactClient ) { if ( ! $ this -> get ( 'mautic.security' ) -> hasEntityAccess ( 'contactclient:items:' . $ action . 'own' , 'contactclient:items:' . $ action . 'other' , $ contactClient [ 'createdBy' ] ) ) { unset ( $ contactClient ) ; } } return $ contactClients ; } | Returns contactClients the user has access to . |
568 | protected function getUpdateSelectParams ( $ updateSelect , $ entity , $ nameMethod = 'getName' , $ groupMethod = 'getLanguage' ) { $ options = [ 'updateSelect' => $ updateSelect , 'id' => $ entity -> getId ( ) , 'name' => $ entity -> $ nameMethod ( ) , ] ; return $ options ; } | Return array of options update select response . |
569 | public function getStartOperation ( ) { $ id = 0 ; if ( $ this -> hasAuthRequest ( ) ) { foreach ( $ this -> operations as $ id => $ operation ) { if ( $ id == count ( $ this -> operations ) - 1 ) { break ; } if ( ! $ this -> hasAuthRequest ( $ id ) ) { break ; } if ( $ this -> operationUpdatesContact ( $ operation ) ) { break ; } $ this -> determineOperationRequirements ( ) ; if ( isset ( $ this -> requiredPayloadTokens [ $ id ] ) ) { $ this -> loadPreviousPayloadAuthTokens ( ) ; foreach ( $ this -> requiredPayloadTokens [ $ id ] as $ token ) { if ( ! isset ( $ this -> previousPayloadAuthTokens [ $ token ] ) ) { break ; } } } else { break ; } } } return $ id ; } | Step forward through operations to find the one we MUST start with . |
570 | private function determineOperationRequirements ( ) { if ( null === $ this -> requiredPayloadTokens ) { $ this -> requiredPayloadTokens = [ ] ; $ valueSources = [ 'value' , 'default_value' ] ; if ( $ this -> test ) { $ valueSources = [ 'test_value' , 'value' , 'default_value' ] ; } foreach ( $ this -> operations as $ id => $ operation ) { if ( isset ( $ operation -> request ) ) { foreach ( [ 'headers' , 'body' ] as $ fieldType ) { if ( is_array ( $ operation -> request -> { $ fieldType } ) ) { foreach ( $ operation -> request -> { $ fieldType } as $ field ) { foreach ( $ valueSources as $ valueSource ) { if ( ! empty ( $ field -> { $ valueSource } ) ) { $ tokens = $ this -> tokenHelper -> getTokens ( $ field -> { $ valueSource } ) ; if ( $ tokens ) { foreach ( $ tokens as $ token ) { $ parts = explode ( '.' , $ token ) ; if ( isset ( $ parts [ 0 ] ) && 'payload' === $ parts [ 0 ] && isset ( $ parts [ 1 ] ) && 'operations' === $ parts [ 1 ] && isset ( $ parts [ 2 ] ) && is_numeric ( $ parts [ 2 ] ) && isset ( $ parts [ 3 ] ) && 'response' === $ parts [ 3 ] && in_array ( $ parts [ 4 ] , [ 'headers' , 'body' ] ) && isset ( $ parts [ 5 ] ) ) { if ( ! isset ( $ this -> requiredPayloadTokens [ $ parts [ 2 ] ] ) ) { $ this -> requiredPayloadTokens [ $ parts [ 2 ] ] = [ ] ; } $ this -> requiredPayloadTokens [ $ parts [ 2 ] ] [ ] = $ token ; } } } } } } } } } } } } | Discern the tokens that are required by operation ID . |
571 | private function loadPreviousPayloadAuthTokens ( ) { if ( ! $ this -> previousPayloadAuthTokens ) { $ this -> previousPayloadAuthTokens = $ this -> getAuthRepository ( ) -> getPreviousPayloadAuthTokensByContactClient ( $ this -> contactClient -> getId ( ) , null , $ this -> test ) ; } } | Load up the previously stored payload tokens . |
572 | public function addEvent ( ContactClient $ contactClient = null , $ type = null , Contact $ contact = null , $ logs = null , $ message = null , $ integrationEntityId = null ) { $ event = new EventEntity ( ) ; $ event -> setDateAdded ( new \ DateTime ( ) ) ; if ( $ type ) { $ event -> setType ( $ type ) ; } if ( $ contactClient ) { $ event -> setContactClientId ( $ contactClient -> getId ( ) ) ; } if ( $ contact ) { $ event -> setContact ( $ contact ) ; } if ( $ logs ) { $ event -> setLogs ( $ logs ) ; } if ( $ message ) { $ event -> setMessage ( $ message ) ; } if ( $ integrationEntityId ) { $ event -> setIntegrationEntityId ( $ integrationEntityId ) ; } $ this -> getEventRepository ( ) -> saveEntity ( $ event ) ; } | Add transactional log in contactclient_events . |
573 | public function limitQueryToCreator ( QueryBuilder $ q ) { $ q -> join ( 't' , MAUTIC_TABLE_PREFIX . 'contactclient' , 'm' , 'e.id = t.contactclient_id' ) -> andWhere ( 'm.created_by = :userId' ) -> setParameter ( 'userId' , $ this -> userHelper -> getUser ( ) -> getId ( ) ) ; } | Joins the email table and limits created_by to currently logged in user . |
574 | public function run ( ) { if ( empty ( $ this -> request ) ) { $ this -> setLogs ( 'Skipping empty operation: ' . $ this -> name , 'notice' ) ; return true ; } $ this -> setLogs ( $ this -> name , 'name' ) ; $ this -> setLogs ( ( $ this -> test ? 'TEST' : 'PROD' ) , 'mode' ) ; $ apiRequest = new ApiRequest ( $ this -> request , $ this -> transport , $ this -> tokenHelper , $ this -> test ) ; $ apiRequest -> send ( ) ; $ this -> setLogs ( $ apiRequest -> getLogs ( ) , 'request' ) ; $ apiResponse = new ApiResponse ( $ this -> responseExpected , $ this -> successDefinition , $ this -> transport , $ this -> test ) ; $ this -> responseActual = $ apiResponse -> parse ( ) -> getResponse ( ) ; $ this -> setLogs ( $ apiResponse -> getLogs ( ) , 'response' ) ; $ valid = false ; try { $ valid = $ apiResponse -> validate ( ) ; } catch ( \ Exception $ e ) { } $ this -> setValid ( $ valid ) ; $ this -> setLogs ( $ valid , 'valid' ) ; if ( $ this -> updatePayload && $ this -> test ) { $ this -> updatePayloadResponse ( ) ; } if ( ! empty ( $ e ) ) { throw $ e ; } return $ this ; } | Run this single API Operation . |
575 | public function getResponseMap ( ) { $ mappedFields = [ ] ; foreach ( [ 'headers' , 'body' ] as $ type ) { if ( isset ( $ this -> responseExpected -> { $ type } ) && isset ( $ this -> responseActual [ $ type ] ) ) { foreach ( $ this -> responseExpected -> { $ type } as $ value ) { if ( ! empty ( $ value -> destination ) && ! empty ( $ value -> key ) && ! empty ( $ this -> responseActual [ $ type ] [ $ value -> key ] ) ) { $ mappedFields [ $ value -> destination ] = $ this -> responseActual [ $ type ] [ $ value -> key ] ; } } } } return $ mappedFields ; } | Get filled responses that have Contact destinations defined . |
576 | public function getExternalId ( ) { $ externalIds = array_flip ( $ this -> externalIds ) ; $ id = null ; $ idIndex = null ; foreach ( [ 'headers' , 'body' ] as $ type ) { if ( isset ( $ this -> responseActual [ $ type ] ) && isset ( $ this -> responseActual [ $ type ] ) ) { foreach ( $ this -> responseActual [ $ type ] as $ key => $ value ) { $ key = preg_replace ( '/[^a-z0-9]/' , '' , strtolower ( $ key ) ) ; if ( isset ( $ externalIds [ $ key ] ) && ( null === $ idIndex || $ externalIds [ $ key ] < $ idIndex ) ) { $ idIndex = $ externalIds [ $ key ] ; $ id = $ value ; if ( 0 == $ idIndex ) { break ; } } } } } return $ id ; } | Given the response fields attempt to assume an external ID for future correlation . Find the best possible fit . |
577 | public function findOpening ( $ startDay = 0 , $ endDay = 7 , $ fileRate = 1 , $ all = false , $ startTime = null ) { $ openings = [ ] ; for ( $ day = $ startDay ; $ day <= $ endDay ; ++ $ day ) { if ( 0 === $ day ) { if ( $ startTime && $ startTime instanceof \ DateTime ) { $ date = clone $ startTime ; } else { $ date = new \ DateTime ( ) ; } } else { $ date = new \ DateTime ( 'noon +' . $ day . ' day' ) ; } try { $ start = clone $ date ; $ end = clone $ date ; $ hours = $ this -> evaluateDay ( true , $ date ) ; $ this -> evaluateExclusions ( $ date ) ; $ timeTill = ! empty ( $ hours -> timeTill ) ? $ hours -> timeTill : '23:59' ; $ end -> setTimezone ( $ this -> timezone ) ; $ end -> modify ( $ timeTill . ':59' ) ; if ( 0 == $ day && $ this -> now > $ end ) { continue ; } $ timeFrom = ! empty ( $ hours -> timeFrom ) ? $ hours -> timeFrom : '00:00' ; $ start -> setTimezone ( $ this -> timezone ) ; $ start -> modify ( $ timeFrom ) ; if ( 'file' === $ this -> contactClient -> getType ( ) ) { $ fileCount = $ this -> evaluateFileRate ( $ fileRate , $ date ) ; if ( $ fileCount > 0 && $ fileRate > 1 ) { $ daySeconds = $ end -> format ( 'U' ) - $ start -> format ( 'U' ) ; if ( '00:00' === $ timeFrom && '23:59' === $ timeTill ) { $ segmentSeconds = intval ( $ daySeconds / $ fileRate ) ; } else { $ segmentSeconds = intval ( $ daySeconds / ( $ fileRate - 1 ) ) ; } $ start -> modify ( '+' . ( $ segmentSeconds * $ fileCount ) . ' seconds' ) ; } } if ( 0 === $ day && $ start < $ this -> now ) { $ start = $ this -> now ; } $ openings [ ] = [ $ start , $ end ] ; if ( ! $ all ) { break ; } } catch ( \ Exception $ e ) { if ( $ e instanceof ContactClientException ) { } else { throw $ e ; } } } return $ openings ; } | Given the hours of operation timezone and excluded dates of the client ... Find the next appropriate time to send them contacts . |
578 | public function setTimezone ( \ DateTimeZone $ timezone = null ) { if ( ! $ timezone ) { $ timezone = $ this -> contactClient -> getScheduleTimezone ( ) ; if ( ! $ timezone ) { $ timezone = $ this -> coreParametersHelper -> getParameter ( 'default_timezone' ) ; $ timezone = ! empty ( $ timezone ) ? $ timezone : date_default_timezone_get ( ) ; } $ timezone = new \ DateTimeZone ( $ timezone ) ; } $ this -> timezone = $ timezone ; $ this -> now -> setTimezone ( $ timezone ) ; return $ this ; } | Set Client timezone defaulting to Mautic or System as is relevant . |
579 | public function create ( ) { $ entities = [ ] ; $ exclusive = $ this -> getExclusiveRules ( ) ; if ( count ( $ exclusive ) ) { foreach ( $ exclusive as $ rule ) { if ( ! isset ( $ entity ) ) { $ entity = $ this -> createEntity ( ) ; } else { $ entity = clone $ entity ; } $ expireDate = $ this -> getRepository ( ) -> oldestDateAdded ( $ rule [ 'duration' ] , $ this -> getTimezone ( ) , $ this -> dateSend ) ; $ entity -> setExclusiveExpireDate ( $ expireDate ) ; $ entity -> setExclusivePattern ( $ rule [ 'matching' ] ) ; $ entity -> setExclusiveScope ( $ rule [ 'scope' ] ) ; $ entities [ ] = $ entity ; } } else { $ entities [ ] = $ this -> createEntity ( ) ; } if ( count ( $ entities ) ) { $ this -> getRepository ( ) -> saveEntities ( $ entities ) ; $ this -> em -> clear ( 'MauticPlugin\MauticContactClientBundle\Entity\Cache' ) ; } } | Create all necessary cache entities for the given Contact and Contact Client . |
580 | public function getExclusiveRules ( ) { $ jsonHelper = new JSONHelper ( ) ; $ exclusive = $ jsonHelper -> decodeObject ( $ this -> contactClient -> getExclusive ( ) , 'Exclusive' ) ; $ this -> excludeIrrelevantRules ( $ exclusive ) ; return $ this -> mergeRules ( $ exclusive ) ; } | Given the Contact and Contact Client discern which exclusivity entries need to be cached . |
581 | public function evaluateExclusive ( ) { if ( ! $ this -> contactClient -> getExclusiveIgnore ( ) ) { $ exclusive = $ this -> getRepository ( ) -> findExclusive ( $ this -> contact , $ this -> contactClient , $ this -> dateSend ) ; if ( $ exclusive ) { throw new ContactClientException ( 'Skipping exclusive Contact.' , Codes :: HTTP_CONFLICT , null , Stat :: TYPE_EXCLUSIVE , false , null , $ exclusive ) ; } } } | Given a contact evaluate exclusivity rules of all cache entries against it . |
582 | public function getLimitRules ( ) { $ jsonHelper = new JSONHelper ( ) ; $ limits = $ jsonHelper -> decodeObject ( $ this -> contactClient -> getLimits ( ) , 'Limits' ) ; $ this -> excludeIrrelevantRules ( $ limits ) ; return $ this -> mergeRules ( $ limits , false ) ; } | Given the Contact and Contact Client get the rules used to evaluate limits . |
583 | public function setAttribution ( $ attribution ) { if ( $ this -> queue ) { $ this -> queue -> setAttribution ( $ attribution ) ; $ this -> getQueueRepository ( ) -> saveEntity ( $ this -> queue ) ; } } | Append the current queue entity with attribution . |
584 | public function reset ( $ exclusions = [ 'contactClientModel' , 'tokenHelper' , 'em' , 'formModel' , 'eventModel' , 'contactModel' , 'pathsHelper' , 'coreParametersHelper' , 'filesystemLocal' , 'mailHelper' , 'scheduleModel' , 'utmSourceHelper' , ] ) { foreach ( array_diff_key ( get_class_vars ( get_class ( $ this ) ) , array_flip ( $ exclusions ) ) as $ name => $ default ) { $ this -> $ name = $ default ; } return $ this ; } | Reset local class variables . |
585 | private function setSettings ( $ settings ) { if ( $ settings ) { foreach ( $ this -> settings as $ key => & $ value ) { if ( ! empty ( $ settings -> { $ key } ) && $ settings -> { $ key } ) { if ( is_object ( $ settings -> { $ key } ) ) { $ value = array_merge ( $ value , json_decode ( json_encode ( $ settings -> { $ key } , JSON_FORCE_OBJECT ) , true ) ) ; } else { $ value = $ settings -> { $ key } ; } } } } } | Retrieve File settings from the payload to override our defaults . |
586 | public function run ( $ step = 'add' ) { $ this -> setLogs ( $ step , 'step' ) ; switch ( $ step ) { case 'add' : $ this -> getFieldValues ( ) ; $ this -> fileEntitySelect ( true ) ; $ this -> fileEntityRefreshSettings ( ) ; $ this -> addContactToQueue ( ) ; break ; case 'build' : if ( $ this -> test ) { $ this -> getFieldValues ( ) ; } $ this -> fileEntitySelect ( ) ; $ this -> evaluateSchedule ( true ) ; $ this -> fileEntityRefreshSettings ( ) ; $ this -> fileBuild ( ) ; break ; case 'send' : $ this -> fileEntitySelect ( false , File :: STATUS_READY ) ; $ this -> evaluateSchedule ( true ) ; $ this -> fileSend ( ) ; break ; } return $ this ; } | These steps can occur in different sessions . |
587 | private function fileEntityRefreshSettings ( ) { if ( $ this -> file ) { if ( ! empty ( $ this -> settings [ 'name' ] ) && ! $ this -> file -> getLocation ( ) ) { $ this -> file -> setName ( $ this -> settings [ 'name' ] ) ; } if ( ! empty ( $ this -> settings [ 'type' ] ) ) { if ( ! empty ( $ this -> settings [ 'type' ] [ 'key' ] ) ) { $ this -> file -> setType ( $ this -> settings [ 'type' ] [ 'key' ] ) ; } if ( ! empty ( $ this -> settings [ 'type' ] [ 'delimiter' ] ) ) { $ this -> file -> setCsvDelimiter ( $ this -> settings [ 'type' ] [ 'delimiter' ] ) ; } if ( ! empty ( $ this -> settings [ 'type' ] [ 'enclosure' ] ) ) { $ this -> file -> setCsvEnclosure ( $ this -> settings [ 'type' ] [ 'enclosure' ] ) ; } if ( ! empty ( $ this -> settings [ 'type' ] [ 'escape' ] ) ) { $ this -> file -> setCsvEscape ( $ this -> settings [ 'type' ] [ 'escape' ] ) ; } if ( ! empty ( $ this -> settings [ 'type' ] [ 'terminate' ] ) ) { $ this -> file -> setCsvTerminate ( $ this -> settings [ 'type' ] [ 'terminate' ] ) ; } if ( ! empty ( $ this -> settings [ 'type' ] [ 'null' ] ) ) { $ this -> file -> setCsvNull ( $ this -> settings [ 'type' ] [ 'null' ] ) ; } } if ( isset ( $ this -> settings [ 'compression' ] ) ) { $ this -> file -> setCompression ( $ this -> settings [ 'compression' ] ) ; } if ( isset ( $ this -> settings [ 'exclusions' ] ) ) { $ this -> file -> setExclusions ( $ this -> settings [ 'exclusions' ] ) ; } if ( ! empty ( $ this -> settings [ 'headers' ] ) ) { $ this -> file -> setHeaders ( ( bool ) $ this -> settings [ 'headers' ] ) ; } if ( $ this -> count ) { $ this -> file -> setCount ( $ this -> count ) ; $ this -> setLogs ( $ this -> count , 'count' ) ; } if ( $ this -> scheduleStart ) { $ this -> file -> setDateAdded ( $ this -> scheduleStart ) ; } } return $ this ; } | Update fields on the file entity based on latest data . |
588 | public function evaluateSchedule ( $ prepFile = false ) { if ( ! $ this -> scheduleStart && ! $ this -> test ) { $ rate = max ( 1 , ( int ) $ this -> settings [ 'rate' ] ) ; $ endDay = 30 ; $ this -> scheduleModel -> reset ( ) -> setContactClient ( $ this -> contactClient ) -> setTimezone ( ) ; $ openings = $ this -> scheduleModel -> findOpening ( 0 , $ endDay , $ rate ) ; if ( ! $ openings ) { throw new ContactClientException ( 'Could not find an open time slot to send in the next ' . $ endDay . ' days' , 0 , null , Stat :: TYPE_SCHEDULE , false ) ; } $ opening = reset ( $ openings ) ; list ( $ start , $ end ) = $ opening ; if ( $ prepFile ) { $ now = new \ DateTime ( ) ; $ prepStart = clone $ start ; $ prepEnd = clone $ end ; $ prepStart -> modify ( '-' . self :: FILE_PREP_BEFORE_TIME ) ; $ prepEnd -> modify ( '+' . self :: FILE_PREP_AFTER_TIME ) ; if ( $ now < $ prepStart || $ now > $ prepEnd ) { throw new ContactClientException ( 'It is not yet time to prepare the next file for this client.' , 0 , null , Stat :: TYPE_SCHEDULE , false ) ; } } $ this -> scheduleStart = $ start ; } return $ this -> scheduleStart ; } | Assuming we have a file entity ready to go Throws an exception if an open slot is not available . |
589 | private function fileGenerateTmp ( $ compression = null ) { $ fileTmp = null ; $ compression = 'none' == $ compression ? null : $ compression ; while ( true ) { $ fileTmpName = uniqid ( $ this -> getFileName ( $ compression ) , true ) ; $ fileTmp = sys_get_temp_dir ( ) . '/' . $ fileTmpName ; if ( ! file_exists ( $ fileTmp ) ) { if ( ! $ compression ) { $ this -> file -> setTmp ( $ fileTmp ) ; $ this -> setLogs ( $ fileTmp , 'fileTmp' ) ; } break ; } } return $ fileTmp ; } | Generates a temporary path for file generation . |
590 | private function getFileName ( $ compression = null ) { $ compression = 'none' == $ compression ? null : $ compression ; $ this -> tokenHelper -> newSession ( $ this -> contactClient , $ this -> contact , $ this -> payload , $ this -> campaign , $ this -> event ) ; $ type = $ this -> file -> getType ( ) ; $ type = str_ireplace ( 'custom' , '' , $ type ) ; $ extension = $ type . ( $ compression ? '.' . $ compression : '' ) ; $ this -> settings [ 'name' ] = str_replace ( [ '{{count}}' , '{{test}}' , '{{date}}' , '{{time}}' , '{{type}}' , '{{compression}}' , '{{extension}}' , ] , [ '{{file_count}}' , '{{file_test}}' , '{{file_date|date.yyyy-mm-dd}}' , '{{file_date|date.hh-mm-ss}}' , '{{file_type}}' , '{{file_compression}}' , '{{file_extension}}' , ] , $ this -> settings [ 'name' ] ) ; $ this -> tokenHelper -> addContext ( [ 'file_count' => ( $ this -> count ? $ this -> count : 0 ) , 'file_test' => $ this -> test ? '.test' : '' , 'file_date' => $ this -> tokenHelper -> getDateFormatHelper ( ) -> format ( new \ DateTime ( ) ) , 'file_type' => $ type , 'file_compression' => $ compression , 'file_extension' => $ extension , ] ) ; $ result = $ this -> tokenHelper -> render ( $ this -> settings [ 'name' ] ) ; return trim ( $ result ) ; } | Discern the desired output file name for a new file . |
591 | private function fileEntitySave ( ) { if ( ! $ this -> file ) { return ; } if ( $ this -> file -> isNew ( ) || $ this -> file -> getChanges ( ) ) { if ( $ this -> contactClient -> getId ( ) ) { $ this -> formModel -> saveEntity ( $ this -> file , true ) ; } } } | Save any file changes using the form model . |
592 | private function fileCompress ( ) { if ( $ this -> file && $ this -> file -> getTmp ( ) ) { $ compression = $ this -> file -> getCompression ( ) ; if ( $ compression && in_array ( $ compression , [ 'tar.gz' , 'tar.bz2' , 'zip' ] ) ) { $ target = $ this -> fileGenerateTmp ( $ compression ) ; $ fileName = $ this -> getFileName ( ) ; try { switch ( $ compression ) { case 'tar.gz' : $ phar = new \ PharData ( $ target ) ; $ phar -> addFile ( $ this -> file -> getTmp ( ) , $ fileName ) ; $ phar -> compress ( \ Phar :: GZ , $ compression ) ; $ target = $ phar -> getRealPath ( ) ; break ; case 'tar.bz2' : $ phar = new \ PharData ( $ target ) ; $ phar -> addFile ( $ this -> file -> getTmp ( ) , $ fileName ) ; $ phar -> compress ( \ Phar :: BZ2 , $ compression ) ; $ target = $ phar -> getRealPath ( ) ; break ; default : case 'zip' : $ zip = new \ ZipArchive ( ) ; if ( true !== $ zip -> open ( $ target , \ ZipArchive :: CREATE ) ) { throw new ContactClientException ( 'Cound not open zip ' . $ target , Codes :: HTTP_INTERNAL_SERVER_ERROR , null , Stat :: TYPE_ERROR , false ) ; } $ zip -> addFile ( $ this -> file -> getTmp ( ) , $ fileName ) ; $ zip -> close ( ) ; break ; } $ this -> file -> setTmp ( $ target ) ; $ this -> setLogs ( $ target , 'fileCompressed' ) ; } catch ( \ Exception $ e ) { throw new ContactClientException ( 'Could not create compressed file ' . $ target , Codes :: HTTP_INTERNAL_SERVER_ERROR , $ e , Stat :: TYPE_ERROR , false ) ; } } else { $ this -> setLogs ( false , 'fileCompressed' ) ; } } return $ this ; } | Perform compression on the temp file . |
593 | private function fileMove ( $ overwrite = true ) { if ( ! $ this -> file -> getLocation ( ) || $ overwrite ) { $ origin = $ this -> file -> getTmp ( ) ; $ uploadDir = realpath ( $ this -> coreParametersHelper -> getParameter ( 'upload_dir' ) ) ; $ fileName = $ this -> getFileName ( $ this -> file -> getCompression ( ) ) ; $ target = $ uploadDir . '/client_payloads/' . $ this -> contactClient -> getId ( ) . '/' . $ fileName ; if ( $ origin && ( ! file_exists ( $ target ) || $ overwrite ) ) { $ this -> filesystemLocal -> copy ( $ origin , $ target , $ overwrite ) ; if ( file_exists ( $ target ) ) { $ this -> file -> setName ( $ fileName ) ; $ this -> setLogs ( $ fileName , 'fileName' ) ; $ this -> file -> setDateAdded ( new \ DateTime ( ) ) ; $ this -> file -> setLocation ( $ target ) ; $ this -> setLogs ( $ target , 'fileLocation' ) ; $ crc32 = hash_file ( 'crc32b' , $ target ) ; $ this -> file -> setCrc32 ( $ crc32 ) ; $ this -> setLogs ( $ crc32 , 'crc32' ) ; $ md5 = hash_file ( 'md5' , $ target ) ; $ this -> file -> setMd5 ( $ md5 ) ; $ this -> setLogs ( $ md5 , 'md5' ) ; $ sha1 = hash_file ( 'sha1' , $ target ) ; $ this -> file -> setSha1 ( $ sha1 ) ; $ this -> setLogs ( $ sha1 , 'sha1' ) ; $ this -> setLogs ( filesize ( $ target ) , 'fileSize' ) ; $ this -> filesystemLocal -> remove ( $ origin ) ; $ this -> file -> setStatus ( File :: STATUS_READY ) ; $ this -> setLogs ( $ this -> file -> getStatus ( ) , 'fileStatus' ) ; } else { throw new ContactClientException ( 'Could not move file to local location.' , Codes :: HTTP_INTERNAL_SERVER_ERROR , null , Stat :: TYPE_ERROR , false ) ; } } } return $ this ; } | Moves the file out of temp and locks the hashes . |
594 | private function operationSftp ( $ operation ) { $ config = $ this -> operationFtpConfig ( $ operation ) ; $ adapter = new SftpAdapter ( $ config ) ; $ filesystem = new Filesystem ( $ adapter ) ; $ written = false ; if ( $ stream = fopen ( $ this -> file -> getLocation ( ) , 'r+' ) ) { $ this -> setLogs ( $ this -> file -> getLocation ( ) , 'sftpUploading' ) ; $ written = $ filesystem -> writeStream ( $ this -> file -> getName ( ) , $ stream ) ; if ( is_resource ( $ stream ) ) { fclose ( $ stream ) ; } $ this -> setLogs ( $ written , 'sftpConfirmed' ) ; if ( ! $ written ) { $ this -> setLogs ( 'Could not confirm file upload via SFTP' , 'error' ) ; } else { $ this -> setLogs ( $ filesystem -> has ( $ this -> file -> getName ( ) ) , 'sftpConfirmed2' ) ; } } else { $ this -> setLogs ( 'Unable to open file for upload via SFTP.' , 'error' ) ; } return $ written ; } | Upload the current client file by sFTP . |
595 | public function getExternalId ( ) { if ( $ this -> file && $ this -> file -> getCrc32 ( ) ) { return $ this -> file -> getName ( ) . ' (' . $ this -> file -> getCrc32 ( ) . ')' ; } return null ; } | Since there is no external ID when sending files we ll include the file name and CRC check at creation . |
596 | public function pushLead ( $ contact , $ event = [ ] ) { $ this -> reset ( ) ; $ this -> getEvent ( $ event ) ; if ( empty ( $ this -> event [ 'config' ] [ 'contactclient' ] ) ) { return false ; } $ clientModel = $ this -> getContactClientModel ( ) ; $ client = $ clientModel -> getEntity ( $ this -> event [ 'config' ] [ 'contactclient' ] ) ; $ this -> sendContact ( $ client , $ contact , false ) ; return $ this -> valid ? $ this -> valid : ! $ this -> retry ; } | Push a contact to a preconfigured Contact Client . |
597 | public function getEvent ( $ event = [ ] ) { if ( ! $ this -> event ) { $ this -> event = $ event ; if ( isset ( $ event [ 'config' ] ) && ( empty ( $ event [ 'integration' ] ) || ( ! empty ( $ event [ 'integration' ] ) && $ event [ 'integration' ] == $ this -> getName ( ) ) ) ) { $ this -> event [ 'config' ] = array_merge ( $ this -> settings -> getFeatureSettings ( ) , $ event [ 'config' ] ) ; } if ( isset ( $ this -> event [ 'campaignEvent' ] ) && ! empty ( $ this -> event [ 'campaignEvent' ] ) ) { $ campaignEvent = $ this -> event [ 'campaignEvent' ] ; $ this -> event [ 'id' ] = $ campaignEvent [ 'id' ] ; $ this -> event [ 'campaignId' ] = $ campaignEvent [ 'campaign' ] [ 'id' ] ; } if ( ! isset ( $ this -> event [ 'id' ] ) || ! is_numeric ( $ this -> event [ 'id' ] ) ) { try { $ identityMap = $ this -> em -> getUnitOfWork ( ) -> getIdentityMap ( ) ; if ( isset ( $ identityMap [ 'Mautic\CampaignBundle\Entity\Event' ] ) ) { if ( isset ( $ identityMap [ 'Mautic\CampaignBundle\Entity\Campaign' ] ) && ! empty ( $ identityMap [ 'Mautic\CampaignBundle\Entity\Campaign' ] ) ) { $ memoryCampaign = end ( $ identityMap [ 'Mautic\CampaignBundle\Entity\Campaign' ] ) ; $ campaignId = $ memoryCampaign -> getId ( ) ; foreach ( $ identityMap [ 'Mautic\CampaignBundle\Entity\Event' ] as $ leadEvent ) { $ properties = $ leadEvent -> getProperties ( ) ; $ campaign = $ leadEvent -> getCampaign ( ) ; if ( $ properties [ '_token' ] === $ this -> event [ '_token' ] && $ campaignId == $ campaign -> getId ( ) ) { $ this -> event [ 'id' ] = $ leadEvent -> getId ( ) ; $ this -> event [ 'name' ] = $ leadEvent -> getName ( ) ; $ this -> event [ 'campaignId' ] = $ campaign -> getId ( ) ; break ; } } } } } catch ( \ Exception $ e ) { } } } return $ this -> event ; } | Merges a config from integration_list with feature settings . |
598 | private function getPayloadModel ( ContactClient $ contactClient = null ) { if ( ! $ this -> payloadModel || $ contactClient ) { $ contactClient = $ contactClient ? $ contactClient : $ this -> contactClient ; $ clientType = $ contactClient -> getType ( ) ; if ( 'api' == $ clientType ) { $ model = $ this -> getApiPayloadModel ( ) ; } elseif ( 'file' == $ clientType ) { $ model = $ this -> getFilePayloadModel ( ) ; } else { throw new \ InvalidArgumentException ( 'Client type is invalid.' ) ; } $ model -> reset ( ) ; $ model -> setTest ( $ this -> test ) ; $ model -> setContactClient ( $ contactClient ) ; if ( $ this -> contact ) { $ model -> setContact ( $ this -> contact ) ; } $ this -> payloadModel = $ model ; } return $ this -> payloadModel ; } | Get the current Payload model or the model of a particular client . |
599 | private function evaluateDnc ( ) { if ( $ this -> test ) { return $ this ; } $ channels = explode ( ',' , $ this -> contactClient -> getDncChecks ( ) ) ; if ( $ channels ) { foreach ( $ channels as $ channel ) { $ dncRepo = $ this -> getDncRepo ( ) ; $ dncRepo -> setDispatcher ( $ this -> dispatcher ) ; $ dncEntries = $ dncRepo -> getEntriesByLeadAndChannel ( $ this -> contact , $ channel ) ; if ( ! empty ( $ dncEntries ) ) { foreach ( $ dncEntries as $ dnc ) { $ comments = ! in_array ( $ dnc -> getComments ( ) , [ 'user' , 'system' ] ) ? $ dnc -> getComments ( ) : '' ; throw new ContactClientException ( trim ( $ this -> translator -> trans ( 'mautic.contactclient.sendcontact.error.dnc' , [ '%channel%' => $ this -> getDncChannelName ( $ channel ) , '%date%' => $ dnc -> getDateAdded ( ) -> format ( 'Y-m-d H:i:s e' ) , '%comments%' => $ comments , ] ) ) , 0 , null , Stat :: TYPE_DNC , false ) ; } } } } return $ this ; } | Evaluates the DNC entries for the Contact against the Client settings . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.