repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/Interface_.php
Interface_.doCreate
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $docBlock = $this->createDocBlock($strategies, $object->getDocComment(), $context); $parents = []; foreach ($object->extends as $extend) { $parents['\\' . (string) $extend] = new Fqsen('\\' . (string) $extend); } $interface = new InterfaceElement($object->fqsen, $parents, $docBlock, new Location($object->getLine())); if (isset($object->stmts)) { foreach ($object->stmts as $stmt) { switch (get_class($stmt)) { case ClassMethod::class: $method = $this->createMember($stmt, $strategies, $context); $interface->addMethod($method); break; case ClassConst::class: $constants = new ClassConstantIterator($stmt); foreach ($constants as $const) { $element = $this->createMember($const, $strategies, $context); $interface->addConstant($element); } break; } } } return $interface; }
php
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $docBlock = $this->createDocBlock($strategies, $object->getDocComment(), $context); $parents = []; foreach ($object->extends as $extend) { $parents['\\' . (string) $extend] = new Fqsen('\\' . (string) $extend); } $interface = new InterfaceElement($object->fqsen, $parents, $docBlock, new Location($object->getLine())); if (isset($object->stmts)) { foreach ($object->stmts as $stmt) { switch (get_class($stmt)) { case ClassMethod::class: $method = $this->createMember($stmt, $strategies, $context); $interface->addMethod($method); break; case ClassConst::class: $constants = new ClassConstantIterator($stmt); foreach ($constants as $const) { $element = $this->createMember($const, $strategies, $context); $interface->addConstant($element); } break; } } } return $interface; }
[ "protected", "function", "doCreate", "(", "$", "object", ",", "StrategyContainer", "$", "strategies", ",", "?", "Context", "$", "context", "=", "null", ")", "{", "$", "docBlock", "=", "$", "this", "->", "createDocBlock", "(", "$", "strategies", ",", "$", ...
Creates an Interface_ out of the given object. Since an object might contain other objects that need to be converted the $factory is passed so it can be used to create nested Elements. @param InterfaceNode $object object to convert to an Element @param StrategyContainer $strategies used to convert nested objects. @param Context $context of the created object @return InterfaceElement
[ "Creates", "an", "Interface_", "out", "of", "the", "given", "object", ".", "Since", "an", "object", "might", "contain", "other", "objects", "that", "need", "to", "be", "converted", "the", "$factory", "is", "passed", "so", "it", "can", "be", "used", "to", ...
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/Interface_.php#L49-L78
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/Method.php
Method.doCreate
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $docBlock = $this->createDocBlock($strategies, $object->getDocComment(), $context); $returnType = null; if ($object->getReturnType() !== null) { $typeResolver = new TypeResolver(); if ($object->getReturnType() instanceof NullableType) { $typeString = '?' . $object->getReturnType()->type; } else { $typeString = (string) $object->getReturnType(); } $returnType = $typeResolver->resolve($typeString, $context); } $method = new MethodDescriptor( $object->fqsen, $this->buildVisibility($object), $docBlock, $object->isAbstract(), $object->isStatic(), $object->isFinal(), new Location($object->getLine()), $returnType ); foreach ($object->params as $param) { $method->addArgument($this->createMember($param, $strategies, $context)); } return $method; }
php
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $docBlock = $this->createDocBlock($strategies, $object->getDocComment(), $context); $returnType = null; if ($object->getReturnType() !== null) { $typeResolver = new TypeResolver(); if ($object->getReturnType() instanceof NullableType) { $typeString = '?' . $object->getReturnType()->type; } else { $typeString = (string) $object->getReturnType(); } $returnType = $typeResolver->resolve($typeString, $context); } $method = new MethodDescriptor( $object->fqsen, $this->buildVisibility($object), $docBlock, $object->isAbstract(), $object->isStatic(), $object->isFinal(), new Location($object->getLine()), $returnType ); foreach ($object->params as $param) { $method->addArgument($this->createMember($param, $strategies, $context)); } return $method; }
[ "protected", "function", "doCreate", "(", "$", "object", ",", "StrategyContainer", "$", "strategies", ",", "?", "Context", "$", "context", "=", "null", ")", "{", "$", "docBlock", "=", "$", "this", "->", "createDocBlock", "(", "$", "strategies", ",", "$", ...
Creates an MethodDescriptor out of the given object including its child elements. @param ClassMethod $object object to convert to an MethodDescriptor @param StrategyContainer $strategies used to convert nested objects. @param Context $context of the created object @return MethodDescriptor
[ "Creates", "an", "MethodDescriptor", "out", "of", "the", "given", "object", "including", "its", "child", "elements", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/Method.php#L45-L77
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/Method.php
Method.buildVisibility
private function buildVisibility(ClassMethod $node): Visibility { if ($node->isPrivate()) { return new Visibility(Visibility::PRIVATE_); } elseif ($node->isProtected()) { return new Visibility(Visibility::PROTECTED_); } return new Visibility(Visibility::PUBLIC_); }
php
private function buildVisibility(ClassMethod $node): Visibility { if ($node->isPrivate()) { return new Visibility(Visibility::PRIVATE_); } elseif ($node->isProtected()) { return new Visibility(Visibility::PROTECTED_); } return new Visibility(Visibility::PUBLIC_); }
[ "private", "function", "buildVisibility", "(", "ClassMethod", "$", "node", ")", ":", "Visibility", "{", "if", "(", "$", "node", "->", "isPrivate", "(", ")", ")", "{", "return", "new", "Visibility", "(", "Visibility", "::", "PRIVATE_", ")", ";", "}", "els...
Converts the visibility of the method to a valid Visibility object.
[ "Converts", "the", "visibility", "of", "the", "method", "to", "a", "valid", "Visibility", "object", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/Method.php#L82-L91
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/File.php
File.doCreate
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $command = new CreateCommand($object, $strategies); $middlewareChain = $this->middlewareChain; return $middlewareChain($command); }
php
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $command = new CreateCommand($object, $strategies); $middlewareChain = $this->middlewareChain; return $middlewareChain($command); }
[ "protected", "function", "doCreate", "(", "$", "object", ",", "StrategyContainer", "$", "strategies", ",", "?", "Context", "$", "context", "=", "null", ")", "{", "$", "command", "=", "new", "CreateCommand", "(", "$", "object", ",", "$", "strategies", ")", ...
Creates an File out of the given object. Since an object might contain other objects that need to be converted the $factory is passed so it can be used to create nested Elements. @param FileSystemFile $object path to the file to convert to an File object. @param StrategyContainer $strategies used to convert nested objects. @return File
[ "Creates", "an", "File", "out", "of", "the", "given", "object", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/File.php#L85-L91
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/ClassConstantIterator.php
ClassConstantIterator.getDocComment
public function getDocComment(): ?Doc { $docComment = $this->classConstants->consts[$this->index]->getDocComment(); if ($docComment === null) { $docComment = $this->classConstants->getDocComment(); } return $docComment; }
php
public function getDocComment(): ?Doc { $docComment = $this->classConstants->consts[$this->index]->getDocComment(); if ($docComment === null) { $docComment = $this->classConstants->getDocComment(); } return $docComment; }
[ "public", "function", "getDocComment", "(", ")", ":", "?", "Doc", "{", "$", "docComment", "=", "$", "this", "->", "classConstants", "->", "consts", "[", "$", "this", "->", "index", "]", "->", "getDocComment", "(", ")", ";", "if", "(", "$", "docComment"...
Gets the doc comment of the node. The doc comment has to be the last comment associated with the node.
[ "Gets", "the", "doc", "comment", "of", "the", "node", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/ClassConstantIterator.php#L77-L85
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/ProjectFactoryStrategies.php
ProjectFactoryStrategies.findMatching
public function findMatching($object): ProjectFactoryStrategy { foreach ($this->strategies as $strategy) { if ($strategy->matches($object)) { return $strategy; } } throw new OutOfBoundsException( sprintf( 'No matching factory found for %s', is_object($object) ? get_class($object) : print_r($object, true) ) ); }
php
public function findMatching($object): ProjectFactoryStrategy { foreach ($this->strategies as $strategy) { if ($strategy->matches($object)) { return $strategy; } } throw new OutOfBoundsException( sprintf( 'No matching factory found for %s', is_object($object) ? get_class($object) : print_r($object, true) ) ); }
[ "public", "function", "findMatching", "(", "$", "object", ")", ":", "ProjectFactoryStrategy", "{", "foreach", "(", "$", "this", "->", "strategies", "as", "$", "strategy", ")", "{", "if", "(", "$", "strategy", "->", "matches", "(", "$", "object", ")", ")"...
Find the ProjectFactoryStrategy that matches $object. @param mixed $object @throws OutOfBoundsException when no matching strategy was found.
[ "Find", "the", "ProjectFactoryStrategy", "that", "matches", "$object", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/ProjectFactoryStrategies.php#L47-L61
phpDocumentor/Reflection
src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php
ElementNameResolver.leaveNode
public function leaveNode(Node $node) { switch (get_class($node)) { case Namespace_::class: case Class_::class: case ClassMethod::class: case Trait_::class: case PropertyProperty::class: case ClassConst::class: case Const_::class: case Interface_::class: case Function_::class: if (!$this->parts->isEmpty()) { $this->parts->pop(); } break; } }
php
public function leaveNode(Node $node) { switch (get_class($node)) { case Namespace_::class: case Class_::class: case ClassMethod::class: case Trait_::class: case PropertyProperty::class: case ClassConst::class: case Const_::class: case Interface_::class: case Function_::class: if (!$this->parts->isEmpty()) { $this->parts->pop(); } break; } }
[ "public", "function", "leaveNode", "(", "Node", "$", "node", ")", "{", "switch", "(", "get_class", "(", "$", "node", ")", ")", "{", "case", "Namespace_", "::", "class", ":", "case", "Class_", "::", "class", ":", "case", "ClassMethod", "::", "class", ":...
Performs a reset of the added element when needed.
[ "Performs", "a", "reset", "of", "the", "added", "element", "when", "needed", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php#L50-L67
phpDocumentor/Reflection
src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php
ElementNameResolver.enterNode
public function enterNode(Node $node): ?int { switch (get_class($node)) { case Namespace_::class: $this->resetState('\\' . $node->name . '\\'); $node->fqsen = new Fqsen($this->buildName()); break; case Class_::class: case Trait_::class: case Interface_::class: if (empty($node->name)) { return NodeTraverser::DONT_TRAVERSE_CHILDREN; } $this->parts->push((string)$node->name); $node->fqsen = new Fqsen($this->buildName()); break; case Function_::class: $this->parts->push($node->name . '()'); $node->fqsen = new Fqsen($this->buildName()); return NodeTraverser::DONT_TRAVERSE_CHILDREN; case ClassMethod::class: $this->parts->push('::' . $node->name . '()'); $node->fqsen = new Fqsen($this->buildName()); return NodeTraverser::DONT_TRAVERSE_CHILDREN; case ClassConst::class: $this->parts->push('::'); break; case Const_::class: $this->parts->push($node->name); $node->fqsen = new Fqsen($this->buildName()); break; case PropertyProperty::class: $this->parts->push('::$' . $node->name); $node->fqsen = new Fqsen($this->buildName()); break; } return null; }
php
public function enterNode(Node $node): ?int { switch (get_class($node)) { case Namespace_::class: $this->resetState('\\' . $node->name . '\\'); $node->fqsen = new Fqsen($this->buildName()); break; case Class_::class: case Trait_::class: case Interface_::class: if (empty($node->name)) { return NodeTraverser::DONT_TRAVERSE_CHILDREN; } $this->parts->push((string)$node->name); $node->fqsen = new Fqsen($this->buildName()); break; case Function_::class: $this->parts->push($node->name . '()'); $node->fqsen = new Fqsen($this->buildName()); return NodeTraverser::DONT_TRAVERSE_CHILDREN; case ClassMethod::class: $this->parts->push('::' . $node->name . '()'); $node->fqsen = new Fqsen($this->buildName()); return NodeTraverser::DONT_TRAVERSE_CHILDREN; case ClassConst::class: $this->parts->push('::'); break; case Const_::class: $this->parts->push($node->name); $node->fqsen = new Fqsen($this->buildName()); break; case PropertyProperty::class: $this->parts->push('::$' . $node->name); $node->fqsen = new Fqsen($this->buildName()); break; } return null; }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", ":", "?", "int", "{", "switch", "(", "get_class", "(", "$", "node", ")", ")", "{", "case", "Namespace_", "::", "class", ":", "$", "this", "->", "resetState", "(", "'\\\\'", ".", "$", ...
Adds fqsen property to a node when applicable. @todo this method is decorating the Node with an $fqsen property... since we can't declare it in PhpParser/NodeAbstract, we should add a decorator class wrapper in Reflection... that should clear up the PHPSTAN errors about "access to an undefined property ::$fqsen".
[ "Adds", "fqsen", "property", "to", "a", "node", "when", "applicable", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php#L78-L117
phpDocumentor/Reflection
src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php
ElementNameResolver.resetState
private function resetState(?string $namespace = null): void { $this->parts = new SplDoublyLinkedList(); $this->parts->push($namespace); }
php
private function resetState(?string $namespace = null): void { $this->parts = new SplDoublyLinkedList(); $this->parts->push($namespace); }
[ "private", "function", "resetState", "(", "?", "string", "$", "namespace", "=", "null", ")", ":", "void", "{", "$", "this", "->", "parts", "=", "new", "SplDoublyLinkedList", "(", ")", ";", "$", "this", "->", "parts", "->", "push", "(", "$", "namespace"...
Resets the state of the object to an empty state.
[ "Resets", "the", "state", "of", "the", "object", "to", "an", "empty", "state", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php#L122-L126
phpDocumentor/Reflection
src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php
ElementNameResolver.buildName
private function buildName(): string { $name = null; foreach ($this->parts as $part) { $name .= $part; } return rtrim((string) $name, '\\'); }
php
private function buildName(): string { $name = null; foreach ($this->parts as $part) { $name .= $part; } return rtrim((string) $name, '\\'); }
[ "private", "function", "buildName", "(", ")", ":", "string", "{", "$", "name", "=", "null", ";", "foreach", "(", "$", "this", "->", "parts", "as", "$", "part", ")", "{", "$", "name", ".=", "$", "part", ";", "}", "return", "rtrim", "(", "(", "stri...
Builds the name of the current node using the parts that are pushed to the parts list.
[ "Builds", "the", "name", "of", "the", "current", "node", "using", "the", "parts", "that", "are", "pushed", "to", "the", "parts", "list", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/NodeVisitor/ElementNameResolver.php#L131-L139
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/Argument.php
Argument.doCreate
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { Assert::isInstanceOf($object, Param::class); Assert::isInstanceOf($object->var, Variable::class); $default = null; if ($object->default !== null) { $default = $this->valueConverter->prettyPrintExpr($object->default); } $type = null; if (!empty($object->type)) { $type = $this->createType($object); } return new ArgumentDescriptor((string) $object->var->name, $type, $default, $object->byRef, $object->variadic); }
php
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { Assert::isInstanceOf($object, Param::class); Assert::isInstanceOf($object->var, Variable::class); $default = null; if ($object->default !== null) { $default = $this->valueConverter->prettyPrintExpr($object->default); } $type = null; if (!empty($object->type)) { $type = $this->createType($object); } return new ArgumentDescriptor((string) $object->var->name, $type, $default, $object->byRef, $object->variadic); }
[ "protected", "function", "doCreate", "(", "$", "object", ",", "StrategyContainer", "$", "strategies", ",", "?", "Context", "$", "context", "=", "null", ")", "{", "Assert", "::", "isInstanceOf", "(", "$", "object", ",", "Param", "::", "class", ")", ";", "...
Creates an ArgumentDescriptor out of the given object. Since an object might contain other objects that need to be converted the $factory is passed so it can be used to create nested Elements. @param Param $object object to convert to an Element @param StrategyContainer $strategies used to convert nested objects. @param Context $context of the created object @return ArgumentDescriptor
[ "Creates", "an", "ArgumentDescriptor", "out", "of", "the", "given", "object", ".", "Since", "an", "object", "might", "contain", "other", "objects", "that", "need", "to", "be", "converted", "the", "$factory", "is", "passed", "so", "it", "can", "be", "used", ...
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/Argument.php#L65-L80
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/NodesFactory.php
NodesFactory.createInstance
public static function createInstance($kind = ParserFactory::PREFER_PHP7): self { $parser = (new ParserFactory())->create($kind); $traverser = new NodeTraverser(); $traverser->addVisitor(new NameResolver()); $traverser->addVisitor(new ElementNameResolver()); return new static($parser, $traverser); }
php
public static function createInstance($kind = ParserFactory::PREFER_PHP7): self { $parser = (new ParserFactory())->create($kind); $traverser = new NodeTraverser(); $traverser->addVisitor(new NameResolver()); $traverser->addVisitor(new ElementNameResolver()); return new static($parser, $traverser); }
[ "public", "static", "function", "createInstance", "(", "$", "kind", "=", "ParserFactory", "::", "PREFER_PHP7", ")", ":", "self", "{", "$", "parser", "=", "(", "new", "ParserFactory", "(", ")", ")", "->", "create", "(", "$", "kind", ")", ";", "$", "trav...
Creates a new instance of NodeFactory with default Parser ands Traverser. @param int $kind One of ParserFactory::PREFER_PHP7, ParserFactory::PREFER_PHP5, ParserFactory::ONLY_PHP7 or ParserFactory::ONLY_PHP5 @return static
[ "Creates", "a", "new", "instance", "of", "NodeFactory", "with", "default", "Parser", "ands", "Traverser", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/NodesFactory.php#L63-L70
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/NodesFactory.php
NodesFactory.create
public function create(string $code): array { $stmt = $this->parser->parse($code); return $this->traverser->traverse($stmt); }
php
public function create(string $code): array { $stmt = $this->parser->parse($code); return $this->traverser->traverse($stmt); }
[ "public", "function", "create", "(", "string", "$", "code", ")", ":", "array", "{", "$", "stmt", "=", "$", "this", "->", "parser", "->", "parse", "(", "$", "code", ")", ";", "return", "$", "this", "->", "traverser", "->", "traverse", "(", "$", "stm...
Will convert the provided code to nodes. @param string $code code to process. @return Node[]
[ "Will", "convert", "the", "provided", "code", "to", "nodes", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/NodesFactory.php#L78-L82
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/Trait_.php
Trait_.doCreate
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $docBlock = $this->createDocBlock($strategies, $object->getDocComment(), $context); $trait = new TraitElement($object->fqsen, $docBlock, new Location($object->getLine())); if (isset($object->stmts)) { foreach ($object->stmts as $stmt) { switch (get_class($stmt)) { case PropertyNode::class: $properties = new PropertyIterator($stmt); foreach ($properties as $property) { $element = $this->createMember($property, $strategies, $context); $trait->addProperty($element); } break; case ClassMethod::class: $method = $this->createMember($stmt, $strategies, $context); $trait->addMethod($method); break; case TraitUse::class: foreach ($stmt->traits as $use) { $trait->addUsedTrait(new Fqsen('\\' . $use->toString())); } break; } } } return $trait; }
php
protected function doCreate($object, StrategyContainer $strategies, ?Context $context = null) { $docBlock = $this->createDocBlock($strategies, $object->getDocComment(), $context); $trait = new TraitElement($object->fqsen, $docBlock, new Location($object->getLine())); if (isset($object->stmts)) { foreach ($object->stmts as $stmt) { switch (get_class($stmt)) { case PropertyNode::class: $properties = new PropertyIterator($stmt); foreach ($properties as $property) { $element = $this->createMember($property, $strategies, $context); $trait->addProperty($element); } break; case ClassMethod::class: $method = $this->createMember($stmt, $strategies, $context); $trait->addMethod($method); break; case TraitUse::class: foreach ($stmt->traits as $use) { $trait->addUsedTrait(new Fqsen('\\' . $use->toString())); } break; } } } return $trait; }
[ "protected", "function", "doCreate", "(", "$", "object", ",", "StrategyContainer", "$", "strategies", ",", "?", "Context", "$", "context", "=", "null", ")", "{", "$", "docBlock", "=", "$", "this", "->", "createDocBlock", "(", "$", "strategies", ",", "$", ...
Creates an TraitElement out of the given object. Since an object might contain other objects that need to be converted the $factory is passed so it can be used to create nested Elements. @param TraitNode $object object to convert to an TraitElement @param StrategyContainer $strategies used to convert nested objects. @return TraitElement
[ "Creates", "an", "TraitElement", "out", "of", "the", "given", "object", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/Trait_.php#L47-L77
phpDocumentor/Reflection
src/phpDocumentor/Reflection/Php/Factory/PropertyIterator.php
PropertyIterator.getDocComment
public function getDocComment(): ?Doc { $docComment = $this->property->props[$this->index]->getDocComment(); if ($docComment === null) { $docComment = $this->property->getDocComment(); } return $docComment; }
php
public function getDocComment(): ?Doc { $docComment = $this->property->props[$this->index]->getDocComment(); if ($docComment === null) { $docComment = $this->property->getDocComment(); } return $docComment; }
[ "public", "function", "getDocComment", "(", ")", ":", "?", "Doc", "{", "$", "docComment", "=", "$", "this", "->", "property", "->", "props", "[", "$", "this", "->", "index", "]", "->", "getDocComment", "(", ")", ";", "if", "(", "$", "docComment", "==...
Gets the doc comment of the node. The doc comment has to be the last comment associated with the node.
[ "Gets", "the", "doc", "comment", "of", "the", "node", "." ]
train
https://github.com/phpDocumentor/Reflection/blob/0548704854fdaf6630ccc39fb92dc37487d05ad3/src/phpDocumentor/Reflection/Php/Factory/PropertyIterator.php#L92-L100
walkor/workerman-statistics
Applications/Statistics/Clients/StatisticClient.php
StatisticClient.report
public static function report($module, $interface, $success, $code, $msg, $report_address = '') { $report_address = $report_address ? $report_address : 'udp://127.0.0.1:55656'; if(isset(self::$timeMap[$module][$interface]) && self::$timeMap[$module][$interface] > 0) { $time_start = self::$timeMap[$module][$interface]; self::$timeMap[$module][$interface] = 0; } else if(isset(self::$timeMap['']['']) && self::$timeMap[''][''] > 0) { $time_start = self::$timeMap['']['']; self::$timeMap[''][''] = 0; } else { $time_start = microtime(true); } $cost_time = microtime(true) - $time_start; $bin_data = StatisticProtocol::encode($module, $interface, $cost_time, $success, $code, $msg); return self::sendData($report_address, $bin_data); }
php
public static function report($module, $interface, $success, $code, $msg, $report_address = '') { $report_address = $report_address ? $report_address : 'udp://127.0.0.1:55656'; if(isset(self::$timeMap[$module][$interface]) && self::$timeMap[$module][$interface] > 0) { $time_start = self::$timeMap[$module][$interface]; self::$timeMap[$module][$interface] = 0; } else if(isset(self::$timeMap['']['']) && self::$timeMap[''][''] > 0) { $time_start = self::$timeMap['']['']; self::$timeMap[''][''] = 0; } else { $time_start = microtime(true); } $cost_time = microtime(true) - $time_start; $bin_data = StatisticProtocol::encode($module, $interface, $cost_time, $success, $code, $msg); return self::sendData($report_address, $bin_data); }
[ "public", "static", "function", "report", "(", "$", "module", ",", "$", "interface", ",", "$", "success", ",", "$", "code", ",", "$", "msg", ",", "$", "report_address", "=", "''", ")", "{", "$", "report_address", "=", "$", "report_address", "?", "$", ...
上报统计数据 @param string $module @param string $interface @param bool $success @param int $code @param string $msg @param string $report_address @return boolean
[ "上报统计数据" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Clients/StatisticClient.php#L47-L70
walkor/workerman-statistics
Applications/Statistics/Clients/StatisticClient.php
StatisticClient.sendData
public static function sendData($address, $buffer) { $socket = stream_socket_client($address); if(!$socket) { return false; } return stream_socket_sendto($socket, $buffer) == strlen($buffer); }
php
public static function sendData($address, $buffer) { $socket = stream_socket_client($address); if(!$socket) { return false; } return stream_socket_sendto($socket, $buffer) == strlen($buffer); }
[ "public", "static", "function", "sendData", "(", "$", "address", ",", "$", "buffer", ")", "{", "$", "socket", "=", "stream_socket_client", "(", "$", "address", ")", ";", "if", "(", "!", "$", "socket", ")", "{", "return", "false", ";", "}", "return", ...
发送数据给统计系统 @param string $address @param string $buffer @return boolean
[ "发送数据给统计系统" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Clients/StatisticClient.php#L78-L86
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticWorker.php
StatisticWorker.onMessage
public function onMessage($connection, $data) { // 解码 $module = $data['module']; $interface = $data['interface']; $cost_time = $data['cost_time']; $success = $data['success']; $time = $data['time']; $code = $data['code']; $msg = str_replace("\n", "<br>", $data['msg']); $ip = $connection->getRemoteIp(); // 模块接口统计 $this->collectStatistics($module, $interface, $cost_time, $success, $ip, $code, $msg); // 全局统计 $this->collectStatistics('WorkerMan', 'Statistics', $cost_time, $success, $ip, $code, $msg); // 失败记录日志 if(!$success) { $this->logBuffer .= date('Y-m-d H:i:s',$time)."\t$ip\t$module::$interface\tcode:$code\tmsg:$msg\n"; if(strlen($this->logBuffer) >= self::MAX_LOG_BUFFER_SIZE) { $this->writeLogToDisk(); } } }
php
public function onMessage($connection, $data) { // 解码 $module = $data['module']; $interface = $data['interface']; $cost_time = $data['cost_time']; $success = $data['success']; $time = $data['time']; $code = $data['code']; $msg = str_replace("\n", "<br>", $data['msg']); $ip = $connection->getRemoteIp(); // 模块接口统计 $this->collectStatistics($module, $interface, $cost_time, $success, $ip, $code, $msg); // 全局统计 $this->collectStatistics('WorkerMan', 'Statistics', $cost_time, $success, $ip, $code, $msg); // 失败记录日志 if(!$success) { $this->logBuffer .= date('Y-m-d H:i:s',$time)."\t$ip\t$module::$interface\tcode:$code\tmsg:$msg\n"; if(strlen($this->logBuffer) >= self::MAX_LOG_BUFFER_SIZE) { $this->writeLogToDisk(); } } }
[ "public", "function", "onMessage", "(", "$", "connection", ",", "$", "data", ")", "{", "// 解码", "$", "module", "=", "$", "data", "[", "'module'", "]", ";", "$", "interface", "=", "$", "data", "[", "'interface'", "]", ";", "$", "cost_time", "=", "$", ...
业务处理 @see Man\Core.SocketWorker::dealProcess()
[ "业务处理" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticWorker.php#L92-L118
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticWorker.php
StatisticWorker.collectStatistics
protected function collectStatistics($module, $interface , $cost_time, $success, $ip, $code, $msg) { // 统计相关信息 if(!isset($this->statisticData[$ip])) { $this->statisticData[$ip] = array(); } if(!isset($this->statisticData[$ip][$module])) { $this->statisticData[$ip][$module] = array(); } if(!isset($this->statisticData[$ip][$module][$interface])) { $this->statisticData[$ip][$module][$interface] = array('code'=>array(), 'suc_cost_time'=>0, 'fail_cost_time'=>0, 'suc_count'=>0, 'fail_count'=>0); } if(!isset($this->statisticData[$ip][$module][$interface]['code'][$code])) { $this->statisticData[$ip][$module][$interface]['code'][$code] = 0; } $this->statisticData[$ip][$module][$interface]['code'][$code]++; if($success) { $this->statisticData[$ip][$module][$interface]['suc_cost_time'] += $cost_time; $this->statisticData[$ip][$module][$interface]['suc_count'] ++; } else { $this->statisticData[$ip][$module][$interface]['fail_cost_time'] += $cost_time; $this->statisticData[$ip][$module][$interface]['fail_count'] ++; } }
php
protected function collectStatistics($module, $interface , $cost_time, $success, $ip, $code, $msg) { // 统计相关信息 if(!isset($this->statisticData[$ip])) { $this->statisticData[$ip] = array(); } if(!isset($this->statisticData[$ip][$module])) { $this->statisticData[$ip][$module] = array(); } if(!isset($this->statisticData[$ip][$module][$interface])) { $this->statisticData[$ip][$module][$interface] = array('code'=>array(), 'suc_cost_time'=>0, 'fail_cost_time'=>0, 'suc_count'=>0, 'fail_count'=>0); } if(!isset($this->statisticData[$ip][$module][$interface]['code'][$code])) { $this->statisticData[$ip][$module][$interface]['code'][$code] = 0; } $this->statisticData[$ip][$module][$interface]['code'][$code]++; if($success) { $this->statisticData[$ip][$module][$interface]['suc_cost_time'] += $cost_time; $this->statisticData[$ip][$module][$interface]['suc_count'] ++; } else { $this->statisticData[$ip][$module][$interface]['fail_cost_time'] += $cost_time; $this->statisticData[$ip][$module][$interface]['fail_count'] ++; } }
[ "protected", "function", "collectStatistics", "(", "$", "module", ",", "$", "interface", ",", "$", "cost_time", ",", "$", "success", ",", "$", "ip", ",", "$", "code", ",", "$", "msg", ")", "{", "// 统计相关信息", "if", "(", "!", "isset", "(", "$", "this", ...
收集统计数据 @param string $module @param string $interface @param float $cost_time @param int $success @param string $ip @param int $code @param string $msg @return void
[ "收集统计数据" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticWorker.php#L131-L161
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticWorker.php
StatisticWorker.writeStatisticsToDisk
public function writeStatisticsToDisk() { $time = time(); // 循环将每个ip的统计数据写入磁盘 foreach($this->statisticData as $ip => $mod_if_data) { foreach($mod_if_data as $module=>$items) { // 文件夹不存在则创建一个 $file_dir = Config::$dataPath . $this->statisticDir.$module; if(!is_dir($file_dir)) { umask(0); mkdir($file_dir, 0777, true); } // 依次写入磁盘 foreach($items as $interface=>$data) { file_put_contents($file_dir. "/{$interface}.".date('Y-m-d'), "$ip\t$time\t{$data['suc_count']}\t{$data['suc_cost_time']}\t{$data['fail_count']}\t{$data['fail_cost_time']}\t".json_encode($data['code'])."\n", FILE_APPEND | LOCK_EX); } } } // 清空统计 $this->statisticData = array(); }
php
public function writeStatisticsToDisk() { $time = time(); // 循环将每个ip的统计数据写入磁盘 foreach($this->statisticData as $ip => $mod_if_data) { foreach($mod_if_data as $module=>$items) { // 文件夹不存在则创建一个 $file_dir = Config::$dataPath . $this->statisticDir.$module; if(!is_dir($file_dir)) { umask(0); mkdir($file_dir, 0777, true); } // 依次写入磁盘 foreach($items as $interface=>$data) { file_put_contents($file_dir. "/{$interface}.".date('Y-m-d'), "$ip\t$time\t{$data['suc_count']}\t{$data['suc_cost_time']}\t{$data['fail_count']}\t{$data['fail_cost_time']}\t".json_encode($data['code'])."\n", FILE_APPEND | LOCK_EX); } } } // 清空统计 $this->statisticData = array(); }
[ "public", "function", "writeStatisticsToDisk", "(", ")", "{", "$", "time", "=", "time", "(", ")", ";", "// 循环将每个ip的统计数据写入磁盘", "foreach", "(", "$", "this", "->", "statisticData", "as", "$", "ip", "=>", "$", "mod_if_data", ")", "{", "foreach", "(", "$", "m...
将统计数据写入磁盘 @return void
[ "将统计数据写入磁盘" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticWorker.php#L167-L191
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticWorker.php
StatisticWorker.writeLogToDisk
public function writeLogToDisk() { // 没有统计数据则返回 if(empty($this->logBuffer)) { return; } // 写入磁盘 file_put_contents(Config::$dataPath . $this->logDir . date('Y-m-d'), $this->logBuffer, FILE_APPEND | LOCK_EX); $this->logBuffer = ''; }
php
public function writeLogToDisk() { // 没有统计数据则返回 if(empty($this->logBuffer)) { return; } // 写入磁盘 file_put_contents(Config::$dataPath . $this->logDir . date('Y-m-d'), $this->logBuffer, FILE_APPEND | LOCK_EX); $this->logBuffer = ''; }
[ "public", "function", "writeLogToDisk", "(", ")", "{", "// 没有统计数据则返回", "if", "(", "empty", "(", "$", "this", "->", "logBuffer", ")", ")", "{", "return", ";", "}", "// 写入磁盘", "file_put_contents", "(", "Config", "::", "$", "dataPath", ".", "$", "this", "->...
将日志数据写入磁盘 @return void
[ "将日志数据写入磁盘" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticWorker.php#L197-L207
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticWorker.php
StatisticWorker.onStart
protected function onStart() { // 初始化目录 umask(0); $statistic_dir = Config::$dataPath . $this->statisticDir; if(!is_dir($statistic_dir)) { mkdir($statistic_dir, 0777, true); } $log_dir = Config::$dataPath . $this->logDir; if(!is_dir($log_dir)) { mkdir($log_dir, 0777, true); } // 定时保存统计数据 Timer::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeStatisticsToDisk')); Timer::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeLogToDisk')); // 定时清理不用的统计数据 Timer::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(Config::$dataPath . $this->statisticDir, self::EXPIRED_TIME)); Timer::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(Config::$dataPath . $this->logDir, self::EXPIRED_TIME)); }
php
protected function onStart() { // 初始化目录 umask(0); $statistic_dir = Config::$dataPath . $this->statisticDir; if(!is_dir($statistic_dir)) { mkdir($statistic_dir, 0777, true); } $log_dir = Config::$dataPath . $this->logDir; if(!is_dir($log_dir)) { mkdir($log_dir, 0777, true); } // 定时保存统计数据 Timer::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeStatisticsToDisk')); Timer::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeLogToDisk')); // 定时清理不用的统计数据 Timer::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(Config::$dataPath . $this->statisticDir, self::EXPIRED_TIME)); Timer::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(Config::$dataPath . $this->logDir, self::EXPIRED_TIME)); }
[ "protected", "function", "onStart", "(", ")", "{", "// 初始化目录", "umask", "(", "0", ")", ";", "$", "statistic_dir", "=", "Config", "::", "$", "dataPath", ".", "$", "this", "->", "statisticDir", ";", "if", "(", "!", "is_dir", "(", "$", "statistic_dir", ")...
初始化 统计目录检查 初始化任务 @see Man\Core.SocketWorker::onStart()
[ "初始化", "统计目录检查", "初始化任务" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticWorker.php#L215-L236
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticWorker.php
StatisticWorker.clearDisk
public function clearDisk($file = null, $exp_time = 86400) { $time_now = time(); if(is_file($file)) { $mtime = filemtime($file); if(!$mtime) { $this->notice("filemtime $file fail"); return; } if($time_now - $mtime > $exp_time) { unlink($file); } return; } foreach (glob($file."/*") as $file_name) { $this->clearDisk($file_name, $exp_time); } }
php
public function clearDisk($file = null, $exp_time = 86400) { $time_now = time(); if(is_file($file)) { $mtime = filemtime($file); if(!$mtime) { $this->notice("filemtime $file fail"); return; } if($time_now - $mtime > $exp_time) { unlink($file); } return; } foreach (glob($file."/*") as $file_name) { $this->clearDisk($file_name, $exp_time); } }
[ "public", "function", "clearDisk", "(", "$", "file", "=", "null", ",", "$", "exp_time", "=", "86400", ")", "{", "$", "time_now", "=", "time", "(", ")", ";", "if", "(", "is_file", "(", "$", "file", ")", ")", "{", "$", "mtime", "=", "filemtime", "(...
清除磁盘数据 @param string $file @param int $exp_time
[ "清除磁盘数据" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticWorker.php#L253-L274
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticProvider.php
StatisticProvider.onMessage
public function onMessage($connection, $recv_buffer) { $req_data = json_decode(trim($recv_buffer), true); $module = $req_data['module']; $interface = $req_data['interface']; $cmd = $req_data['cmd']; $start_time = isset($req_data['start_time']) ? $req_data['start_time'] : ''; $end_time = isset($req_data['end_time']) ? $req_data['end_time'] : ''; $date = isset($req_data['date']) ? $req_data['date'] : ''; $code = isset($req_data['code']) ? $req_data['code'] : ''; $msg = isset($req_data['msg']) ? $req_data['msg'] : ''; $offset = isset($req_data['offset']) ? $req_data['offset'] : ''; $count = isset($req_data['count']) ? $req_data['count'] : 10; switch($cmd) { case 'get_statistic': $buffer = json_encode(array('modules'=>$this->getModules($module), 'statistic' => $this->getStatistic($date, $module, $interface)))."\n"; $connection->send($buffer); break; case 'get_log': $buffer = json_encode($this->getStasticLog($module, $interface , $start_time , $end_time, $code, $msg, $offset, $count))."\n"; $connection->send($buffer); break; default : $connection->send('pack err'); } }
php
public function onMessage($connection, $recv_buffer) { $req_data = json_decode(trim($recv_buffer), true); $module = $req_data['module']; $interface = $req_data['interface']; $cmd = $req_data['cmd']; $start_time = isset($req_data['start_time']) ? $req_data['start_time'] : ''; $end_time = isset($req_data['end_time']) ? $req_data['end_time'] : ''; $date = isset($req_data['date']) ? $req_data['date'] : ''; $code = isset($req_data['code']) ? $req_data['code'] : ''; $msg = isset($req_data['msg']) ? $req_data['msg'] : ''; $offset = isset($req_data['offset']) ? $req_data['offset'] : ''; $count = isset($req_data['count']) ? $req_data['count'] : 10; switch($cmd) { case 'get_statistic': $buffer = json_encode(array('modules'=>$this->getModules($module), 'statistic' => $this->getStatistic($date, $module, $interface)))."\n"; $connection->send($buffer); break; case 'get_log': $buffer = json_encode($this->getStasticLog($module, $interface , $start_time , $end_time, $code, $msg, $offset, $count))."\n"; $connection->send($buffer); break; default : $connection->send('pack err'); } }
[ "public", "function", "onMessage", "(", "$", "connection", ",", "$", "recv_buffer", ")", "{", "$", "req_data", "=", "json_decode", "(", "trim", "(", "$", "recv_buffer", ")", ",", "true", ")", ";", "$", "module", "=", "$", "req_data", "[", "'module'", "...
处理请求统计 @param string $recv_buffer
[ "处理请求统计" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticProvider.php#L92-L118
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticProvider.php
StatisticProvider.getModules
public function getModules($current_module = '') { $st_dir = Config::$dataPath . $this->statisticDir; $modules_name_array = array(); foreach(glob($st_dir."/*", GLOB_ONLYDIR) as $module_file) { $tmp = explode("/", $module_file); $module = end($tmp); $modules_name_array[$module] = array(); if($current_module == $module) { $st_dir = $st_dir.$current_module.'/'; $all_interface = array(); foreach(glob($st_dir."*") as $file) { if(is_dir($file)) { continue; } list($interface, $date) = explode(".", basename($file)); $all_interface[$interface] = $interface; } $modules_name_array[$module] = $all_interface; } } return $modules_name_array; }
php
public function getModules($current_module = '') { $st_dir = Config::$dataPath . $this->statisticDir; $modules_name_array = array(); foreach(glob($st_dir."/*", GLOB_ONLYDIR) as $module_file) { $tmp = explode("/", $module_file); $module = end($tmp); $modules_name_array[$module] = array(); if($current_module == $module) { $st_dir = $st_dir.$current_module.'/'; $all_interface = array(); foreach(glob($st_dir."*") as $file) { if(is_dir($file)) { continue; } list($interface, $date) = explode(".", basename($file)); $all_interface[$interface] = $interface; } $modules_name_array[$module] = $all_interface; } } return $modules_name_array; }
[ "public", "function", "getModules", "(", "$", "current_module", "=", "''", ")", "{", "$", "st_dir", "=", "Config", "::", "$", "dataPath", ".", "$", "this", "->", "statisticDir", ";", "$", "modules_name_array", "=", "array", "(", ")", ";", "foreach", "(",...
获取模块 @return array
[ "获取模块" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticProvider.php#L124-L150
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticProvider.php
StatisticProvider.getStatistic
protected function getStatistic($date, $module, $interface) { if(empty($module) || empty($interface)) { return ''; } // log文件 $log_file = Config::$dataPath . $this->statisticDir."{$module}/{$interface}.{$date}"; $handle = @fopen($log_file, 'r'); if(!$handle) { return ''; } // 预处理统计数据,每5分钟一行 // [time=>[ip=>['suc_count'=>xx, 'suc_cost_time'=>xx, 'fail_count'=>xx, 'fail_cost_time'=>xx, 'code_map'=>[code=>count, ..], ..], ..] $statistics_data = array(); while(!feof($handle)) { $line = fgets($handle, 4096); if($line) { $explode = explode("\t", $line); if(count($explode) < 7) { continue; } list($ip, $time, $suc_count, $suc_cost_time, $fail_count, $fail_cost_time, $code_map) = $explode; $time = ceil($time/300)*300; if(!isset($statistics_data[$time])) { $statistics_data[$time] = array(); } if(!isset($statistics_data[$time][$ip])) { $statistics_data[$time][$ip] = array( 'suc_count' =>0, 'suc_cost_time' =>0, 'fail_count' =>0, 'fail_cost_time' =>0, 'code_map' =>array(), ); } $statistics_data[$time][$ip]['suc_count'] += $suc_count; $statistics_data[$time][$ip]['suc_cost_time'] += round($suc_cost_time, 5); $statistics_data[$time][$ip]['fail_count'] += $fail_count; $statistics_data[$time][$ip]['fail_cost_time'] += round($fail_cost_time, 5); $code_map = json_decode(trim($code_map), true); if($code_map && is_array($code_map)) { foreach($code_map as $code=>$count) { if(!isset($statistics_data[$time][$ip]['code_map'][$code])) { $statistics_data[$time][$ip]['code_map'][$code] = 0; } $statistics_data[$time][$ip]['code_map'][$code] +=$count; } } } // end if } // end while fclose($handle); ksort($statistics_data); // 整理数据 $statistics_str = ''; foreach($statistics_data as $time => $items) { foreach($items as $ip => $item) { $statistics_str .= "$ip\t$time\t{$item['suc_count']}\t{$item['suc_cost_time']}\t{$item['fail_count']}\t{$item['fail_cost_time']}\t".json_encode($item['code_map'])."\n"; } } return $statistics_str; }
php
protected function getStatistic($date, $module, $interface) { if(empty($module) || empty($interface)) { return ''; } // log文件 $log_file = Config::$dataPath . $this->statisticDir."{$module}/{$interface}.{$date}"; $handle = @fopen($log_file, 'r'); if(!$handle) { return ''; } // 预处理统计数据,每5分钟一行 // [time=>[ip=>['suc_count'=>xx, 'suc_cost_time'=>xx, 'fail_count'=>xx, 'fail_cost_time'=>xx, 'code_map'=>[code=>count, ..], ..], ..] $statistics_data = array(); while(!feof($handle)) { $line = fgets($handle, 4096); if($line) { $explode = explode("\t", $line); if(count($explode) < 7) { continue; } list($ip, $time, $suc_count, $suc_cost_time, $fail_count, $fail_cost_time, $code_map) = $explode; $time = ceil($time/300)*300; if(!isset($statistics_data[$time])) { $statistics_data[$time] = array(); } if(!isset($statistics_data[$time][$ip])) { $statistics_data[$time][$ip] = array( 'suc_count' =>0, 'suc_cost_time' =>0, 'fail_count' =>0, 'fail_cost_time' =>0, 'code_map' =>array(), ); } $statistics_data[$time][$ip]['suc_count'] += $suc_count; $statistics_data[$time][$ip]['suc_cost_time'] += round($suc_cost_time, 5); $statistics_data[$time][$ip]['fail_count'] += $fail_count; $statistics_data[$time][$ip]['fail_cost_time'] += round($fail_cost_time, 5); $code_map = json_decode(trim($code_map), true); if($code_map && is_array($code_map)) { foreach($code_map as $code=>$count) { if(!isset($statistics_data[$time][$ip]['code_map'][$code])) { $statistics_data[$time][$ip]['code_map'][$code] = 0; } $statistics_data[$time][$ip]['code_map'][$code] +=$count; } } } // end if } // end while fclose($handle); ksort($statistics_data); // 整理数据 $statistics_str = ''; foreach($statistics_data as $time => $items) { foreach($items as $ip => $item) { $statistics_str .= "$ip\t$time\t{$item['suc_count']}\t{$item['suc_cost_time']}\t{$item['fail_count']}\t{$item['fail_cost_time']}\t".json_encode($item['code_map'])."\n"; } } return $statistics_str; }
[ "protected", "function", "getStatistic", "(", "$", "date", ",", "$", "module", ",", "$", "interface", ")", "{", "if", "(", "empty", "(", "$", "module", ")", "||", "empty", "(", "$", "interface", ")", ")", "{", "return", "''", ";", "}", "// log文件", ...
获得统计数据 @param string $module @param string $interface @param int $date @return bool/string
[ "获得统计数据" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticProvider.php#L159-L235
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticProvider.php
StatisticProvider.getStasticLog
protected function getStasticLog($module, $interface , $start_time = '', $end_time = '', $code = '', $msg = '', $offset='', $count=100) { // log文件 $log_file = Config::$dataPath . $this->logDir. (empty($start_time) ? date('Y-m-d') : date('Y-m-d', $start_time)); if(!is_readable($log_file)) { return array('offset'=>0, 'data'=>''); } // 读文件 $h = fopen($log_file, 'r'); // 如果有时间,则进行二分查找,加速查询 if($start_time && $offset == 0 && ($file_size = filesize($log_file)) > 1024000) { $offset = $this->binarySearch(0, $file_size, $start_time-1, $h); $offset = $offset < 100000 ? 0 : $offset - 100000; } // 正则表达式 $pattern = "/^([\d: \-]+)\t\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\t"; if($module && $module != 'WorkerMan') { $pattern .= $module."::"; } else { $pattern .= ".*::"; } if($interface && $module != 'WorkerMan') { $pattern .= $interface."\t"; } else { $pattern .= ".*\t"; } if($code !== '') { $pattern .= "code:$code\t"; } else { $pattern .= "code:\d+\t"; } if($msg) { $pattern .= "msg:$msg"; } $pattern .= '/'; // 指定偏移位置 if($offset > 0) { fseek($h, (int)$offset-1); } // 查找符合条件的数据 $now_count = 0; $log_buffer = ''; while(1) { if(feof($h)) { break; } // 读1行 $line = fgets($h); if(preg_match($pattern, $line, $match)) { // 判断时间是否符合要求 $time = strtotime($match[1]); if($start_time) { if($time<$start_time) { continue; } } if($end_time) { if($time>$end_time) { break; } } // 收集符合条件的log $log_buffer .= $line; if(++$now_count >= $count) { break; } } } // 记录偏移位置 $offset = ftell($h); return array('offset'=>$offset, 'data'=>$log_buffer); }
php
protected function getStasticLog($module, $interface , $start_time = '', $end_time = '', $code = '', $msg = '', $offset='', $count=100) { // log文件 $log_file = Config::$dataPath . $this->logDir. (empty($start_time) ? date('Y-m-d') : date('Y-m-d', $start_time)); if(!is_readable($log_file)) { return array('offset'=>0, 'data'=>''); } // 读文件 $h = fopen($log_file, 'r'); // 如果有时间,则进行二分查找,加速查询 if($start_time && $offset == 0 && ($file_size = filesize($log_file)) > 1024000) { $offset = $this->binarySearch(0, $file_size, $start_time-1, $h); $offset = $offset < 100000 ? 0 : $offset - 100000; } // 正则表达式 $pattern = "/^([\d: \-]+)\t\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\t"; if($module && $module != 'WorkerMan') { $pattern .= $module."::"; } else { $pattern .= ".*::"; } if($interface && $module != 'WorkerMan') { $pattern .= $interface."\t"; } else { $pattern .= ".*\t"; } if($code !== '') { $pattern .= "code:$code\t"; } else { $pattern .= "code:\d+\t"; } if($msg) { $pattern .= "msg:$msg"; } $pattern .= '/'; // 指定偏移位置 if($offset > 0) { fseek($h, (int)$offset-1); } // 查找符合条件的数据 $now_count = 0; $log_buffer = ''; while(1) { if(feof($h)) { break; } // 读1行 $line = fgets($h); if(preg_match($pattern, $line, $match)) { // 判断时间是否符合要求 $time = strtotime($match[1]); if($start_time) { if($time<$start_time) { continue; } } if($end_time) { if($time>$end_time) { break; } } // 收集符合条件的log $log_buffer .= $line; if(++$now_count >= $count) { break; } } } // 记录偏移位置 $offset = ftell($h); return array('offset'=>$offset, 'data'=>$log_buffer); }
[ "protected", "function", "getStasticLog", "(", "$", "module", ",", "$", "interface", ",", "$", "start_time", "=", "''", ",", "$", "end_time", "=", "''", ",", "$", "code", "=", "''", ",", "$", "msg", "=", "''", ",", "$", "offset", "=", "''", ",", ...
获取指定日志
[ "获取指定日志" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticProvider.php#L242-L344
walkor/workerman-statistics
Applications/Statistics/Bootstrap/StatisticProvider.php
StatisticProvider.binarySearch
protected function binarySearch($start_point, $end_point, $time, $fd) { if($end_point - $start_point < 65535) { return $start_point; } // 计算中点 $mid_point = (int)(($end_point+$start_point)/2); // 定位文件指针在中点 fseek($fd, $mid_point - 1); // 读第一行 $line = fgets($fd); if(feof($fd) || false === $line) { return $start_point; } // 第一行可能数据不全,再读一行 $line = fgets($fd); if(feof($fd) || false === $line || trim($line) == '') { return $start_point; } // 判断是否越界 $current_point = ftell($fd); if($current_point>=$end_point) { return $start_point; } // 获得时间 $tmp = explode("\t", $line); $tmp_time = strtotime($tmp[0]); // 判断时间,返回指针位置 if($tmp_time > $time) { return $this->binarySearch($start_point, $current_point, $time, $fd); } elseif($tmp_time < $time) { return $this->binarySearch($current_point, $end_point, $time, $fd); } else { return $current_point; } }
php
protected function binarySearch($start_point, $end_point, $time, $fd) { if($end_point - $start_point < 65535) { return $start_point; } // 计算中点 $mid_point = (int)(($end_point+$start_point)/2); // 定位文件指针在中点 fseek($fd, $mid_point - 1); // 读第一行 $line = fgets($fd); if(feof($fd) || false === $line) { return $start_point; } // 第一行可能数据不全,再读一行 $line = fgets($fd); if(feof($fd) || false === $line || trim($line) == '') { return $start_point; } // 判断是否越界 $current_point = ftell($fd); if($current_point>=$end_point) { return $start_point; } // 获得时间 $tmp = explode("\t", $line); $tmp_time = strtotime($tmp[0]); // 判断时间,返回指针位置 if($tmp_time > $time) { return $this->binarySearch($start_point, $current_point, $time, $fd); } elseif($tmp_time < $time) { return $this->binarySearch($current_point, $end_point, $time, $fd); } else { return $current_point; } }
[ "protected", "function", "binarySearch", "(", "$", "start_point", ",", "$", "end_point", ",", "$", "time", ",", "$", "fd", ")", "{", "if", "(", "$", "end_point", "-", "$", "start_point", "<", "65535", ")", "{", "return", "$", "start_point", ";", "}", ...
日志二分查找法 @param int $start_point @param int $end_point @param int $time @param fd $fd @return int
[ "日志二分查找法" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Bootstrap/StatisticProvider.php#L353-L404
walkor/workerman-statistics
Applications/Statistics/Protocols/Statistic.php
Statistic.input
public static function input($recv_buffer) { if(strlen($recv_buffer) < self::PACKAGE_FIXED_LENGTH) { return 0; } $data = unpack("Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime", $recv_buffer); return $data['module_name_len'] + $data['interface_name_len'] + $data['msg_len'] + self::PACKAGE_FIXED_LENGTH; }
php
public static function input($recv_buffer) { if(strlen($recv_buffer) < self::PACKAGE_FIXED_LENGTH) { return 0; } $data = unpack("Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime", $recv_buffer); return $data['module_name_len'] + $data['interface_name_len'] + $data['msg_len'] + self::PACKAGE_FIXED_LENGTH; }
[ "public", "static", "function", "input", "(", "$", "recv_buffer", ")", "{", "if", "(", "strlen", "(", "$", "recv_buffer", ")", "<", "self", "::", "PACKAGE_FIXED_LENGTH", ")", "{", "return", "0", ";", "}", "$", "data", "=", "unpack", "(", "\"Cmodule_name_...
input @param string $recv_buffer
[ "input" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Protocols/Statistic.php#L63-L71
walkor/workerman-statistics
Applications/Statistics/Protocols/Statistic.php
Statistic.encode
public static function encode($data) { $module = $data['module']; $interface = $data['interface']; $cost_time = $data['cost_time']; $success = $data['success']; $code = isset($data['code']) ? $data['code'] : 0; $msg = isset($data['msg']) ? $data['msg'] : ''; // 防止模块名过长 if(strlen($module) > self::MAX_CHAR_VALUE) { $module = substr($module, 0, self::MAX_CHAR_VALUE); } // 防止接口名过长 if(strlen($interface) > self::MAX_CHAR_VALUE) { $interface = substr($interface, 0, self::MAX_CHAR_VALUE); } // 防止msg过长 $module_name_length = strlen($module); $interface_name_length = strlen($interface); $avalible_size = self::MAX_UDP_PACKGE_SIZE - self::PACKAGE_FIXED_LENGTH - $module_name_length - $interface_name_length; if(strlen($msg) > $avalible_size) { $msg = substr($msg, 0, $avalible_size); } // 打包 return pack('CCfCNnN', $module_name_length, $interface_name_length, $cost_time, $success ? 1 : 0, $code, strlen($msg), time()).$module.$interface.$msg; }
php
public static function encode($data) { $module = $data['module']; $interface = $data['interface']; $cost_time = $data['cost_time']; $success = $data['success']; $code = isset($data['code']) ? $data['code'] : 0; $msg = isset($data['msg']) ? $data['msg'] : ''; // 防止模块名过长 if(strlen($module) > self::MAX_CHAR_VALUE) { $module = substr($module, 0, self::MAX_CHAR_VALUE); } // 防止接口名过长 if(strlen($interface) > self::MAX_CHAR_VALUE) { $interface = substr($interface, 0, self::MAX_CHAR_VALUE); } // 防止msg过长 $module_name_length = strlen($module); $interface_name_length = strlen($interface); $avalible_size = self::MAX_UDP_PACKGE_SIZE - self::PACKAGE_FIXED_LENGTH - $module_name_length - $interface_name_length; if(strlen($msg) > $avalible_size) { $msg = substr($msg, 0, $avalible_size); } // 打包 return pack('CCfCNnN', $module_name_length, $interface_name_length, $cost_time, $success ? 1 : 0, $code, strlen($msg), time()).$module.$interface.$msg; }
[ "public", "static", "function", "encode", "(", "$", "data", ")", "{", "$", "module", "=", "$", "data", "[", "'module'", "]", ";", "$", "interface", "=", "$", "data", "[", "'interface'", "]", ";", "$", "cost_time", "=", "$", "data", "[", "'cost_time'"...
编码 @param string $module @param string $interface @param float $cost_time @param int $success @param int $code @param string $msg @return string
[ "编码" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Protocols/Statistic.php#L83-L115
walkor/workerman-statistics
Applications/Statistics/Protocols/Statistic.php
Statistic.decode
public static function decode($recv_buffer) { // 解包 $data = unpack("Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime", $recv_buffer); $module = substr($recv_buffer, self::PACKAGE_FIXED_LENGTH, $data['module_name_len']); $interface = substr($recv_buffer, self::PACKAGE_FIXED_LENGTH + $data['module_name_len'], $data['interface_name_len']); $msg = substr($recv_buffer, self::PACKAGE_FIXED_LENGTH + $data['module_name_len'] + $data['interface_name_len']); return array( 'module' => $module, 'interface' => $interface, 'cost_time' => $data['cost_time'], 'success' => $data['success'], 'time' => $data['time'], 'code' => $data['code'], 'msg' => $msg, ); }
php
public static function decode($recv_buffer) { // 解包 $data = unpack("Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime", $recv_buffer); $module = substr($recv_buffer, self::PACKAGE_FIXED_LENGTH, $data['module_name_len']); $interface = substr($recv_buffer, self::PACKAGE_FIXED_LENGTH + $data['module_name_len'], $data['interface_name_len']); $msg = substr($recv_buffer, self::PACKAGE_FIXED_LENGTH + $data['module_name_len'] + $data['interface_name_len']); return array( 'module' => $module, 'interface' => $interface, 'cost_time' => $data['cost_time'], 'success' => $data['success'], 'time' => $data['time'], 'code' => $data['code'], 'msg' => $msg, ); }
[ "public", "static", "function", "decode", "(", "$", "recv_buffer", ")", "{", "// 解包", "$", "data", "=", "unpack", "(", "\"Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime\"", ",", "$", "recv_buffer", ")", ";", "$", "module", "=", "substr",...
解包 @param string $recv_buffer @return array
[ "解包" ]
train
https://github.com/walkor/workerman-statistics/blob/5254e68a65f9061efc6066cc5361323112478f84/Applications/Statistics/Protocols/Statistic.php#L122-L138
gliterd/backblaze-b2
src/Client.php
Client.createBucket
public function createBucket(array $options) { if (!in_array($options['BucketType'], [Bucket::TYPE_PUBLIC, Bucket::TYPE_PRIVATE])) { throw new ValidationException( sprintf('Bucket type must be %s or %s', Bucket::TYPE_PRIVATE, Bucket::TYPE_PUBLIC) ); } $response = $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, 'bucketName' => $options['BucketName'], 'bucketType' => $options['BucketType'], ])->request('POST', '/b2_create_bucket'); return new Bucket($response['bucketId'], $response['bucketName'], $response['bucketType']); }
php
public function createBucket(array $options) { if (!in_array($options['BucketType'], [Bucket::TYPE_PUBLIC, Bucket::TYPE_PRIVATE])) { throw new ValidationException( sprintf('Bucket type must be %s or %s', Bucket::TYPE_PRIVATE, Bucket::TYPE_PUBLIC) ); } $response = $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, 'bucketName' => $options['BucketName'], 'bucketType' => $options['BucketType'], ])->request('POST', '/b2_create_bucket'); return new Bucket($response['bucketId'], $response['bucketName'], $response['bucketType']); }
[ "public", "function", "createBucket", "(", "array", "$", "options", ")", "{", "if", "(", "!", "in_array", "(", "$", "options", "[", "'BucketType'", "]", ",", "[", "Bucket", "::", "TYPE_PUBLIC", ",", "Bucket", "::", "TYPE_PRIVATE", "]", ")", ")", "{", "...
Create a bucket with the given name and type. @param array $options @throws ValidationException @return Bucket
[ "Create", "a", "bucket", "with", "the", "given", "name", "and", "type", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L64-L79
gliterd/backblaze-b2
src/Client.php
Client.updateBucket
public function updateBucket(array $options) { if (!in_array($options['BucketType'], [Bucket::TYPE_PUBLIC, Bucket::TYPE_PRIVATE])) { throw new ValidationException( sprintf('Bucket type must be %s or %s', Bucket::TYPE_PRIVATE, Bucket::TYPE_PUBLIC) ); } if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } $response = $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, 'bucketId' => $options['BucketId'], 'bucketType' => $options['BucketType'], ])->request('POST', '/b2_update_bucket'); return new Bucket($response['bucketId'], $response['bucketName'], $response['bucketType']); }
php
public function updateBucket(array $options) { if (!in_array($options['BucketType'], [Bucket::TYPE_PUBLIC, Bucket::TYPE_PRIVATE])) { throw new ValidationException( sprintf('Bucket type must be %s or %s', Bucket::TYPE_PRIVATE, Bucket::TYPE_PUBLIC) ); } if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } $response = $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, 'bucketId' => $options['BucketId'], 'bucketType' => $options['BucketType'], ])->request('POST', '/b2_update_bucket'); return new Bucket($response['bucketId'], $response['bucketName'], $response['bucketType']); }
[ "public", "function", "updateBucket", "(", "array", "$", "options", ")", "{", "if", "(", "!", "in_array", "(", "$", "options", "[", "'BucketType'", "]", ",", "[", "Bucket", "::", "TYPE_PUBLIC", ",", "Bucket", "::", "TYPE_PRIVATE", "]", ")", ")", "{", "...
Updates the type attribute of a bucket by the given ID. @param array $options @throws ValidationException @return Bucket
[ "Updates", "the", "type", "attribute", "of", "a", "bucket", "by", "the", "given", "ID", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L90-L109
gliterd/backblaze-b2
src/Client.php
Client.listBuckets
public function listBuckets() { $buckets = []; $response = $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, ])->request('POST', '/b2_list_buckets'); foreach ($response['buckets'] as $bucket) { $buckets[] = new Bucket($bucket['bucketId'], $bucket['bucketName'], $bucket['bucketType']); } return $buckets; }
php
public function listBuckets() { $buckets = []; $response = $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, ])->request('POST', '/b2_list_buckets'); foreach ($response['buckets'] as $bucket) { $buckets[] = new Bucket($bucket['bucketId'], $bucket['bucketName'], $bucket['bucketType']); } return $buckets; }
[ "public", "function", "listBuckets", "(", ")", "{", "$", "buckets", "=", "[", "]", ";", "$", "response", "=", "$", "this", "->", "generateAuthenticatedClient", "(", "[", "'accountId'", "=>", "$", "this", "->", "accountId", ",", "]", ")", "->", "request",...
Returns a list of bucket objects representing the buckets on the account. @throws \Exception @throws GuzzleException @return array
[ "Returns", "a", "list", "of", "bucket", "objects", "representing", "the", "buckets", "on", "the", "account", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L119-L132
gliterd/backblaze-b2
src/Client.php
Client.deleteBucket
public function deleteBucket(array $options) { if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } try { $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, 'bucketId' => $options['BucketId'], ])->request('POST', $this->apiUrl.'/b2_delete_bucket'); } catch (\Exception $e) { return false; } return true; }
php
public function deleteBucket(array $options) { if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } try { $this->generateAuthenticatedClient([ 'accountId' => $this->accountId, 'bucketId' => $options['BucketId'], ])->request('POST', $this->apiUrl.'/b2_delete_bucket'); } catch (\Exception $e) { return false; } return true; }
[ "public", "function", "deleteBucket", "(", "array", "$", "options", ")", "{", "if", "(", "!", "isset", "(", "$", "options", "[", "'BucketId'", "]", ")", "&&", "isset", "(", "$", "options", "[", "'BucketName'", "]", ")", ")", "{", "$", "options", "[",...
Deletes the bucket identified by its ID. @param array $options @throws \Exception @throws GuzzleException @return bool
[ "Deletes", "the", "bucket", "identified", "by", "its", "ID", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L144-L160
gliterd/backblaze-b2
src/Client.php
Client.download
public function download(array $options) { $requestUrl = null; $requestOptions = [ 'headers' => [ 'Authorization' => $this->authToken, ], 'sink' => isset($options['SaveAs']) ? $options['SaveAs'] : null, ]; if (isset($options['FileId'])) { $requestOptions['query'] = ['fileId' => $options['FileId']]; $requestUrl = $this->downloadUrl.'/b2api/v1/b2_download_file_by_id'; } else { if (!isset($options['BucketName']) && isset($options['BucketId'])) { $options['BucketName'] = $this->getBucketNameFromId($options['BucketId']); } $requestUrl = sprintf('%s/file/%s/%s', $this->downloadUrl, $options['BucketName'], $options['FileName']); } $this->authorizeAccount(); $response = $this->client->request('GET', $requestUrl, $requestOptions, false); return isset($options['SaveAs']) ? true : $response; }
php
public function download(array $options) { $requestUrl = null; $requestOptions = [ 'headers' => [ 'Authorization' => $this->authToken, ], 'sink' => isset($options['SaveAs']) ? $options['SaveAs'] : null, ]; if (isset($options['FileId'])) { $requestOptions['query'] = ['fileId' => $options['FileId']]; $requestUrl = $this->downloadUrl.'/b2api/v1/b2_download_file_by_id'; } else { if (!isset($options['BucketName']) && isset($options['BucketId'])) { $options['BucketName'] = $this->getBucketNameFromId($options['BucketId']); } $requestUrl = sprintf('%s/file/%s/%s', $this->downloadUrl, $options['BucketName'], $options['FileName']); } $this->authorizeAccount(); $response = $this->client->request('GET', $requestUrl, $requestOptions, false); return isset($options['SaveAs']) ? true : $response; }
[ "public", "function", "download", "(", "array", "$", "options", ")", "{", "$", "requestUrl", "=", "null", ";", "$", "requestOptions", "=", "[", "'headers'", "=>", "[", "'Authorization'", "=>", "$", "this", "->", "authToken", ",", "]", ",", "'sink'", "=>"...
Download a file from a B2 bucket. @param array $options @throws \Exception @return bool|mixed|string
[ "Download", "a", "file", "from", "a", "B2", "bucket", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L247-L273
gliterd/backblaze-b2
src/Client.php
Client.listFiles
public function listFiles(array $options) { // if FileName is set, we only attempt to retrieve information about that single file. $fileName = !empty($options['FileName']) ? $options['FileName'] : null; $nextFileName = null; $maxFileCount = 1000; $prefix = isset($options['Prefix']) ? $options['Prefix'] : ''; $delimiter = isset($options['Delimiter']) ? $options['Delimiter'] : null; $files = []; if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } if ($fileName) { $nextFileName = $fileName; $maxFileCount = 1; } $this->authorizeAccount(); // B2 returns, at most, 1000 files per "page". Loop through the pages and compile an array of File objects. while (true) { $response = $this->generateAuthenticatedClient([ 'bucketId' => $options['BucketId'], 'startFileName' => $nextFileName, 'maxFileCount' => $maxFileCount, 'prefix' => $prefix, 'delimiter' => $delimiter, ])->request('POST', '/b2_list_file_names'); foreach ($response['files'] as $file) { // if we have a file name set, only retrieve information if the file name matches if (!$fileName || ($fileName === $file['fileName'])) { $files[] = new File($file['fileId'], $file['fileName'], null, $file['size']); } } if ($fileName || $response['nextFileName'] === null) { // We've got all the files - break out of loop. break; } $nextFileName = $response['nextFileName']; } return $files; }
php
public function listFiles(array $options) { // if FileName is set, we only attempt to retrieve information about that single file. $fileName = !empty($options['FileName']) ? $options['FileName'] : null; $nextFileName = null; $maxFileCount = 1000; $prefix = isset($options['Prefix']) ? $options['Prefix'] : ''; $delimiter = isset($options['Delimiter']) ? $options['Delimiter'] : null; $files = []; if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } if ($fileName) { $nextFileName = $fileName; $maxFileCount = 1; } $this->authorizeAccount(); // B2 returns, at most, 1000 files per "page". Loop through the pages and compile an array of File objects. while (true) { $response = $this->generateAuthenticatedClient([ 'bucketId' => $options['BucketId'], 'startFileName' => $nextFileName, 'maxFileCount' => $maxFileCount, 'prefix' => $prefix, 'delimiter' => $delimiter, ])->request('POST', '/b2_list_file_names'); foreach ($response['files'] as $file) { // if we have a file name set, only retrieve information if the file name matches if (!$fileName || ($fileName === $file['fileName'])) { $files[] = new File($file['fileId'], $file['fileName'], null, $file['size']); } } if ($fileName || $response['nextFileName'] === null) { // We've got all the files - break out of loop. break; } $nextFileName = $response['nextFileName']; } return $files; }
[ "public", "function", "listFiles", "(", "array", "$", "options", ")", "{", "// if FileName is set, we only attempt to retrieve information about that single file.", "$", "fileName", "=", "!", "empty", "(", "$", "options", "[", "'FileName'", "]", ")", "?", "$", "option...
Retrieve a collection of File objects representing the files stored inside a bucket. @param array $options @throws \Exception @throws GuzzleException @return array
[ "Retrieve", "a", "collection", "of", "File", "objects", "representing", "the", "files", "stored", "inside", "a", "bucket", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L285-L335
gliterd/backblaze-b2
src/Client.php
Client.getFile
public function getFile(array $options) { if (!isset($options['FileId']) && isset($options['BucketName']) && isset($options['FileName'])) { $options['FileId'] = $this->getFileIdFromBucketAndFileName($options['BucketName'], $options['FileName']); if (!$options['FileId']) { throw new NotFoundException(); } } $response = $this->generateAuthenticatedClient([ 'fileId' => $options['FileId'], ])->request('POST', '/b2_get_file_info'); return new File( $response['fileId'], $response['fileName'], $response['contentSha1'], $response['contentLength'], $response['contentType'], $response['fileInfo'], $response['bucketId'], $response['action'], $response['uploadTimestamp'] ); }
php
public function getFile(array $options) { if (!isset($options['FileId']) && isset($options['BucketName']) && isset($options['FileName'])) { $options['FileId'] = $this->getFileIdFromBucketAndFileName($options['BucketName'], $options['FileName']); if (!$options['FileId']) { throw new NotFoundException(); } } $response = $this->generateAuthenticatedClient([ 'fileId' => $options['FileId'], ])->request('POST', '/b2_get_file_info'); return new File( $response['fileId'], $response['fileName'], $response['contentSha1'], $response['contentLength'], $response['contentType'], $response['fileInfo'], $response['bucketId'], $response['action'], $response['uploadTimestamp'] ); }
[ "public", "function", "getFile", "(", "array", "$", "options", ")", "{", "if", "(", "!", "isset", "(", "$", "options", "[", "'FileId'", "]", ")", "&&", "isset", "(", "$", "options", "[", "'BucketName'", "]", ")", "&&", "isset", "(", "$", "options", ...
Returns a single File object representing a file stored on B2. @param array $options @throws NotFoundException If no file id was provided and BucketName + FileName does not resolve to a file, a NotFoundException is thrown. @return File
[ "Returns", "a", "single", "File", "object", "representing", "a", "file", "stored", "on", "B2", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L363-L388
gliterd/backblaze-b2
src/Client.php
Client.deleteFile
public function deleteFile(array $options) { if (!isset($options['FileName'])) { $file = $this->getFile($options); $options['FileName'] = $file->getName(); } if (!isset($options['FileId']) && isset($options['BucketName']) && isset($options['FileName'])) { $file = $this->getFile($options); $options['FileId'] = $file->getId(); } try { $this->generateAuthenticatedClient([ 'fileName' => $options['FileName'], 'fileId' => $options['FileId'], ])->request('POST', '/b2_delete_file_version'); } catch (\Exception $e) { return false; } return true; }
php
public function deleteFile(array $options) { if (!isset($options['FileName'])) { $file = $this->getFile($options); $options['FileName'] = $file->getName(); } if (!isset($options['FileId']) && isset($options['BucketName']) && isset($options['FileName'])) { $file = $this->getFile($options); $options['FileId'] = $file->getId(); } try { $this->generateAuthenticatedClient([ 'fileName' => $options['FileName'], 'fileId' => $options['FileId'], ])->request('POST', '/b2_delete_file_version'); } catch (\Exception $e) { return false; } return true; }
[ "public", "function", "deleteFile", "(", "array", "$", "options", ")", "{", "if", "(", "!", "isset", "(", "$", "options", "[", "'FileName'", "]", ")", ")", "{", "$", "file", "=", "$", "this", "->", "getFile", "(", "$", "options", ")", ";", "$", "...
Deletes the file identified by ID from Backblaze B2. @param array $options @throws NotFoundException @throws GuzzleException @return bool
[ "Deletes", "the", "file", "identified", "by", "ID", "from", "Backblaze", "B2", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L400-L424
gliterd/backblaze-b2
src/Client.php
Client.authorizeAccount
protected function authorizeAccount() { if (Carbon::now('UTC')->timestamp > $this->reAuthTime->timestamp) { $response = $this->client->request('GET', 'https://api.backblazeb2.com/b2api/v1/b2_authorize_account', [ 'auth' => [$this->accountId, $this->applicationKey], ]); $this->authToken = $response['authorizationToken']; $this->apiUrl = $response['apiUrl'].'/b2api/v1'; $this->downloadUrl = $response['downloadUrl']; $this->reAuthTime = Carbon::now('UTC'); $this->reAuthTime->addSeconds($this->authTimeoutSeconds); } }
php
protected function authorizeAccount() { if (Carbon::now('UTC')->timestamp > $this->reAuthTime->timestamp) { $response = $this->client->request('GET', 'https://api.backblazeb2.com/b2api/v1/b2_authorize_account', [ 'auth' => [$this->accountId, $this->applicationKey], ]); $this->authToken = $response['authorizationToken']; $this->apiUrl = $response['apiUrl'].'/b2api/v1'; $this->downloadUrl = $response['downloadUrl']; $this->reAuthTime = Carbon::now('UTC'); $this->reAuthTime->addSeconds($this->authTimeoutSeconds); } }
[ "protected", "function", "authorizeAccount", "(", ")", "{", "if", "(", "Carbon", "::", "now", "(", "'UTC'", ")", "->", "timestamp", ">", "$", "this", "->", "reAuthTime", "->", "timestamp", ")", "{", "$", "response", "=", "$", "this", "->", "client", "-...
Authorize the B2 account in order to get an auth token and API/download URLs. @throws \Exception
[ "Authorize", "the", "B2", "account", "in", "order", "to", "get", "an", "auth", "token", "and", "API", "/", "download", "URLs", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L431-L444
gliterd/backblaze-b2
src/Client.php
Client.uploadLargeFile
public function uploadLargeFile(array $options) { if (substr($options['FileName'], 0, 1) === '/') { $options['FileName'] = ltrim($options['FileName'], '/'); } //if last char of path is not a "/" then add a "/" if (substr($options['FilePath'], -1) != '/') { $options['FilePath'] = $options['FilePath'].'/'; } if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } if (!isset($options['FileContentType'])) { $options['FileContentType'] = 'b2/x-auto'; } $this->authorizeAccount(); // 1) b2_start_large_file, (returns fileId) $start = $this->startLargeFile($options['FileName'], $options['FileContentType'], $options['BucketId']); // 2) b2_get_upload_part_url for each thread uploading (takes fileId) $url = $this->getUploadPartUrl($start['fileId']); // 3) b2_upload_part for each part of the file $parts = $this->uploadParts($options['FilePath'].$options['FileName'], $url['uploadUrl'], $url['authorizationToken']); $sha1s = []; foreach ($parts as $part) { $sha1s[] = $part['contentSha1']; } // 4) b2_finish_large_file. return $this->finishLargeFile($start['fileId'], $sha1s); }
php
public function uploadLargeFile(array $options) { if (substr($options['FileName'], 0, 1) === '/') { $options['FileName'] = ltrim($options['FileName'], '/'); } //if last char of path is not a "/" then add a "/" if (substr($options['FilePath'], -1) != '/') { $options['FilePath'] = $options['FilePath'].'/'; } if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } if (!isset($options['FileContentType'])) { $options['FileContentType'] = 'b2/x-auto'; } $this->authorizeAccount(); // 1) b2_start_large_file, (returns fileId) $start = $this->startLargeFile($options['FileName'], $options['FileContentType'], $options['BucketId']); // 2) b2_get_upload_part_url for each thread uploading (takes fileId) $url = $this->getUploadPartUrl($start['fileId']); // 3) b2_upload_part for each part of the file $parts = $this->uploadParts($options['FilePath'].$options['FileName'], $url['uploadUrl'], $url['authorizationToken']); $sha1s = []; foreach ($parts as $part) { $sha1s[] = $part['contentSha1']; } // 4) b2_finish_large_file. return $this->finishLargeFile($start['fileId'], $sha1s); }
[ "public", "function", "uploadLargeFile", "(", "array", "$", "options", ")", "{", "if", "(", "substr", "(", "$", "options", "[", "'FileName'", "]", ",", "0", ",", "1", ")", "===", "'/'", ")", "{", "$", "options", "[", "'FileName'", "]", "=", "ltrim", ...
Uploads a large file using b2 large file proceedure. @param array $options @throws \Exception @throws GuzzleException @return \BackblazeB2\File
[ "Uploads", "a", "large", "file", "using", "b2", "large", "file", "proceedure", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L510-L548
gliterd/backblaze-b2
src/Client.php
Client.startLargeFile
protected function startLargeFile($fileName, $contentType, $bucketId) { $response = $this->generateAuthenticatedClient([ 'fileName' => $fileName, 'contentType' => $contentType, 'bucketId' => $bucketId, ])->request('POST', '/b2_start_large_file'); return $response; }
php
protected function startLargeFile($fileName, $contentType, $bucketId) { $response = $this->generateAuthenticatedClient([ 'fileName' => $fileName, 'contentType' => $contentType, 'bucketId' => $bucketId, ])->request('POST', '/b2_start_large_file'); return $response; }
[ "protected", "function", "startLargeFile", "(", "$", "fileName", ",", "$", "contentType", ",", "$", "bucketId", ")", "{", "$", "response", "=", "$", "this", "->", "generateAuthenticatedClient", "(", "[", "'fileName'", "=>", "$", "fileName", ",", "'contentType'...
starts the large file upload process. @param $fileName @param $contentType @param $bucketId @throws GuzzleException @return array
[ "starts", "the", "large", "file", "upload", "process", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L561-L570
gliterd/backblaze-b2
src/Client.php
Client.uploadParts
protected function uploadParts($filePath, $uploadUrl, $largeFileAuthToken) { $return = []; $minimum_part_size = 100 * (1000 * 1000); $local_file_size = filesize($filePath); $total_bytes_sent = 0; $bytes_sent_for_part = $minimum_part_size; $sha1_of_parts = []; $part_no = 1; $file_handle = fopen($filePath, 'r'); while ($total_bytes_sent < $local_file_size) { // Determine the number of bytes to send based on the minimum part size if (($local_file_size - $total_bytes_sent) < $minimum_part_size) { $bytes_sent_for_part = ($local_file_size - $total_bytes_sent); } // Get a sha1 of the part we are going to send fseek($file_handle, $total_bytes_sent); $data_part = fread($file_handle, $bytes_sent_for_part); array_push($sha1_of_parts, sha1($data_part)); fseek($file_handle, $total_bytes_sent); $response = $this->client->request('POST', $uploadUrl, [ 'headers' => [ 'Authorization' => $largeFileAuthToken, 'Content-Length' => $bytes_sent_for_part, 'X-Bz-Part-Number' => $part_no, 'X-Bz-Content-Sha1' => $sha1_of_parts[$part_no - 1], ], 'body' => $data_part, ]); $return[] = $response; // Prepare for the next iteration of the loop $part_no++; $total_bytes_sent = $bytes_sent_for_part + $total_bytes_sent; } fclose($file_handle); return $return; }
php
protected function uploadParts($filePath, $uploadUrl, $largeFileAuthToken) { $return = []; $minimum_part_size = 100 * (1000 * 1000); $local_file_size = filesize($filePath); $total_bytes_sent = 0; $bytes_sent_for_part = $minimum_part_size; $sha1_of_parts = []; $part_no = 1; $file_handle = fopen($filePath, 'r'); while ($total_bytes_sent < $local_file_size) { // Determine the number of bytes to send based on the minimum part size if (($local_file_size - $total_bytes_sent) < $minimum_part_size) { $bytes_sent_for_part = ($local_file_size - $total_bytes_sent); } // Get a sha1 of the part we are going to send fseek($file_handle, $total_bytes_sent); $data_part = fread($file_handle, $bytes_sent_for_part); array_push($sha1_of_parts, sha1($data_part)); fseek($file_handle, $total_bytes_sent); $response = $this->client->request('POST', $uploadUrl, [ 'headers' => [ 'Authorization' => $largeFileAuthToken, 'Content-Length' => $bytes_sent_for_part, 'X-Bz-Part-Number' => $part_no, 'X-Bz-Content-Sha1' => $sha1_of_parts[$part_no - 1], ], 'body' => $data_part, ]); $return[] = $response; // Prepare for the next iteration of the loop $part_no++; $total_bytes_sent = $bytes_sent_for_part + $total_bytes_sent; } fclose($file_handle); return $return; }
[ "protected", "function", "uploadParts", "(", "$", "filePath", ",", "$", "uploadUrl", ",", "$", "largeFileAuthToken", ")", "{", "$", "return", "=", "[", "]", ";", "$", "minimum_part_size", "=", "100", "*", "(", "1000", "*", "1000", ")", ";", "$", "local...
uploads the file as "parts" of 100MB each. @param $filePath @param $uploadUrl @param $largeFileAuthToken @return array
[ "uploads", "the", "file", "as", "parts", "of", "100MB", "each", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L599-L645
gliterd/backblaze-b2
src/Client.php
Client.finishLargeFile
protected function finishLargeFile($fileId, array $sha1s) { $response = $this->generateAuthenticatedClient([ 'fileId' => $fileId, 'partSha1Array' => $sha1s, ])->request('POST', '/b2_finish_large_file'); return new File( $response['fileId'], $response['fileName'], $response['contentSha1'], $response['contentLength'], $response['contentType'], $response['fileInfo'], $response['bucketId'], $response['action'], $response['uploadTimestamp'] ); }
php
protected function finishLargeFile($fileId, array $sha1s) { $response = $this->generateAuthenticatedClient([ 'fileId' => $fileId, 'partSha1Array' => $sha1s, ])->request('POST', '/b2_finish_large_file'); return new File( $response['fileId'], $response['fileName'], $response['contentSha1'], $response['contentLength'], $response['contentType'], $response['fileInfo'], $response['bucketId'], $response['action'], $response['uploadTimestamp'] ); }
[ "protected", "function", "finishLargeFile", "(", "$", "fileId", ",", "array", "$", "sha1s", ")", "{", "$", "response", "=", "$", "this", "->", "generateAuthenticatedClient", "(", "[", "'fileId'", "=>", "$", "fileId", ",", "'partSha1Array'", "=>", "$", "sha1s...
finishes the large file upload proceedure. @param $fileId @param array $sha1s @throws GuzzleException @return File
[ "finishes", "the", "large", "file", "upload", "proceedure", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L657-L675
gliterd/backblaze-b2
src/Client.php
Client.generateAuthenticatedClient
protected function generateAuthenticatedClient($json = []) { $this->authorizeAccount(); $client = new \GuzzleHttp\Client([ 'base_uri' => $apiUrl, 'headers' => [ 'Authorization' => $this->authToken, ], 'json' => $json, ]); return $client; }
php
protected function generateAuthenticatedClient($json = []) { $this->authorizeAccount(); $client = new \GuzzleHttp\Client([ 'base_uri' => $apiUrl, 'headers' => [ 'Authorization' => $this->authToken, ], 'json' => $json, ]); return $client; }
[ "protected", "function", "generateAuthenticatedClient", "(", "$", "json", "=", "[", "]", ")", "{", "$", "this", "->", "authorizeAccount", "(", ")", ";", "$", "client", "=", "new", "\\", "GuzzleHttp", "\\", "Client", "(", "[", "'base_uri'", "=>", "$", "ap...
/* Generates Authenticated Guzzle Client
[ "/", "*", "Generates", "Authenticated", "Guzzle", "Client" ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Client.php#L680-L693
gliterd/backblaze-b2
src/Http/Client.php
Client.request
public function request($method, $uri = null, array $options = [], $asJson = true) { $response = parent::request($method, $uri, $options); if ($response->getStatusCode() !== 200) { ErrorHandler::handleErrorResponse($response); } if ($asJson) { return json_decode($response->getBody(), true); } return $response->getBody()->getContents(); }
php
public function request($method, $uri = null, array $options = [], $asJson = true) { $response = parent::request($method, $uri, $options); if ($response->getStatusCode() !== 200) { ErrorHandler::handleErrorResponse($response); } if ($asJson) { return json_decode($response->getBody(), true); } return $response->getBody()->getContents(); }
[ "public", "function", "request", "(", "$", "method", ",", "$", "uri", "=", "null", ",", "array", "$", "options", "=", "[", "]", ",", "$", "asJson", "=", "true", ")", "{", "$", "response", "=", "parent", "::", "request", "(", "$", "method", ",", "...
Sends a response to the B2 API, automatically handling decoding JSON and errors. @param string $method @param null $uri @param array $options @param bool $asJson @return mixed|string
[ "Sends", "a", "response", "to", "the", "B2", "API", "automatically", "handling", "decoding", "JSON", "and", "errors", "." ]
train
https://github.com/gliterd/backblaze-b2/blob/5d4cc9699ad06c0047836092961982548767af3c/src/Http/Client.php#L23-L36
10up/wpsnapshots
src/classes/Snapshot.php
Snapshot.get
public static function get( $id ) { if ( file_exists( Utils\get_snapshot_directory() . $id . '/meta.json' ) ) { $meta_file_contents = file_get_contents( Utils\get_snapshot_directory() . $id . '/meta.json' ); $meta = json_decode( $meta_file_contents, true ); } else { $meta = []; } /** * Backwards compant - need to fill in repo before we started saving repo in meta. */ if ( empty( $meta['repository'] ) ) { Log::instance()->write( 'Legacy snapshot found without repository. Assuming default repository.', 1, 'warning' ); $meta['repository'] = RepositoryManager::instance()->getDefault(); } return new self( $id, $meta['repository'], $meta ); }
php
public static function get( $id ) { if ( file_exists( Utils\get_snapshot_directory() . $id . '/meta.json' ) ) { $meta_file_contents = file_get_contents( Utils\get_snapshot_directory() . $id . '/meta.json' ); $meta = json_decode( $meta_file_contents, true ); } else { $meta = []; } /** * Backwards compant - need to fill in repo before we started saving repo in meta. */ if ( empty( $meta['repository'] ) ) { Log::instance()->write( 'Legacy snapshot found without repository. Assuming default repository.', 1, 'warning' ); $meta['repository'] = RepositoryManager::instance()->getDefault(); } return new self( $id, $meta['repository'], $meta ); }
[ "public", "static", "function", "get", "(", "$", "id", ")", "{", "if", "(", "file_exists", "(", "Utils", "\\", "get_snapshot_directory", "(", ")", ".", "$", "id", ".", "'/meta.json'", ")", ")", "{", "$", "meta_file_contents", "=", "file_get_contents", "(",...
Given an ID, create a WP Snapshots object @param string $id Snapshot ID @return Snapshot
[ "Given", "an", "ID", "create", "a", "WP", "Snapshots", "object" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Snapshot.php#L73-L91
10up/wpsnapshots
src/classes/Snapshot.php
Snapshot.create
public static function create( $args ) { $path = Utils\normalize_path( $args['path'] ); if ( ! Utils\is_wp_present( $path ) ) { Log::instance()->write( 'This is not a WordPress install. You can only create a snapshot from the root of a WordPress install.', 0, 'error' ); return; } /** * Define snapshot ID */ $id = Utils\generate_snapshot_id(); $create_dir = Utils\create_snapshot_directory( $id ); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directories.', 0, 'error' ); return false; } if ( ! Utils\is_wp_present( $path ) ) { Log::instance()->write( 'This is not a WordPress install.', 0, 'error' ); return false; } if ( ! Utils\locate_wp_config( $path ) ) { Log::instance()->write( 'No wp-config.php file present.', 0, 'error' ); return false; } $extra_config_constants = [ 'WP_CACHE' => false, ]; if ( ! empty( $args['db_host'] ) ) { $extra_config_constants['DB_HOST'] = $args['db_host']; } if ( ! empty( $args['db_name'] ) ) { $extra_config_constants['DB_NAME'] = $args['db_name']; } if ( ! empty( $args['db_user'] ) ) { $extra_config_constants['DB_USER'] = $args['db_user']; } if ( ! empty( $args['db_password'] ) ) { $extra_config_constants['DB_PASSWORD'] = $args['db_password']; } Log::instance()->write( 'Bootstrapping WordPress...', 1 ); if ( ! WordPressBridge::instance()->load( $path, $extra_config_constants ) ) { Log::instance()->write( 'Could not connect to WordPress database.', 0, 'error' ); return false; } global $wpdb; $meta = [ 'author' => [], 'repository' => $args['repository'], 'description' => $args['description'], 'project' => $args['project'], ]; $author_info = RepositoryManager::instance()->getAuthorInfo(); if ( ! empty( $author_info['name'] ) ) { $meta['author']['name'] = $author_info['name']; } if ( ! empty( $author_info['email'] ) ) { $meta['author']['email'] = $author_info['email']; } $meta['multisite'] = false; $meta['subdomain_install'] = false; $meta['domain_current_site'] = false; $meta['path_current_site'] = false; $meta['site_id_current_site'] = false; $meta['blog_id_current_site'] = false; $meta['sites'] = []; if ( is_multisite() ) { $meta['multisite'] = true; if ( defined( 'SUBDOMAIN_INSTALL' ) && SUBDOMAIN_INSTALL ) { $meta['subdomain_install'] = true; } if ( defined( 'DOMAIN_CURRENT_SITE' ) ) { $meta['domain_current_site'] = DOMAIN_CURRENT_SITE; } if ( defined( 'PATH_CURRENT_SITE' ) ) { $meta['path_current_site'] = PATH_CURRENT_SITE; } if ( defined( 'SITE_ID_CURRENT_SITE' ) ) { $meta['site_id_current_site'] = SITE_ID_CURRENT_SITE; } if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) { $meta['blog_id_current_site'] = BLOG_ID_CURRENT_SITE; } $sites = get_sites( [ 'number' => 500 ] ); foreach ( $sites as $site ) { $meta['sites'][] = [ 'blog_id' => $site->blog_id, 'domain' => $site->domain, 'path' => $site->path, 'site_url' => get_blog_option( $site->blog_id, 'siteurl' ), 'home_url' => get_blog_option( $site->blog_id, 'home' ), 'blogname' => get_blog_option( $site->blog_id, 'blogname' ), ]; } } else { $meta['sites'][] = [ 'site_url' => get_option( 'siteurl' ), 'home_url' => get_option( 'home' ), 'blogname' => get_option( 'blogname' ), ]; } $main_blog_id = ( defined( 'BLOG_ID_CURRENT_SITE' ) ) ? BLOG_ID_CURRENT_SITE : null; $meta['table_prefix'] = $wpdb->get_blog_prefix( $main_blog_id ); global $wp_version; $meta['wp_version'] = ( ! empty( $wp_version ) ) ? $wp_version : ''; /** * Dump sql to .wpsnapshots/data.sql */ $command = '/usr/bin/env mysqldump --no-defaults %s'; $command_esc_args = array( DB_NAME ); $command .= ' --tables'; /** * We only export tables with WP prefix */ Log::instance()->write( 'Getting WordPress tables...', 1 ); $tables = Utils\get_tables(); foreach ( $tables as $table ) { // We separate the users table for scrubbing if ( ! $args['no_scrub'] && $GLOBALS['table_prefix'] . 'users' === $table ) { continue; } $command .= ' %s'; $command_esc_args[] = trim( $table ); } $snapshot_path = Utils\get_snapshot_directory() . $id . '/'; $mysql_args = [ 'host' => DB_HOST, 'pass' => DB_PASSWORD, 'user' => DB_USER, 'result-file' => $snapshot_path . 'data.sql', ]; if ( defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) { $mysql_args['default-character-set'] = constant( 'DB_CHARSET' ); } $escaped_command = call_user_func_array( '\WPSnapshots\Utils\esc_cmd', array_merge( array( $command ), $command_esc_args ) ); Log::instance()->write( 'Exporting database...' ); Utils\run_mysql_command( $escaped_command, $mysql_args ); if ( ! $args['no_scrub'] ) { $command = '/usr/bin/env mysqldump --no-defaults %s'; $command_esc_args = array( DB_NAME ); $command .= ' --tables %s'; $command_esc_args[] = $GLOBALS['table_prefix'] . 'users'; $mysql_args = [ 'host' => DB_HOST, 'pass' => DB_PASSWORD, 'user' => DB_USER, 'result-file' => $snapshot_path . 'data-users.sql', ]; $escaped_command = call_user_func_array( '\WPSnapshots\Utils\esc_cmd', array_merge( array( $command ), $command_esc_args ) ); Log::instance()->write( 'Exporting users...', 1 ); Utils\run_mysql_command( $escaped_command, $mysql_args ); Log::instance()->write( 'Scrubbing user database...' ); $all_hashed_passwords = []; $all_emails = []; Log::instance()->write( 'Getting users...', 1 ); $user_rows = $wpdb->get_results( "SELECT user_pass, user_email FROM $wpdb->users", ARRAY_A ); foreach ( $user_rows as $user_row ) { $all_hashed_passwords[] = $user_row['user_pass']; if ( $user_row['user_email'] ) { $all_emails[] = $user_row['user_email']; } } $sterile_password = wp_hash_password( 'password' ); $sterile_email = 'user%d@example.com'; Log::instance()->write( 'Opening users export...', 1 ); $users_handle = @fopen( $snapshot_path . 'data-users.sql', 'r' ); $data_handle = @fopen( $snapshot_path . 'data.sql', 'a' ); if ( ! $users_handle || ! $data_handle ) { Log::instance()->write( 'Could not scrub users.', 0, 'error' ); return false; } $buffer = ''; $i = 0; Log::instance()->write( 'Writing scrubbed user data and merging exports...', 1 ); while ( ! feof( $users_handle ) ) { $chunk = fread( $users_handle, 4096 ); foreach ( $all_hashed_passwords as $password ) { $chunk = str_replace( "'$password'", "'$sterile_password'", $chunk ); } foreach ( $all_emails as $index => $email ) { $chunk = str_replace( "'$email'", sprintf( "'$sterile_email'", $index ), $chunk ); } $buffer .= $chunk; if ( 0 === $i % 10000 ) { fwrite( $data_handle, $buffer ); $buffer = ''; } $i++; } if ( ! empty( $buffer ) ) { fwrite( $data_handle, $buffer ); $buffer = ''; } fclose( $data_handle ); fclose( $users_handle ); Log::instance()->write( 'Removing old SQL...', 1 ); unlink( $snapshot_path . 'data-users.sql' ); } $verbose_pipe = ( empty( Log::instance()->getVerbosity() ) ) ? '> /dev/null' : ''; /** * Create file back up of wp-content in .wpsnapshots/files.tar.gz */ Log::instance()->write( 'Saving file back up...' ); $excludes = ''; if ( ! empty( $args['exclude'] ) ) { foreach ( $args['exclude'] as $exclude ) { $exclude = trim( $exclude ); if ( ! preg_match( '#^\./.*#', $exclude ) ) { $exclude = './' . $exclude; } Log::instance()->write( 'Excluding ' . $exclude, 1 ); $excludes .= ' --exclude="' . $exclude . '"'; } } Log::instance()->write( 'Compressing files...', 1 ); $v_flag = ( ! empty( Log::instance()->getVerbosity() ) ) ? 'v' : ''; $command = 'cd ' . escapeshellarg( WP_CONTENT_DIR ) . '/ && tar ' . $excludes . ' -zc' . $v_flag . 'f ' . Utils\escape_shell_path( $snapshot_path ) . 'files.tar.gz . ' . $verbose_pipe; Log::instance()->write( $command, 2 ); exec( $command ); Log::instance()->write( 'Compressing database backup...', 1 ); exec( 'gzip -9 ' . Utils\escape_shell_path( $snapshot_path ) . 'data.sql ' . $verbose_pipe ); $meta['size'] = filesize( $snapshot_path . 'data.sql.gz' ) + filesize( $snapshot_path . 'files.tar.gz' ); /** * Finally save snapshot meta to meta.json */ $meta_handle = @fopen( $snapshot_path . 'meta.json', 'x' ); // Create file and fail if it exists. if ( ! $meta_handle ) { Log::instance()->write( 'Could not create .wpsnapshots/SNAPSHOT_ID/meta.json.', 0, 'error' ); return false; } fwrite( $meta_handle, json_encode( $meta, JSON_PRETTY_PRINT ) ); $snapshot = new self( $id, $args['repository'], $meta ); return $snapshot; }
php
public static function create( $args ) { $path = Utils\normalize_path( $args['path'] ); if ( ! Utils\is_wp_present( $path ) ) { Log::instance()->write( 'This is not a WordPress install. You can only create a snapshot from the root of a WordPress install.', 0, 'error' ); return; } /** * Define snapshot ID */ $id = Utils\generate_snapshot_id(); $create_dir = Utils\create_snapshot_directory( $id ); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directories.', 0, 'error' ); return false; } if ( ! Utils\is_wp_present( $path ) ) { Log::instance()->write( 'This is not a WordPress install.', 0, 'error' ); return false; } if ( ! Utils\locate_wp_config( $path ) ) { Log::instance()->write( 'No wp-config.php file present.', 0, 'error' ); return false; } $extra_config_constants = [ 'WP_CACHE' => false, ]; if ( ! empty( $args['db_host'] ) ) { $extra_config_constants['DB_HOST'] = $args['db_host']; } if ( ! empty( $args['db_name'] ) ) { $extra_config_constants['DB_NAME'] = $args['db_name']; } if ( ! empty( $args['db_user'] ) ) { $extra_config_constants['DB_USER'] = $args['db_user']; } if ( ! empty( $args['db_password'] ) ) { $extra_config_constants['DB_PASSWORD'] = $args['db_password']; } Log::instance()->write( 'Bootstrapping WordPress...', 1 ); if ( ! WordPressBridge::instance()->load( $path, $extra_config_constants ) ) { Log::instance()->write( 'Could not connect to WordPress database.', 0, 'error' ); return false; } global $wpdb; $meta = [ 'author' => [], 'repository' => $args['repository'], 'description' => $args['description'], 'project' => $args['project'], ]; $author_info = RepositoryManager::instance()->getAuthorInfo(); if ( ! empty( $author_info['name'] ) ) { $meta['author']['name'] = $author_info['name']; } if ( ! empty( $author_info['email'] ) ) { $meta['author']['email'] = $author_info['email']; } $meta['multisite'] = false; $meta['subdomain_install'] = false; $meta['domain_current_site'] = false; $meta['path_current_site'] = false; $meta['site_id_current_site'] = false; $meta['blog_id_current_site'] = false; $meta['sites'] = []; if ( is_multisite() ) { $meta['multisite'] = true; if ( defined( 'SUBDOMAIN_INSTALL' ) && SUBDOMAIN_INSTALL ) { $meta['subdomain_install'] = true; } if ( defined( 'DOMAIN_CURRENT_SITE' ) ) { $meta['domain_current_site'] = DOMAIN_CURRENT_SITE; } if ( defined( 'PATH_CURRENT_SITE' ) ) { $meta['path_current_site'] = PATH_CURRENT_SITE; } if ( defined( 'SITE_ID_CURRENT_SITE' ) ) { $meta['site_id_current_site'] = SITE_ID_CURRENT_SITE; } if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) { $meta['blog_id_current_site'] = BLOG_ID_CURRENT_SITE; } $sites = get_sites( [ 'number' => 500 ] ); foreach ( $sites as $site ) { $meta['sites'][] = [ 'blog_id' => $site->blog_id, 'domain' => $site->domain, 'path' => $site->path, 'site_url' => get_blog_option( $site->blog_id, 'siteurl' ), 'home_url' => get_blog_option( $site->blog_id, 'home' ), 'blogname' => get_blog_option( $site->blog_id, 'blogname' ), ]; } } else { $meta['sites'][] = [ 'site_url' => get_option( 'siteurl' ), 'home_url' => get_option( 'home' ), 'blogname' => get_option( 'blogname' ), ]; } $main_blog_id = ( defined( 'BLOG_ID_CURRENT_SITE' ) ) ? BLOG_ID_CURRENT_SITE : null; $meta['table_prefix'] = $wpdb->get_blog_prefix( $main_blog_id ); global $wp_version; $meta['wp_version'] = ( ! empty( $wp_version ) ) ? $wp_version : ''; /** * Dump sql to .wpsnapshots/data.sql */ $command = '/usr/bin/env mysqldump --no-defaults %s'; $command_esc_args = array( DB_NAME ); $command .= ' --tables'; /** * We only export tables with WP prefix */ Log::instance()->write( 'Getting WordPress tables...', 1 ); $tables = Utils\get_tables(); foreach ( $tables as $table ) { // We separate the users table for scrubbing if ( ! $args['no_scrub'] && $GLOBALS['table_prefix'] . 'users' === $table ) { continue; } $command .= ' %s'; $command_esc_args[] = trim( $table ); } $snapshot_path = Utils\get_snapshot_directory() . $id . '/'; $mysql_args = [ 'host' => DB_HOST, 'pass' => DB_PASSWORD, 'user' => DB_USER, 'result-file' => $snapshot_path . 'data.sql', ]; if ( defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) { $mysql_args['default-character-set'] = constant( 'DB_CHARSET' ); } $escaped_command = call_user_func_array( '\WPSnapshots\Utils\esc_cmd', array_merge( array( $command ), $command_esc_args ) ); Log::instance()->write( 'Exporting database...' ); Utils\run_mysql_command( $escaped_command, $mysql_args ); if ( ! $args['no_scrub'] ) { $command = '/usr/bin/env mysqldump --no-defaults %s'; $command_esc_args = array( DB_NAME ); $command .= ' --tables %s'; $command_esc_args[] = $GLOBALS['table_prefix'] . 'users'; $mysql_args = [ 'host' => DB_HOST, 'pass' => DB_PASSWORD, 'user' => DB_USER, 'result-file' => $snapshot_path . 'data-users.sql', ]; $escaped_command = call_user_func_array( '\WPSnapshots\Utils\esc_cmd', array_merge( array( $command ), $command_esc_args ) ); Log::instance()->write( 'Exporting users...', 1 ); Utils\run_mysql_command( $escaped_command, $mysql_args ); Log::instance()->write( 'Scrubbing user database...' ); $all_hashed_passwords = []; $all_emails = []; Log::instance()->write( 'Getting users...', 1 ); $user_rows = $wpdb->get_results( "SELECT user_pass, user_email FROM $wpdb->users", ARRAY_A ); foreach ( $user_rows as $user_row ) { $all_hashed_passwords[] = $user_row['user_pass']; if ( $user_row['user_email'] ) { $all_emails[] = $user_row['user_email']; } } $sterile_password = wp_hash_password( 'password' ); $sterile_email = 'user%d@example.com'; Log::instance()->write( 'Opening users export...', 1 ); $users_handle = @fopen( $snapshot_path . 'data-users.sql', 'r' ); $data_handle = @fopen( $snapshot_path . 'data.sql', 'a' ); if ( ! $users_handle || ! $data_handle ) { Log::instance()->write( 'Could not scrub users.', 0, 'error' ); return false; } $buffer = ''; $i = 0; Log::instance()->write( 'Writing scrubbed user data and merging exports...', 1 ); while ( ! feof( $users_handle ) ) { $chunk = fread( $users_handle, 4096 ); foreach ( $all_hashed_passwords as $password ) { $chunk = str_replace( "'$password'", "'$sterile_password'", $chunk ); } foreach ( $all_emails as $index => $email ) { $chunk = str_replace( "'$email'", sprintf( "'$sterile_email'", $index ), $chunk ); } $buffer .= $chunk; if ( 0 === $i % 10000 ) { fwrite( $data_handle, $buffer ); $buffer = ''; } $i++; } if ( ! empty( $buffer ) ) { fwrite( $data_handle, $buffer ); $buffer = ''; } fclose( $data_handle ); fclose( $users_handle ); Log::instance()->write( 'Removing old SQL...', 1 ); unlink( $snapshot_path . 'data-users.sql' ); } $verbose_pipe = ( empty( Log::instance()->getVerbosity() ) ) ? '> /dev/null' : ''; /** * Create file back up of wp-content in .wpsnapshots/files.tar.gz */ Log::instance()->write( 'Saving file back up...' ); $excludes = ''; if ( ! empty( $args['exclude'] ) ) { foreach ( $args['exclude'] as $exclude ) { $exclude = trim( $exclude ); if ( ! preg_match( '#^\./.*#', $exclude ) ) { $exclude = './' . $exclude; } Log::instance()->write( 'Excluding ' . $exclude, 1 ); $excludes .= ' --exclude="' . $exclude . '"'; } } Log::instance()->write( 'Compressing files...', 1 ); $v_flag = ( ! empty( Log::instance()->getVerbosity() ) ) ? 'v' : ''; $command = 'cd ' . escapeshellarg( WP_CONTENT_DIR ) . '/ && tar ' . $excludes . ' -zc' . $v_flag . 'f ' . Utils\escape_shell_path( $snapshot_path ) . 'files.tar.gz . ' . $verbose_pipe; Log::instance()->write( $command, 2 ); exec( $command ); Log::instance()->write( 'Compressing database backup...', 1 ); exec( 'gzip -9 ' . Utils\escape_shell_path( $snapshot_path ) . 'data.sql ' . $verbose_pipe ); $meta['size'] = filesize( $snapshot_path . 'data.sql.gz' ) + filesize( $snapshot_path . 'files.tar.gz' ); /** * Finally save snapshot meta to meta.json */ $meta_handle = @fopen( $snapshot_path . 'meta.json', 'x' ); // Create file and fail if it exists. if ( ! $meta_handle ) { Log::instance()->write( 'Could not create .wpsnapshots/SNAPSHOT_ID/meta.json.', 0, 'error' ); return false; } fwrite( $meta_handle, json_encode( $meta, JSON_PRETTY_PRINT ) ); $snapshot = new self( $id, $args['repository'], $meta ); return $snapshot; }
[ "public", "static", "function", "create", "(", "$", "args", ")", "{", "$", "path", "=", "Utils", "\\", "normalize_path", "(", "$", "args", "[", "'path'", "]", ")", ";", "if", "(", "!", "Utils", "\\", "is_wp_present", "(", "$", "path", ")", ")", "{"...
Create a snapshot. @param array $args List of arguments @return bool|Snapshot
[ "Create", "a", "snapshot", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Snapshot.php#L99-L426
10up/wpsnapshots
src/classes/Snapshot.php
Snapshot.download
public static function download( $id, $repository_name ) { if ( Utils\is_snapshot_cached( $id ) ) { Log::instance()->write( 'Snapshot found in cache.' ); return self::get( $id ); } $create_dir = Utils\create_snapshot_directory( $id ); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directories.', 0, 'error' ); return false; } $repository = RepositoryManager::instance()->setup( $repository_name ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return false; } Log::instance()->write( 'Getting snapshot information...' ); $snapshot = $repository->getDB()->getSnapshot( $id ); if ( ! $snapshot ) { Log::instance()->write( 'Could not get snapshot from database.', 0, 'error' ); return false; } if ( empty( $snapshot ) || empty( $snapshot['project'] ) ) { Log::instance()->write( 'Missing critical snapshot data.', 0, 'error' ); return false; } /** * Backwards compant. Add repository to meta before we started saving it. */ if ( empty( $snapshot['repository'] ) ) { $snapshot['repository'] = $repository_name; } Log::instance()->write( 'Downloading snapshot files and database (' . Utils\format_bytes( $snapshot['size'] ) . ')...' ); $snapshot_path = Utils\get_snapshot_directory() . $id . '/'; $download = $repository->getS3()->downloadSnapshot( $id, $snapshot['project'], $snapshot_path . 'data.sql.gz', $snapshot_path . 'files.tar.gz' ); if ( ! $download ) { Log::instance()->write( 'Failed to download snapshot.', 0, 'error' ); return false; } /** * Finally save snapshot meta to meta.json */ $meta_handle = @fopen( $snapshot_path . 'meta.json', 'x' ); // Create file and fail if it exists. if ( ! $meta_handle ) { Log::instance()->write( 'Could not create meta.json.', 0, 'error' ); return false; } fwrite( $meta_handle, json_encode( $snapshot, JSON_PRETTY_PRINT ) ); return new self( $id, $repository_name, $snapshot, true ); }
php
public static function download( $id, $repository_name ) { if ( Utils\is_snapshot_cached( $id ) ) { Log::instance()->write( 'Snapshot found in cache.' ); return self::get( $id ); } $create_dir = Utils\create_snapshot_directory( $id ); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directories.', 0, 'error' ); return false; } $repository = RepositoryManager::instance()->setup( $repository_name ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return false; } Log::instance()->write( 'Getting snapshot information...' ); $snapshot = $repository->getDB()->getSnapshot( $id ); if ( ! $snapshot ) { Log::instance()->write( 'Could not get snapshot from database.', 0, 'error' ); return false; } if ( empty( $snapshot ) || empty( $snapshot['project'] ) ) { Log::instance()->write( 'Missing critical snapshot data.', 0, 'error' ); return false; } /** * Backwards compant. Add repository to meta before we started saving it. */ if ( empty( $snapshot['repository'] ) ) { $snapshot['repository'] = $repository_name; } Log::instance()->write( 'Downloading snapshot files and database (' . Utils\format_bytes( $snapshot['size'] ) . ')...' ); $snapshot_path = Utils\get_snapshot_directory() . $id . '/'; $download = $repository->getS3()->downloadSnapshot( $id, $snapshot['project'], $snapshot_path . 'data.sql.gz', $snapshot_path . 'files.tar.gz' ); if ( ! $download ) { Log::instance()->write( 'Failed to download snapshot.', 0, 'error' ); return false; } /** * Finally save snapshot meta to meta.json */ $meta_handle = @fopen( $snapshot_path . 'meta.json', 'x' ); // Create file and fail if it exists. if ( ! $meta_handle ) { Log::instance()->write( 'Could not create meta.json.', 0, 'error' ); return false; } fwrite( $meta_handle, json_encode( $snapshot, JSON_PRETTY_PRINT ) ); return new self( $id, $repository_name, $snapshot, true ); }
[ "public", "static", "function", "download", "(", "$", "id", ",", "$", "repository_name", ")", "{", "if", "(", "Utils", "\\", "is_snapshot_cached", "(", "$", "id", ")", ")", "{", "Log", "::", "instance", "(", ")", "->", "write", "(", "'Snapshot found in c...
Download snapshot. @param string $id Snapshot id @param string $repository_name Name of repo @return bool|Snapshot
[ "Download", "snapshot", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Snapshot.php#L435-L506
10up/wpsnapshots
src/classes/Snapshot.php
Snapshot.push
public function push() { if ( $this->remote ) { Log::instance()->write( 'Snapshot already pushed.', 0, 'error' ); return false; } $repository = RepositoryManager::instance()->setup( $this->repository_name ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return false; } /** * Put files to S3 */ Log::instance()->write( 'Uploading files (' . Utils\format_bytes( $this->meta['size'] ) . ')...' ); $s3_add = $repository->getS3()->putSnapshot( $this->id, $this->meta['project'], Utils\get_snapshot_directory() . $this->id . '/data.sql.gz', Utils\get_snapshot_directory() . $this->id . '/files.tar.gz' ); if ( ! $s3_add ) { Log::instance()->write( 'Could not upload files to S3.', 0, 'error' ); return false; } /** * Add snapshot to DB */ Log::instance()->write( 'Adding snapshot to database...' ); $inserted_snapshot = $repository->getDB()->insertSnapshot( $this->id, $this->meta ); if ( ! $inserted_snapshot ) { Log::instance()->write( 'Could not add snapshot to database.', 0, 'error' ); return false; } $this->remote = true; return true; }
php
public function push() { if ( $this->remote ) { Log::instance()->write( 'Snapshot already pushed.', 0, 'error' ); return false; } $repository = RepositoryManager::instance()->setup( $this->repository_name ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return false; } /** * Put files to S3 */ Log::instance()->write( 'Uploading files (' . Utils\format_bytes( $this->meta['size'] ) . ')...' ); $s3_add = $repository->getS3()->putSnapshot( $this->id, $this->meta['project'], Utils\get_snapshot_directory() . $this->id . '/data.sql.gz', Utils\get_snapshot_directory() . $this->id . '/files.tar.gz' ); if ( ! $s3_add ) { Log::instance()->write( 'Could not upload files to S3.', 0, 'error' ); return false; } /** * Add snapshot to DB */ Log::instance()->write( 'Adding snapshot to database...' ); $inserted_snapshot = $repository->getDB()->insertSnapshot( $this->id, $this->meta ); if ( ! $inserted_snapshot ) { Log::instance()->write( 'Could not add snapshot to database.', 0, 'error' ); return false; } $this->remote = true; return true; }
[ "public", "function", "push", "(", ")", "{", "if", "(", "$", "this", "->", "remote", ")", "{", "Log", "::", "instance", "(", ")", "->", "write", "(", "'Snapshot already pushed.'", ",", "0", ",", "'error'", ")", ";", "return", "false", ";", "}", "$", ...
Push snapshot to repository @return boolean
[ "Push", "snapshot", "to", "repository" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Snapshot.php#L513-L556
10up/wpsnapshots
src/classes/SearchReplace.php
SearchReplace.get_columns
private function get_columns( $table ) { global $wpdb; $table_sql = $this->esc_sql_ident( $table ); $primary_keys = $text_columns = $all_columns = array(); foreach ( $wpdb->get_results( "DESCRIBE $table_sql" ) as $col ) { if ( 'PRI' === $col->Key ) { $primary_keys[] = $col->Field; } if ( $this->is_text_col( $col->Type ) ) { $text_columns[] = $col->Field; } $all_columns[] = $col->Field; } return array( $primary_keys, $text_columns, $all_columns ); }
php
private function get_columns( $table ) { global $wpdb; $table_sql = $this->esc_sql_ident( $table ); $primary_keys = $text_columns = $all_columns = array(); foreach ( $wpdb->get_results( "DESCRIBE $table_sql" ) as $col ) { if ( 'PRI' === $col->Key ) { $primary_keys[] = $col->Field; } if ( $this->is_text_col( $col->Type ) ) { $text_columns[] = $col->Field; } $all_columns[] = $col->Field; } return array( $primary_keys, $text_columns, $all_columns ); }
[ "private", "function", "get_columns", "(", "$", "table", ")", "{", "global", "$", "wpdb", ";", "$", "table_sql", "=", "$", "this", "->", "esc_sql_ident", "(", "$", "table", ")", ";", "$", "primary_keys", "=", "$", "text_columns", "=", "$", "all_columns",...
Get columns for a table organizing by text/primary. @param string $table Table name @return array
[ "Get", "columns", "for", "a", "table", "organizing", "by", "text", "/", "primary", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/SearchReplace.php#L92-L111
10up/wpsnapshots
src/classes/SearchReplace.php
SearchReplace.is_text_col
private function is_text_col( $type ) { foreach ( array( 'text', 'varchar' ) as $token ) { if ( false !== strpos( $type, $token ) ) { return true; } } return false; }
php
private function is_text_col( $type ) { foreach ( array( 'text', 'varchar' ) as $token ) { if ( false !== strpos( $type, $token ) ) { return true; } } return false; }
[ "private", "function", "is_text_col", "(", "$", "type", ")", "{", "foreach", "(", "array", "(", "'text'", ",", "'varchar'", ")", "as", "$", "token", ")", "{", "if", "(", "false", "!==", "strpos", "(", "$", "type", ",", "$", "token", ")", ")", "{", ...
Check if column type is text @param string $type Column type @return boolean
[ "Check", "if", "column", "type", "is", "text" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/SearchReplace.php#L119-L127
10up/wpsnapshots
src/classes/SearchReplace.php
SearchReplace.sql_handle_col
private function sql_handle_col( $col, $table ) { global $wpdb; $table_sql = $this->esc_sql_ident( $table ); $col_sql = $this->esc_sql_ident( $col ); $count = $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE($col_sql, %s, %s);", $this->old, $this->new ) ); return $count; }
php
private function sql_handle_col( $col, $table ) { global $wpdb; $table_sql = $this->esc_sql_ident( $table ); $col_sql = $this->esc_sql_ident( $col ); $count = $wpdb->query( $wpdb->prepare( "UPDATE $table_sql SET $col_sql = REPLACE($col_sql, %s, %s);", $this->old, $this->new ) ); return $count; }
[ "private", "function", "sql_handle_col", "(", "$", "col", ",", "$", "table", ")", "{", "global", "$", "wpdb", ";", "$", "table_sql", "=", "$", "this", "->", "esc_sql_ident", "(", "$", "table", ")", ";", "$", "col_sql", "=", "$", "this", "->", "esc_sq...
Handle search/replace with only SQL. This won't work for serialized data. Returns number of updates made. @param string $col Column name @param string $table Table name @return int
[ "Handle", "search", "/", "replace", "with", "only", "SQL", ".", "This", "won", "t", "work", "for", "serialized", "data", ".", "Returns", "number", "of", "updates", "made", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/SearchReplace.php#L156-L165
10up/wpsnapshots
src/classes/SearchReplace.php
SearchReplace.php_handle_col
private function php_handle_col( $col, $primary_keys, $table ) { global $wpdb; $count = 0; $table_sql = $this->esc_sql_ident( $table ); $col_sql = $this->esc_sql_ident( $col ); $where = " WHERE $col_sql" . $wpdb->prepare( ' LIKE %s', '%' . $wpdb->esc_like( $this->old ) . '%' ); $primary_keys_sql = implode( ',', $this->esc_sql_ident( $primary_keys ) ); $rows = $wpdb->get_results( "SELECT {$primary_keys_sql} FROM {$table_sql} {$where}" ); foreach ( $rows as $keys ) { $where_sql = ''; foreach ( (array) $keys as $k => $v ) { if ( strlen( $where_sql ) ) { $where_sql .= ' AND '; } $where_sql .= $this->esc_sql_ident( $k ) . ' = ' . esc_sql( $v ); } $col_value = $wpdb->get_var( "SELECT {$col_sql} FROM {$table_sql} WHERE {$where_sql}" ); if ( '' === $col_value ) { continue; } $value = $this->php_search_replace( $col_value, false ); if ( $value === $col_value ) { continue; } $where = array(); foreach ( (array) $keys as $k => $v ) { $where[ $k ] = $v; } $count += $wpdb->update( $table, array( $col => $value ), $where ); } return $count; }
php
private function php_handle_col( $col, $primary_keys, $table ) { global $wpdb; $count = 0; $table_sql = $this->esc_sql_ident( $table ); $col_sql = $this->esc_sql_ident( $col ); $where = " WHERE $col_sql" . $wpdb->prepare( ' LIKE %s', '%' . $wpdb->esc_like( $this->old ) . '%' ); $primary_keys_sql = implode( ',', $this->esc_sql_ident( $primary_keys ) ); $rows = $wpdb->get_results( "SELECT {$primary_keys_sql} FROM {$table_sql} {$where}" ); foreach ( $rows as $keys ) { $where_sql = ''; foreach ( (array) $keys as $k => $v ) { if ( strlen( $where_sql ) ) { $where_sql .= ' AND '; } $where_sql .= $this->esc_sql_ident( $k ) . ' = ' . esc_sql( $v ); } $col_value = $wpdb->get_var( "SELECT {$col_sql} FROM {$table_sql} WHERE {$where_sql}" ); if ( '' === $col_value ) { continue; } $value = $this->php_search_replace( $col_value, false ); if ( $value === $col_value ) { continue; } $where = array(); foreach ( (array) $keys as $k => $v ) { $where[ $k ] = $v; } $count += $wpdb->update( $table, array( $col => $value ), $where ); } return $count; }
[ "private", "function", "php_handle_col", "(", "$", "col", ",", "$", "primary_keys", ",", "$", "table", ")", "{", "global", "$", "wpdb", ";", "$", "count", "=", "0", ";", "$", "table_sql", "=", "$", "this", "->", "esc_sql_ident", "(", "$", "table", ")...
Use PHP to run search and replace on a column. This is mostly used for serialized data. Returns number of updates made @param string $col Column name @param array $primary_keys Array of keys @param string $table Table name @return int
[ "Use", "PHP", "to", "run", "search", "and", "replace", "on", "a", "column", ".", "This", "is", "mostly", "used", "for", "serialized", "data", ".", "Returns", "number", "of", "updates", "made" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/SearchReplace.php#L176-L221
10up/wpsnapshots
src/classes/SearchReplace.php
SearchReplace.php_search_replace
private function php_search_replace( $data, $serialised, $recursion_level = 0, $visited_data = array() ) { // some unseriliased data cannot be re-serialised eg. SimpleXMLElements try { // If we've reached the maximum recursion level, short circuit if ( $this->max_recursion !== 0 && $recursion_level >= $this->max_recursion ) { // @codingStandardsIgnoreLine return $data; } if ( is_array( $data ) || is_object( $data ) ) { // If we've seen this exact object or array before, short circuit if ( in_array( $data, $visited_data, true ) ) { return $data; // Avoid infinite loops when there's a cycle } // Add this data to the list of $visited_data[] = $data; } if ( is_string( $data ) && ( $unserialized = @unserialize( $data ) ) !== false ) { $data = $this->php_search_replace( $unserialized, true, $recursion_level + 1 ); } elseif ( is_array( $data ) ) { $keys = array_keys( $data ); foreach ( $keys as $key ) { $data[ $key ] = $this->php_search_replace( $data[ $key ], false, $recursion_level + 1, $visited_data ); } } elseif ( is_object( $data ) ) { foreach ( $data as $key => $value ) { $data->$key = $this->php_search_replace( $value, false, $recursion_level + 1, $visited_data ); } } elseif ( is_string( $data ) ) { $data = str_replace( $this->old, $this->new, $data ); } if ( $serialised ) { return serialize( $data ); } } catch ( Exception $error ) { // Do nothing } return $data; }
php
private function php_search_replace( $data, $serialised, $recursion_level = 0, $visited_data = array() ) { // some unseriliased data cannot be re-serialised eg. SimpleXMLElements try { // If we've reached the maximum recursion level, short circuit if ( $this->max_recursion !== 0 && $recursion_level >= $this->max_recursion ) { // @codingStandardsIgnoreLine return $data; } if ( is_array( $data ) || is_object( $data ) ) { // If we've seen this exact object or array before, short circuit if ( in_array( $data, $visited_data, true ) ) { return $data; // Avoid infinite loops when there's a cycle } // Add this data to the list of $visited_data[] = $data; } if ( is_string( $data ) && ( $unserialized = @unserialize( $data ) ) !== false ) { $data = $this->php_search_replace( $unserialized, true, $recursion_level + 1 ); } elseif ( is_array( $data ) ) { $keys = array_keys( $data ); foreach ( $keys as $key ) { $data[ $key ] = $this->php_search_replace( $data[ $key ], false, $recursion_level + 1, $visited_data ); } } elseif ( is_object( $data ) ) { foreach ( $data as $key => $value ) { $data->$key = $this->php_search_replace( $value, false, $recursion_level + 1, $visited_data ); } } elseif ( is_string( $data ) ) { $data = str_replace( $this->old, $this->new, $data ); } if ( $serialised ) { return serialize( $data ); } } catch ( Exception $error ) { // Do nothing } return $data; }
[ "private", "function", "php_search_replace", "(", "$", "data", ",", "$", "serialised", ",", "$", "recursion_level", "=", "0", ",", "$", "visited_data", "=", "array", "(", ")", ")", "{", "// some unseriliased data cannot be re-serialised eg. SimpleXMLElements", "try", ...
Perform php search and replace on data. Returns updated data @param string|object|array $data Data to search @param bool $serialised Serialized data or not @param integer $recursion_level Recursion level @param array $visited_data Array of visited data @return string|object|array
[ "Perform", "php", "search", "and", "replace", "on", "data", ".", "Returns", "updated", "data" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/SearchReplace.php#L232-L270
10up/wpsnapshots
src/classes/Command/CreateRepository.php
CreateRepository.execute
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getArgument( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Repository not configured. Before creating the repository, you must configure. Run `wpsnapshots configure ' . $repository . '`', 0, 'error' ); return 1; } $create_s3 = $repository->getS3()->createBucket(); $s3_setup = true; if ( true !== $create_s3 ) { if ( 'BucketExists' === $create_s3 || 'BucketAlreadyOwnedByYou' === $create_s3 || 'BucketAlreadyExists' === $create_s3 ) { Log::instance()->write( 'S3 already setup.', 0, 'warning' ); } else { Log::instance()->write( 'Could not create S3 bucket.', 0, 'error' ); $s3_setup = false; } } $create_db = $repository->getDB()->createTables(); $db_setup = true; if ( true !== $create_db ) { if ( 'ResourceInUseException' === $create_db ) { Log::instance()->write( 'DynamoDB table already setup.', 0, 'warning' ); } else { Log::instance()->write( 'Could not create DynamoDB table.', 0, 'error' ); $db_setup = false; } } if ( ! $db_setup || ! $s3_setup ) { Log::instance()->write( 'Repository could not be created.', 0, 'error' ); return 1; } else { Log::instance()->write( 'Repository setup!', 0, 'success' ); } }
php
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getArgument( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Repository not configured. Before creating the repository, you must configure. Run `wpsnapshots configure ' . $repository . '`', 0, 'error' ); return 1; } $create_s3 = $repository->getS3()->createBucket(); $s3_setup = true; if ( true !== $create_s3 ) { if ( 'BucketExists' === $create_s3 || 'BucketAlreadyOwnedByYou' === $create_s3 || 'BucketAlreadyExists' === $create_s3 ) { Log::instance()->write( 'S3 already setup.', 0, 'warning' ); } else { Log::instance()->write( 'Could not create S3 bucket.', 0, 'error' ); $s3_setup = false; } } $create_db = $repository->getDB()->createTables(); $db_setup = true; if ( true !== $create_db ) { if ( 'ResourceInUseException' === $create_db ) { Log::instance()->write( 'DynamoDB table already setup.', 0, 'warning' ); } else { Log::instance()->write( 'Could not create DynamoDB table.', 0, 'error' ); $db_setup = false; } } if ( ! $db_setup || ! $s3_setup ) { Log::instance()->write( 'Repository could not be created.', 0, 'error' ); return 1; } else { Log::instance()->write( 'Repository setup!', 0, 'success' ); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "Log", "::", "instance", "(", ")", "->", "setOutput", "(", "$", "output", ")", ";", "$", "repository", "=", "RepositoryManager", "::", ...
Executes the command @param InputInterface $input Command input @param OutputInterface $output Command output
[ "Executes", "the", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/CreateRepository.php#L42-L86
10up/wpsnapshots
src/classes/Config.php
Config.get
public static function get() { Log::instance()->write( 'Reading configuration from file.', 1 ); $file_path = Utils\get_snapshot_directory() . 'config.json'; if ( ! file_exists( $file_path ) ) { /** * Backwards compat for old config file path */ $file_path = $_SERVER['HOME'] . '/.wpsnapshots.json'; if ( ! file_exists( $file_path ) ) { Log::instance()->write( 'No config found.', 1 ); $config = new self(); $config->write(); return $config; } else { rename( $file_path, Utils\get_snapshot_directory() . 'config.json' ); $file_path = Utils\get_snapshot_directory() . 'config.json'; } } $config = json_decode( file_get_contents( $file_path ), true ); return new self( $config ); }
php
public static function get() { Log::instance()->write( 'Reading configuration from file.', 1 ); $file_path = Utils\get_snapshot_directory() . 'config.json'; if ( ! file_exists( $file_path ) ) { /** * Backwards compat for old config file path */ $file_path = $_SERVER['HOME'] . '/.wpsnapshots.json'; if ( ! file_exists( $file_path ) ) { Log::instance()->write( 'No config found.', 1 ); $config = new self(); $config->write(); return $config; } else { rename( $file_path, Utils\get_snapshot_directory() . 'config.json' ); $file_path = Utils\get_snapshot_directory() . 'config.json'; } } $config = json_decode( file_get_contents( $file_path ), true ); return new self( $config ); }
[ "public", "static", "function", "get", "(", ")", "{", "Log", "::", "instance", "(", ")", "->", "write", "(", "'Reading configuration from file.'", ",", "1", ")", ";", "$", "file_path", "=", "Utils", "\\", "get_snapshot_directory", "(", ")", ".", "'config.jso...
Create config from file @return Config|bool
[ "Create", "config", "from", "file" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Config.php#L46-L74
10up/wpsnapshots
src/classes/Config.php
Config.write
public function write() { Log::instance()->write( 'Writing config.', 1 ); $create_dir = Utils\create_snapshot_directory(); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directory.', 0, 'error' ); return false; } file_put_contents( Utils\get_snapshot_directory() . 'config.json', json_encode( $this->config, JSON_PRETTY_PRINT ) ); }
php
public function write() { Log::instance()->write( 'Writing config.', 1 ); $create_dir = Utils\create_snapshot_directory(); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directory.', 0, 'error' ); return false; } file_put_contents( Utils\get_snapshot_directory() . 'config.json', json_encode( $this->config, JSON_PRETTY_PRINT ) ); }
[ "public", "function", "write", "(", ")", "{", "Log", "::", "instance", "(", ")", "->", "write", "(", "'Writing config.'", ",", "1", ")", ";", "$", "create_dir", "=", "Utils", "\\", "create_snapshot_directory", "(", ")", ";", "if", "(", "!", "$", "creat...
Write config to current config file
[ "Write", "config", "to", "current", "config", "file" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Config.php#L79-L91
10up/wpsnapshots
src/classes/Config.php
Config.offsetGet
public function offsetGet( $offset ) { return isset( $this->config[ $offset ] ) ? $this->config[ $offset ] : null; }
php
public function offsetGet( $offset ) { return isset( $this->config[ $offset ] ) ? $this->config[ $offset ] : null; }
[ "public", "function", "offsetGet", "(", "$", "offset", ")", "{", "return", "isset", "(", "$", "this", "->", "config", "[", "$", "offset", "]", ")", "?", "$", "this", "->", "config", "[", "$", "offset", "]", ":", "null", ";", "}" ]
Get array value by key @param int|string $offset Array key @return mixed
[ "Get", "array", "value", "by", "key" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Config.php#L141-L143
10up/wpsnapshots
src/classes/Command/Push.php
Push.configure
protected function configure() { $this->setName( 'push' ); $this->setDescription( 'Push a snapshot to a repository.' ); $this->addArgument( 'snapshot_id', InputArgument::OPTIONAL, 'Optional snapshot ID to push. If none is provided, a new snapshot will be created from the local environment.' ); $this->addOption( 'repository', null, InputOption::VALUE_REQUIRED, 'Repository to use. Defaults to first repository saved in config.' ); $this->addOption( 'no_scrub', false, InputOption::VALUE_NONE, "Don't scrub personal user data." ); $this->addOption( 'path', null, InputOption::VALUE_REQUIRED, 'Path to WordPress files.' ); $this->addOption( 'db_host', null, InputOption::VALUE_REQUIRED, 'Database host.' ); $this->addOption( 'db_name', null, InputOption::VALUE_REQUIRED, 'Database name.' ); $this->addOption( 'db_user', null, InputOption::VALUE_REQUIRED, 'Database user.' ); $this->addOption( 'db_password', null, InputOption::VALUE_REQUIRED, 'Database password.' ); $this->addOption( 'exclude', false, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Exclude a file or directory from the snapshot.' ); $this->addOption( 'exclude_uploads', false, InputOption::VALUE_NONE, 'Exclude uploads from pushed snapshot.' ); }
php
protected function configure() { $this->setName( 'push' ); $this->setDescription( 'Push a snapshot to a repository.' ); $this->addArgument( 'snapshot_id', InputArgument::OPTIONAL, 'Optional snapshot ID to push. If none is provided, a new snapshot will be created from the local environment.' ); $this->addOption( 'repository', null, InputOption::VALUE_REQUIRED, 'Repository to use. Defaults to first repository saved in config.' ); $this->addOption( 'no_scrub', false, InputOption::VALUE_NONE, "Don't scrub personal user data." ); $this->addOption( 'path', null, InputOption::VALUE_REQUIRED, 'Path to WordPress files.' ); $this->addOption( 'db_host', null, InputOption::VALUE_REQUIRED, 'Database host.' ); $this->addOption( 'db_name', null, InputOption::VALUE_REQUIRED, 'Database name.' ); $this->addOption( 'db_user', null, InputOption::VALUE_REQUIRED, 'Database user.' ); $this->addOption( 'db_password', null, InputOption::VALUE_REQUIRED, 'Database password.' ); $this->addOption( 'exclude', false, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Exclude a file or directory from the snapshot.' ); $this->addOption( 'exclude_uploads', false, InputOption::VALUE_NONE, 'Exclude uploads from pushed snapshot.' ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'push'", ")", ";", "$", "this", "->", "setDescription", "(", "'Push a snapshot to a repository.'", ")", ";", "$", "this", "->", "addArgument", "(", "'snapshot_id'", ",", ...
Setup up command
[ "Setup", "up", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Push.php#L33-L47
10up/wpsnapshots
src/classes/Command/Push.php
Push.execute
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $snapshot_id = $input->getArgument( 'snapshot_id' ); if ( empty( $snapshot_id ) ) { $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $path = $input->getOption( 'path' ); if ( empty( $path ) ) { $path = getcwd(); } $path = Utils\normalize_path( $path ); $helper = $this->getHelper( 'question' ); $verbose = $input->getOption( 'verbose' ); $project_question = new Question( 'Project Slug (letters, numbers, _, and - only): ' ); $project_question->setValidator( '\WPSnapshots\Utils\slug_validator' ); $project = $helper->ask( $input, $output, $project_question ); $description_question = new Question( 'Snapshot Description (e.g. Local environment): ' ); $description_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $description = $helper->ask( $input, $output, $description_question ); $exclude = $input->getOption( 'exclude' ); if ( ! empty( $input->getOption( 'exclude_uploads' ) ) ) { $exclude[] = './uploads'; } $snapshot = Snapshot::create( [ 'path' => $path, 'db_host' => $input->getOption( 'db_host' ), 'db_name' => $input->getOption( 'db_name' ), 'db_user' => $input->getOption( 'db_user' ), 'db_password' => $input->getOption( 'db_password' ), 'project' => $project, 'description' => $description, 'no_scrub' => $input->getOption( 'no_scrub' ), 'exclude' => $exclude, 'repository' => $repository->getName(), ], $output, $verbose ); } else { if ( ! Utils\is_snapshot_cached( $snapshot_id ) ) { Log::instance()->write( 'Snapshot not found locally.', 0, 'error' ); return 1; } $snapshot = Snapshot::get( $snapshot_id ); } if ( ! is_a( $snapshot, '\WPSnapshots\Snapshot' ) ) { return 1; } if ( $snapshot->push() ) { Log::instance()->write( 'Push finished!' . ( empty( $snapshot_id ) ? ' Snapshot ID is ' . $snapshot->id : '' ), 0, 'success' ); } }
php
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $snapshot_id = $input->getArgument( 'snapshot_id' ); if ( empty( $snapshot_id ) ) { $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $path = $input->getOption( 'path' ); if ( empty( $path ) ) { $path = getcwd(); } $path = Utils\normalize_path( $path ); $helper = $this->getHelper( 'question' ); $verbose = $input->getOption( 'verbose' ); $project_question = new Question( 'Project Slug (letters, numbers, _, and - only): ' ); $project_question->setValidator( '\WPSnapshots\Utils\slug_validator' ); $project = $helper->ask( $input, $output, $project_question ); $description_question = new Question( 'Snapshot Description (e.g. Local environment): ' ); $description_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $description = $helper->ask( $input, $output, $description_question ); $exclude = $input->getOption( 'exclude' ); if ( ! empty( $input->getOption( 'exclude_uploads' ) ) ) { $exclude[] = './uploads'; } $snapshot = Snapshot::create( [ 'path' => $path, 'db_host' => $input->getOption( 'db_host' ), 'db_name' => $input->getOption( 'db_name' ), 'db_user' => $input->getOption( 'db_user' ), 'db_password' => $input->getOption( 'db_password' ), 'project' => $project, 'description' => $description, 'no_scrub' => $input->getOption( 'no_scrub' ), 'exclude' => $exclude, 'repository' => $repository->getName(), ], $output, $verbose ); } else { if ( ! Utils\is_snapshot_cached( $snapshot_id ) ) { Log::instance()->write( 'Snapshot not found locally.', 0, 'error' ); return 1; } $snapshot = Snapshot::get( $snapshot_id ); } if ( ! is_a( $snapshot, '\WPSnapshots\Snapshot' ) ) { return 1; } if ( $snapshot->push() ) { Log::instance()->write( 'Push finished!' . ( empty( $snapshot_id ) ? ' Snapshot ID is ' . $snapshot->id : '' ), 0, 'success' ); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "Log", "::", "instance", "(", ")", "->", "setOutput", "(", "$", "output", ")", ";", "$", "snapshot_id", "=", "$", "input", "->", "ge...
Executes the command @param InputInterface $input Command input @param OutputInterface $output Command output
[ "Executes", "the", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Push.php#L55-L127
10up/wpsnapshots
src/classes/DB.php
DB.search
public function search( $query ) { $marshaler = new Marshaler(); $args = [ 'TableName' => 'wpsnapshots-' . $this->repository, ]; if ( '*' !== $query ) { $args['ConditionalOperator'] = 'OR'; $args['ScanFilter'] = [ 'project' => [ 'AttributeValueList' => [ [ 'S' => strtolower( $query ) ], ], 'ComparisonOperator' => 'CONTAINS', ], 'id' => [ 'AttributeValueList' => [ [ 'S' => strtolower( $query ) ], ], 'ComparisonOperator' => 'EQ', ], ]; } try { $search_scan = $this->client->getIterator( 'Scan', $args ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } $instances = []; foreach ( $search_scan as $item ) { $instances[] = $marshaler->unmarshalItem( $item ); } return $instances; }
php
public function search( $query ) { $marshaler = new Marshaler(); $args = [ 'TableName' => 'wpsnapshots-' . $this->repository, ]; if ( '*' !== $query ) { $args['ConditionalOperator'] = 'OR'; $args['ScanFilter'] = [ 'project' => [ 'AttributeValueList' => [ [ 'S' => strtolower( $query ) ], ], 'ComparisonOperator' => 'CONTAINS', ], 'id' => [ 'AttributeValueList' => [ [ 'S' => strtolower( $query ) ], ], 'ComparisonOperator' => 'EQ', ], ]; } try { $search_scan = $this->client->getIterator( 'Scan', $args ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } $instances = []; foreach ( $search_scan as $item ) { $instances[] = $marshaler->unmarshalItem( $item ); } return $instances; }
[ "public", "function", "search", "(", "$", "query", ")", "{", "$", "marshaler", "=", "new", "Marshaler", "(", ")", ";", "$", "args", "=", "[", "'TableName'", "=>", "'wpsnapshots-'", ".", "$", "this", "->", "repository", ",", "]", ";", "if", "(", "'*'"...
Use DynamoDB scan to search tables for snapshots where project, id, or author information matches search text. Searching for "*" returns all snapshots. @param string $query Search query string @return array
[ "Use", "DynamoDB", "scan", "to", "search", "tables", "for", "snapshots", "where", "project", "id", "or", "author", "information", "matches", "search", "text", ".", "Searching", "for", "*", "returns", "all", "snapshots", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/DB.php#L86-L130
10up/wpsnapshots
src/classes/DB.php
DB.insertSnapshot
public function insertSnapshot( $id, $snapshot ) { $marshaler = new Marshaler(); $snapshot_item = [ 'project' => strtolower( $snapshot['project'] ), 'id' => $id, 'time' => time(), 'description' => $snapshot['description'], 'author' => $snapshot['author'], 'multisite' => $snapshot['multisite'], 'sites' => $snapshot['sites'], 'table_prefix' => $snapshot['table_prefix'], 'subdomain_install' => $snapshot['subdomain_install'], 'size' => $snapshot['size'], 'wp_version' => $snapshot['wp_version'], 'repository' => $snapshot['repository'], ]; $snapshot_json = json_encode( $snapshot_item ); try { $result = $this->client->putItem( [ 'TableName' => 'wpsnapshots-' . $this->repository, 'Item' => $marshaler->marshalJson( $snapshot_json ), ] ); } catch ( \Exception $e ) { if ( 'AccessDeniedException' === $e->getAwsErrorCode() ) { Log::instance()->write( 'Access denied. You might not have access to this project.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return $snapshot_item; }
php
public function insertSnapshot( $id, $snapshot ) { $marshaler = new Marshaler(); $snapshot_item = [ 'project' => strtolower( $snapshot['project'] ), 'id' => $id, 'time' => time(), 'description' => $snapshot['description'], 'author' => $snapshot['author'], 'multisite' => $snapshot['multisite'], 'sites' => $snapshot['sites'], 'table_prefix' => $snapshot['table_prefix'], 'subdomain_install' => $snapshot['subdomain_install'], 'size' => $snapshot['size'], 'wp_version' => $snapshot['wp_version'], 'repository' => $snapshot['repository'], ]; $snapshot_json = json_encode( $snapshot_item ); try { $result = $this->client->putItem( [ 'TableName' => 'wpsnapshots-' . $this->repository, 'Item' => $marshaler->marshalJson( $snapshot_json ), ] ); } catch ( \Exception $e ) { if ( 'AccessDeniedException' === $e->getAwsErrorCode() ) { Log::instance()->write( 'Access denied. You might not have access to this project.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return $snapshot_item; }
[ "public", "function", "insertSnapshot", "(", "$", "id", ",", "$", "snapshot", ")", "{", "$", "marshaler", "=", "new", "Marshaler", "(", ")", ";", "$", "snapshot_item", "=", "[", "'project'", "=>", "strtolower", "(", "$", "snapshot", "[", "'project'", "]"...
Insert a snapshot into the DB @param string $id Snapshot ID @param array $snapshot Description of snapshot @return array|bool
[ "Insert", "a", "snapshot", "into", "the", "DB" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/DB.php#L139-L180
10up/wpsnapshots
src/classes/DB.php
DB.deleteSnapshot
public function deleteSnapshot( $id ) { try { $result = $this->client->deleteItem( [ 'TableName' => 'wpsnapshots-' . $this->repository, 'Key' => [ 'id' => [ 'S' => $id, ], ], ] ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
php
public function deleteSnapshot( $id ) { try { $result = $this->client->deleteItem( [ 'TableName' => 'wpsnapshots-' . $this->repository, 'Key' => [ 'id' => [ 'S' => $id, ], ], ] ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
[ "public", "function", "deleteSnapshot", "(", "$", "id", ")", "{", "try", "{", "$", "result", "=", "$", "this", "->", "client", "->", "deleteItem", "(", "[", "'TableName'", "=>", "'wpsnapshots-'", ".", "$", "this", "->", "repository", ",", "'Key'", "=>", ...
Delete a snapshot given an id @param string $id Snapshot ID @return bool|Error
[ "Delete", "a", "snapshot", "given", "an", "id" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/DB.php#L188-L210
10up/wpsnapshots
src/classes/DB.php
DB.getSnapshot
public function getSnapshot( $id ) { try { $result = $this->client->getItem( [ 'ConsistentRead' => true, 'TableName' => 'wpsnapshots-' . $this->repository, 'Key' => [ 'id' => [ 'S' => $id, ], ], ] ); } catch ( \Exception $e ) { if ( 'AccessDeniedException' === $e->getAwsErrorCode() ) { Log::instance()->write( 'Access denied. You might not have access to this snapshot.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } if ( empty( $result['Item'] ) ) { return false; } if ( ! empty( $result['Item']['error'] ) ) { return false; } $marshaler = new Marshaler(); return $marshaler->unmarshalItem( $result['Item'] ); }
php
public function getSnapshot( $id ) { try { $result = $this->client->getItem( [ 'ConsistentRead' => true, 'TableName' => 'wpsnapshots-' . $this->repository, 'Key' => [ 'id' => [ 'S' => $id, ], ], ] ); } catch ( \Exception $e ) { if ( 'AccessDeniedException' === $e->getAwsErrorCode() ) { Log::instance()->write( 'Access denied. You might not have access to this snapshot.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } if ( empty( $result['Item'] ) ) { return false; } if ( ! empty( $result['Item']['error'] ) ) { return false; } $marshaler = new Marshaler(); return $marshaler->unmarshalItem( $result['Item'] ); }
[ "public", "function", "getSnapshot", "(", "$", "id", ")", "{", "try", "{", "$", "result", "=", "$", "this", "->", "client", "->", "getItem", "(", "[", "'ConsistentRead'", "=>", "true", ",", "'TableName'", "=>", "'wpsnapshots-'", ".", "$", "this", "->", ...
Get a snapshot given an id @param string $id Snapshot ID @return bool
[ "Get", "a", "snapshot", "given", "an", "id" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/DB.php#L218-L255
10up/wpsnapshots
src/classes/DB.php
DB.createTables
public function createTables() { try { $this->client->createTable( [ 'TableName' => 'wpsnapshots-' . $this->repository, 'AttributeDefinitions' => [ [ 'AttributeName' => 'id', 'AttributeType' => 'S', ], ], 'KeySchema' => [ [ 'AttributeName' => 'id', 'KeyType' => 'HASH', ], ], 'ProvisionedThroughput' => [ 'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 20, ], ] ); $this->client->waitUntil( 'TableExists', [ 'TableName' => 'wpsnapshots-' . $this->repository, ] ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return $e->getAwsErrorCode(); } return true; }
php
public function createTables() { try { $this->client->createTable( [ 'TableName' => 'wpsnapshots-' . $this->repository, 'AttributeDefinitions' => [ [ 'AttributeName' => 'id', 'AttributeType' => 'S', ], ], 'KeySchema' => [ [ 'AttributeName' => 'id', 'KeyType' => 'HASH', ], ], 'ProvisionedThroughput' => [ 'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 20, ], ] ); $this->client->waitUntil( 'TableExists', [ 'TableName' => 'wpsnapshots-' . $this->repository, ] ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return $e->getAwsErrorCode(); } return true; }
[ "public", "function", "createTables", "(", ")", "{", "try", "{", "$", "this", "->", "client", "->", "createTable", "(", "[", "'TableName'", "=>", "'wpsnapshots-'", ".", "$", "this", "->", "repository", ",", "'AttributeDefinitions'", "=>", "[", "[", "'Attribu...
Create default DB tables. Only need to do this once ever for repo setup. @return bool
[ "Create", "default", "DB", "tables", ".", "Only", "need", "to", "do", "this", "once", "ever", "for", "repo", "setup", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/DB.php#L262-L301
10up/wpsnapshots
src/classes/Command/Configure.php
Configure.execute
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = $input->getArgument( 'repository' ); $region = $input->getOption( 'region' ); $access_key_id = $input->getOption( 'aws_key' ); $secret_access_key = $input->getOption( 'aws_secret' ); if ( empty( $region ) ) { $region = 'us-west-1'; } $config = Config::get(); if ( ! empty( $config['repositories'][ $repository ] ) ) { Log::instance()->write( 'Repository config already exists. Proceeding will overwrite it.' ); } $repo_config = [ 'repository' => $repository, ]; $helper = $this->getHelper( 'question' ); $i = 0; /** * Loop until we get S3 credentials that work */ while ( true ) { if ( 0 < $i || empty( $access_key_id ) ) { $access_key_id = $helper->ask( $input, $output, new Question( 'AWS Access Key ID: ' ) ); } if ( 0 < $i || empty( $secret_access_key ) ) { $secret_access_key = $helper->ask( $input, $output, new Question( 'AWS Secret Access Key: ' ) ); } $repo_config['access_key_id'] = $access_key_id; $repo_config['secret_access_key'] = $secret_access_key; $repo_config['region'] = $region; $test = S3::test( $repo_config ); if ( true !== $test ) { break; } else { if ( 'InvalidAccessKeyId' === $test ) { Log::instance()->write( 'Repository connection did not work. Try again?', 0, 'warning' ); } elseif ( 'NoSuchBucket' === $test ) { Log::instance()->write( 'We successfully connected to AWS. However, no repository has been created. Run `wpsnapshots create-repository` after configuration is complete.', 0, 'warning' ); break; } else { break; } } $i++; } $name = $input->getOption( 'user_name' ); $email = $input->getOption( 'user_email' ); if ( empty( $name ) ) { $name_question = new Question( 'Your Name: ' ); $name_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $name = $helper->ask( $input, $output, $name_question ); } $config['name'] = $name; if ( empty( $email ) ) { $email = $helper->ask( $input, $output, new Question( 'Your Email: ' ) ); } if ( ! empty( $email ) ) { $config['email'] = $email; } $create_dir = Utils\create_snapshot_directory(); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directory.', 0, 'error' ); return 1; } $repositories = $config['repositories']; $repositories[ $repository ] = $repo_config; $config['repositories'] = $repositories; $config->write(); Log::instance()->write( 'WP Snapshots configuration verified and saved.', 0, 'success' ); }
php
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = $input->getArgument( 'repository' ); $region = $input->getOption( 'region' ); $access_key_id = $input->getOption( 'aws_key' ); $secret_access_key = $input->getOption( 'aws_secret' ); if ( empty( $region ) ) { $region = 'us-west-1'; } $config = Config::get(); if ( ! empty( $config['repositories'][ $repository ] ) ) { Log::instance()->write( 'Repository config already exists. Proceeding will overwrite it.' ); } $repo_config = [ 'repository' => $repository, ]; $helper = $this->getHelper( 'question' ); $i = 0; /** * Loop until we get S3 credentials that work */ while ( true ) { if ( 0 < $i || empty( $access_key_id ) ) { $access_key_id = $helper->ask( $input, $output, new Question( 'AWS Access Key ID: ' ) ); } if ( 0 < $i || empty( $secret_access_key ) ) { $secret_access_key = $helper->ask( $input, $output, new Question( 'AWS Secret Access Key: ' ) ); } $repo_config['access_key_id'] = $access_key_id; $repo_config['secret_access_key'] = $secret_access_key; $repo_config['region'] = $region; $test = S3::test( $repo_config ); if ( true !== $test ) { break; } else { if ( 'InvalidAccessKeyId' === $test ) { Log::instance()->write( 'Repository connection did not work. Try again?', 0, 'warning' ); } elseif ( 'NoSuchBucket' === $test ) { Log::instance()->write( 'We successfully connected to AWS. However, no repository has been created. Run `wpsnapshots create-repository` after configuration is complete.', 0, 'warning' ); break; } else { break; } } $i++; } $name = $input->getOption( 'user_name' ); $email = $input->getOption( 'user_email' ); if ( empty( $name ) ) { $name_question = new Question( 'Your Name: ' ); $name_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $name = $helper->ask( $input, $output, $name_question ); } $config['name'] = $name; if ( empty( $email ) ) { $email = $helper->ask( $input, $output, new Question( 'Your Email: ' ) ); } if ( ! empty( $email ) ) { $config['email'] = $email; } $create_dir = Utils\create_snapshot_directory(); if ( ! $create_dir ) { Log::instance()->write( 'Cannot create necessary snapshot directory.', 0, 'error' ); return 1; } $repositories = $config['repositories']; $repositories[ $repository ] = $repo_config; $config['repositories'] = $repositories; $config->write(); Log::instance()->write( 'WP Snapshots configuration verified and saved.', 0, 'success' ); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "Log", "::", "instance", "(", ")", "->", "setOutput", "(", "$", "output", ")", ";", "$", "repository", "=", "$", "input", "->", "get...
Execute command @param InputInterface $input Command input @param OutputInterface $output Command output
[ "Execute", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Configure.php#L48-L146
10up/wpsnapshots
src/classes/WordPressBridge.php
WordPressBridge.load
public function load( $path, $extra_config_constants = [] ) { $wp_config_code = preg_split( '/\R/', file_get_contents( Utils\locate_wp_config( $path ) ) ); $found_wp_settings = false; $lines_to_run = []; if ( file_exists( $path . 'wp-config.php' ) ) { $path_replacements = [ '__FILE__' => "'" . $path . "wp-config.php'", '__DIR__' => "'" . $path . "'", ]; } else { // Must be one directory up $path_replacements = [ '__FILE__' => "'" . dirname( $path ) . "/wp-config.php'", '__DIR__' => "'" . dirname( $path ) . "'", ]; } /** * First thing we do is try to test config DB settings mixed in with user defined DB settings * before defining constants. The purpose of this is to guess the correct DB_HOST if the connection * doesn't work. */ $pre_config_constants = []; foreach ( $wp_config_code as $line ) { if ( preg_match( '#define\(.*?("|\')DB_HOST("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_HOST'] = preg_replace( '#define\(.*?("|\')DB_HOST("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } elseif ( preg_match( '#define\(.*?("|\')DB_USER("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_USER'] = preg_replace( '#define\(.*?("|\')DB_USER("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } elseif ( preg_match( '#define\(.*?("|\')DB_NAME("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_NAME'] = preg_replace( '#define\(.*?("|\')DB_NAME("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } elseif ( preg_match( '#define\(.*?("|\')DB_PASSWORD("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_PASSWORD'] = preg_replace( '#define\(.*?("|\')DB_PASSWORD("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } } foreach ( $extra_config_constants as $config_constant => $config_constant_value ) { $pre_config_constants[ $config_constant ] = $config_constant_value; } if ( ! empty( $pre_config_constants['DB_HOST'] ) && ! empty( $pre_config_constants['DB_NAME'] ) && ! empty( $pre_config_constants['DB_USER'] ) && ! empty( $pre_config_constants['DB_PASSWORD'] ) ) { $connection = Utils\test_mysql_connection( $pre_config_constants['DB_HOST'], $pre_config_constants['DB_NAME'], $pre_config_constants['DB_USER'], $pre_config_constants['DB_PASSWORD'] ); if ( true !== $connection ) { $connection = Utils\test_mysql_connection( '127.0.0.1', $pre_config_constants['DB_NAME'], $pre_config_constants['DB_USER'], $pre_config_constants['DB_PASSWORD'] ); if ( true === $connection ) { $extra_config_constants['DB_HOST'] = '127.0.0.1'; } } } foreach ( $wp_config_code as $line ) { if ( preg_match( '/^\s*require.+wp-settings\.php/', $line ) ) { continue; } /** * Don't execute override constants */ foreach ( $extra_config_constants as $config_constant => $config_constant_value ) { if ( preg_match( '#define\(.*?("|\')' . $config_constant . '("|\').*?\).*?;#', $line ) ) { continue 2; } } /** * Swap path related constants so we can run WP as a composer dependancy */ $line = str_replace( array_keys( $path_replacements ), array_values( $path_replacements ), $line ); $lines_to_run[] = $line; } $source = implode( "\n", $lines_to_run ); define( 'ABSPATH', $path ); /** * Set constant for instances in theme or plugin code that may prevent wpsnapshots from executing properly. */ define( 'WPSNAPSHOTS', true ); /** * Define some server variables we might need */ $_SERVER['REMOTE_ADDR'] = '1.1.1.1'; /** * Add in override constants */ foreach ( $extra_config_constants as $config_constant => $config_constant_value ) { define( $config_constant, $config_constant_value ); } eval( preg_replace( '|^\s*\<\?php\s*|', '', $source ) ); if ( defined( 'DOMAIN_CURRENT_SITE' ) ) { $url = DOMAIN_CURRENT_SITE; if ( defined( 'PATH_CURRENT_SITE' ) ) { $url .= PATH_CURRENT_SITE; } $url_parts = parse_url( $url ); if ( ! isset( $url_parts['scheme'] ) ) { $url_parts = parse_url( 'http://' . $url ); } if ( isset( $url_parts['host'] ) ) { if ( isset( $url_parts['scheme'] ) && 'https' === strtolower( $url_parts['scheme'] ) ) { $_SERVER['HTTPS'] = 'on'; } $_SERVER['HTTP_HOST'] = $url_parts['host']; if ( isset( $url_parts['port'] ) ) { $_SERVER['HTTP_HOST'] .= ':' . $url_parts['port']; } $_SERVER['SERVER_NAME'] = $url_parts['host']; } $_SERVER['REQUEST_URI'] = $url_parts['path'] . ( isset( $url_parts['query'] ) ? '?' . $url_parts['query'] : '' ); $_SERVER['SERVER_PORT'] = ( isset( $url_parts['port'] ) ) ? $url_parts['port'] : 80; $_SERVER['QUERY_STRING'] = ( isset( $url_parts['query'] ) ) ? $url_parts['query'] : ''; } Log::instance()->write( 'Testing MySQL connection.', 1 ); // Test DB connect $connection = Utils\test_mysql_connection( DB_HOST, DB_NAME, DB_USER, DB_PASSWORD ); if ( true !== $connection ) { if ( false !== strpos( $connection, 'php_network_getaddresses' ) ) { Log::instance()->write( "Couldn't connect to MySQL host.", 0, 'error' ); } else { Log::instance()->write( 'Could not connect to MySQL. Is your connection info correct?', 0, 'error' ); Log::instance()->write( 'MySQL error: ' . $connection, 1, 'error' ); } Log::instance()->write( 'MySQL connection info:', 1 ); Log::instance()->write( 'DB_HOST: ' . DB_HOST, 1 ); Log::instance()->write( 'DB_NAME: ' . DB_NAME, 1 ); Log::instance()->write( 'DB_USER: ' . DB_USER, 1 ); Log::instance()->write( 'DB_PASSWORD: ' . DB_PASSWORD, 1 ); return false; } // We can require settings after we fake $_SERVER keys require_once ABSPATH . 'wp-settings.php'; return true; }
php
public function load( $path, $extra_config_constants = [] ) { $wp_config_code = preg_split( '/\R/', file_get_contents( Utils\locate_wp_config( $path ) ) ); $found_wp_settings = false; $lines_to_run = []; if ( file_exists( $path . 'wp-config.php' ) ) { $path_replacements = [ '__FILE__' => "'" . $path . "wp-config.php'", '__DIR__' => "'" . $path . "'", ]; } else { // Must be one directory up $path_replacements = [ '__FILE__' => "'" . dirname( $path ) . "/wp-config.php'", '__DIR__' => "'" . dirname( $path ) . "'", ]; } /** * First thing we do is try to test config DB settings mixed in with user defined DB settings * before defining constants. The purpose of this is to guess the correct DB_HOST if the connection * doesn't work. */ $pre_config_constants = []; foreach ( $wp_config_code as $line ) { if ( preg_match( '#define\(.*?("|\')DB_HOST("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_HOST'] = preg_replace( '#define\(.*?("|\')DB_HOST("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } elseif ( preg_match( '#define\(.*?("|\')DB_USER("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_USER'] = preg_replace( '#define\(.*?("|\')DB_USER("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } elseif ( preg_match( '#define\(.*?("|\')DB_NAME("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_NAME'] = preg_replace( '#define\(.*?("|\')DB_NAME("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } elseif ( preg_match( '#define\(.*?("|\')DB_PASSWORD("|\').*?\).*?;#', $line ) ) { $pre_config_constants['DB_PASSWORD'] = preg_replace( '#define\(.*?("|\')DB_PASSWORD("|\').*?,.*?("|\')(.*?)("|\').*?\).*?;#', '$4', $line ); } } foreach ( $extra_config_constants as $config_constant => $config_constant_value ) { $pre_config_constants[ $config_constant ] = $config_constant_value; } if ( ! empty( $pre_config_constants['DB_HOST'] ) && ! empty( $pre_config_constants['DB_NAME'] ) && ! empty( $pre_config_constants['DB_USER'] ) && ! empty( $pre_config_constants['DB_PASSWORD'] ) ) { $connection = Utils\test_mysql_connection( $pre_config_constants['DB_HOST'], $pre_config_constants['DB_NAME'], $pre_config_constants['DB_USER'], $pre_config_constants['DB_PASSWORD'] ); if ( true !== $connection ) { $connection = Utils\test_mysql_connection( '127.0.0.1', $pre_config_constants['DB_NAME'], $pre_config_constants['DB_USER'], $pre_config_constants['DB_PASSWORD'] ); if ( true === $connection ) { $extra_config_constants['DB_HOST'] = '127.0.0.1'; } } } foreach ( $wp_config_code as $line ) { if ( preg_match( '/^\s*require.+wp-settings\.php/', $line ) ) { continue; } /** * Don't execute override constants */ foreach ( $extra_config_constants as $config_constant => $config_constant_value ) { if ( preg_match( '#define\(.*?("|\')' . $config_constant . '("|\').*?\).*?;#', $line ) ) { continue 2; } } /** * Swap path related constants so we can run WP as a composer dependancy */ $line = str_replace( array_keys( $path_replacements ), array_values( $path_replacements ), $line ); $lines_to_run[] = $line; } $source = implode( "\n", $lines_to_run ); define( 'ABSPATH', $path ); /** * Set constant for instances in theme or plugin code that may prevent wpsnapshots from executing properly. */ define( 'WPSNAPSHOTS', true ); /** * Define some server variables we might need */ $_SERVER['REMOTE_ADDR'] = '1.1.1.1'; /** * Add in override constants */ foreach ( $extra_config_constants as $config_constant => $config_constant_value ) { define( $config_constant, $config_constant_value ); } eval( preg_replace( '|^\s*\<\?php\s*|', '', $source ) ); if ( defined( 'DOMAIN_CURRENT_SITE' ) ) { $url = DOMAIN_CURRENT_SITE; if ( defined( 'PATH_CURRENT_SITE' ) ) { $url .= PATH_CURRENT_SITE; } $url_parts = parse_url( $url ); if ( ! isset( $url_parts['scheme'] ) ) { $url_parts = parse_url( 'http://' . $url ); } if ( isset( $url_parts['host'] ) ) { if ( isset( $url_parts['scheme'] ) && 'https' === strtolower( $url_parts['scheme'] ) ) { $_SERVER['HTTPS'] = 'on'; } $_SERVER['HTTP_HOST'] = $url_parts['host']; if ( isset( $url_parts['port'] ) ) { $_SERVER['HTTP_HOST'] .= ':' . $url_parts['port']; } $_SERVER['SERVER_NAME'] = $url_parts['host']; } $_SERVER['REQUEST_URI'] = $url_parts['path'] . ( isset( $url_parts['query'] ) ? '?' . $url_parts['query'] : '' ); $_SERVER['SERVER_PORT'] = ( isset( $url_parts['port'] ) ) ? $url_parts['port'] : 80; $_SERVER['QUERY_STRING'] = ( isset( $url_parts['query'] ) ) ? $url_parts['query'] : ''; } Log::instance()->write( 'Testing MySQL connection.', 1 ); // Test DB connect $connection = Utils\test_mysql_connection( DB_HOST, DB_NAME, DB_USER, DB_PASSWORD ); if ( true !== $connection ) { if ( false !== strpos( $connection, 'php_network_getaddresses' ) ) { Log::instance()->write( "Couldn't connect to MySQL host.", 0, 'error' ); } else { Log::instance()->write( 'Could not connect to MySQL. Is your connection info correct?', 0, 'error' ); Log::instance()->write( 'MySQL error: ' . $connection, 1, 'error' ); } Log::instance()->write( 'MySQL connection info:', 1 ); Log::instance()->write( 'DB_HOST: ' . DB_HOST, 1 ); Log::instance()->write( 'DB_NAME: ' . DB_NAME, 1 ); Log::instance()->write( 'DB_USER: ' . DB_USER, 1 ); Log::instance()->write( 'DB_PASSWORD: ' . DB_PASSWORD, 1 ); return false; } // We can require settings after we fake $_SERVER keys require_once ABSPATH . 'wp-settings.php'; return true; }
[ "public", "function", "load", "(", "$", "path", ",", "$", "extra_config_constants", "=", "[", "]", ")", "{", "$", "wp_config_code", "=", "preg_split", "(", "'/\\R/'", ",", "file_get_contents", "(", "Utils", "\\", "locate_wp_config", "(", "$", "path", ")", ...
Bootstrap WordPress just enough to get what we need. This method loads wp-config.php without wp-settings.php ensuring we get the constants we need. It also loads $wpdb so we can perform database operations. @param string $path Path to WordPress @param array $extra_config_constants Array of extra constants @return boolean
[ "Bootstrap", "WordPress", "just", "enough", "to", "get", "what", "we", "need", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/WordPressBridge.php#L30-L186
10up/wpsnapshots
src/classes/Command/Pull.php
Pull.configure
protected function configure() { $this->setName( 'pull' ); $this->setDescription( 'Pull a snapshot into a WordPress instance.' ); $this->addArgument( 'snapshot_id', InputArgument::REQUIRED, 'Snapshot ID to pull.' ); $this->addOption( 'confirm', null, InputOption::VALUE_NONE, 'Confirm pull operation.' ); $this->addOption( 'repository', null, InputOption::VALUE_REQUIRED, 'Repository to use. Defaults to first repository saved in config.' ); $this->addOption( 'confirm_wp_download', null, InputOption::VALUE_NONE, 'Confirm WordPress download.' ); $this->addOption( 'confirm_config_create', null, InputOption::VALUE_NONE, 'Confirm wp-config.php create.' ); $this->addOption( 'confirm_wp_version_change', null, InputOption::VALUE_NONE, 'Confirm changing WP version to match snapshot.' ); $this->addOption( 'confirm_ms_constant_update', null, InputOption::VALUE_NONE, 'Confirm updating constants in wp-config.php for multisite.' ); $this->addOption( 'config_db_host', null, InputOption::VALUE_REQUIRED, 'Config database host.' ); $this->addOption( 'config_db_name', null, InputOption::VALUE_REQUIRED, 'Config database name.' ); $this->addOption( 'config_db_user', null, InputOption::VALUE_REQUIRED, 'Config database user.' ); $this->addOption( 'config_db_password', null, InputOption::VALUE_REQUIRED, 'Config database password.' ); $this->addOption( 'path', null, InputOption::VALUE_REQUIRED, 'Path to WordPress files.' ); $this->addOption( 'skip_table_search_replace', [], InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Skip search and replacing specific tables. Leave out table prefix.' ); $this->addOption( 'db_host', null, InputOption::VALUE_REQUIRED, 'Database host.' ); $this->addOption( 'db_name', null, InputOption::VALUE_REQUIRED, 'Database name.' ); $this->addOption( 'db_user', null, InputOption::VALUE_REQUIRED, 'Database user.' ); $this->addOption( 'db_password', null, InputOption::VALUE_REQUIRED, 'Database password.' ); /** * Site Mapping JSON should look like this: * * [ * { * "home_url" : "http://homeurl1", * "site_url" : "http://siteurl1" * "blog_id" : 1 * } * ... * ] * * If blog_id isn't used, order will be respected as compared to the snapshot meta. */ $this->addOption( 'site_mapping', null, InputOption::VALUE_REQUIRED, 'JSON or path to site mapping file.' ); $this->addOption( 'main_domain', null, InputOption::VALUE_REQUIRED, 'Main domain for multisite snapshots' ); }
php
protected function configure() { $this->setName( 'pull' ); $this->setDescription( 'Pull a snapshot into a WordPress instance.' ); $this->addArgument( 'snapshot_id', InputArgument::REQUIRED, 'Snapshot ID to pull.' ); $this->addOption( 'confirm', null, InputOption::VALUE_NONE, 'Confirm pull operation.' ); $this->addOption( 'repository', null, InputOption::VALUE_REQUIRED, 'Repository to use. Defaults to first repository saved in config.' ); $this->addOption( 'confirm_wp_download', null, InputOption::VALUE_NONE, 'Confirm WordPress download.' ); $this->addOption( 'confirm_config_create', null, InputOption::VALUE_NONE, 'Confirm wp-config.php create.' ); $this->addOption( 'confirm_wp_version_change', null, InputOption::VALUE_NONE, 'Confirm changing WP version to match snapshot.' ); $this->addOption( 'confirm_ms_constant_update', null, InputOption::VALUE_NONE, 'Confirm updating constants in wp-config.php for multisite.' ); $this->addOption( 'config_db_host', null, InputOption::VALUE_REQUIRED, 'Config database host.' ); $this->addOption( 'config_db_name', null, InputOption::VALUE_REQUIRED, 'Config database name.' ); $this->addOption( 'config_db_user', null, InputOption::VALUE_REQUIRED, 'Config database user.' ); $this->addOption( 'config_db_password', null, InputOption::VALUE_REQUIRED, 'Config database password.' ); $this->addOption( 'path', null, InputOption::VALUE_REQUIRED, 'Path to WordPress files.' ); $this->addOption( 'skip_table_search_replace', [], InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Skip search and replacing specific tables. Leave out table prefix.' ); $this->addOption( 'db_host', null, InputOption::VALUE_REQUIRED, 'Database host.' ); $this->addOption( 'db_name', null, InputOption::VALUE_REQUIRED, 'Database name.' ); $this->addOption( 'db_user', null, InputOption::VALUE_REQUIRED, 'Database user.' ); $this->addOption( 'db_password', null, InputOption::VALUE_REQUIRED, 'Database password.' ); /** * Site Mapping JSON should look like this: * * [ * { * "home_url" : "http://homeurl1", * "site_url" : "http://siteurl1" * "blog_id" : 1 * } * ... * ] * * If blog_id isn't used, order will be respected as compared to the snapshot meta. */ $this->addOption( 'site_mapping', null, InputOption::VALUE_REQUIRED, 'JSON or path to site mapping file.' ); $this->addOption( 'main_domain', null, InputOption::VALUE_REQUIRED, 'Main domain for multisite snapshots' ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'pull'", ")", ";", "$", "this", "->", "setDescription", "(", "'Pull a snapshot into a WordPress instance.'", ")", ";", "$", "this", "->", "addArgument", "(", "'snapshot_id'"...
Setup up command
[ "Setup", "up", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Pull.php#L36-L77
10up/wpsnapshots
src/classes/Command/Pull.php
Pull.execute
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $id = $input->getArgument( 'snapshot_id' ); $path = $input->getOption( 'path' ); if ( empty( $path ) ) { $path = getcwd(); } $path = Utils\normalize_path( $path ); $snapshot_path = Utils\get_snapshot_directory() . $id . '/'; $snapshot = Snapshot::download( $id, $repository->getName() ); if ( ! is_a( $snapshot, '\WPSnapshots\Snapshot' ) ) { return 1; } $verbose = $input->getOption( 'verbose' ); $verbose_pipe = ( ! $verbose ) ? '> /dev/null' : ''; $helper = $this->getHelper( 'question' ); if ( ! Utils\is_wp_present( $path ) ) { Log::instance()->write( 'This is not a WordPress install. WordPress needs to be present in order to pull a snapshot.', 0, 'error' ); if ( empty( $input->getOption( 'confirm_wp_download' ) ) ) { $download_wp = $helper->ask( $input, $output, new ConfirmationQuestion( 'Do you want to download WordPress? (yes|no) ', false ) ); if ( ! $download_wp ) { return 1; } } /** * Download WordPress core files */ Log::instance()->write( 'Getting WordPress download URL...', 1 ); $download_url = Utils\get_download_url(); $headers = [ 'Accept' => 'application/json' ]; $options = [ 'timeout' => 600, 'filename' => $snapshot_path . 'wp.tar.gz', ]; Log::instance()->write( 'Downloading WordPress...', 1 ); $request = Requests::get( $download_url, $headers, $options ); Log::instance()->write( 'Extracting WordPress...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress && tar -C ' . Utils\escape_shell_path( $path ) . ' -xf ' . Utils\escape_shell_path( $snapshot_path ) . 'wp.tar.gz ' . $verbose_pipe ); Log::instance()->write( 'Moving WordPress files...', 1 ); exec( 'mv ' . Utils\escape_shell_path( $path ) . 'wordpress/* .' ); Log::instance()->write( 'Removing temporary WordPress files...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress' ); Log::instance()->write( 'WordPress downloaded.' ); } if ( ! Utils\locate_wp_config( $path ) ) { Log::instance()->write( 'No wp-config.php file present. wp-config.php needs to be setup in order to pull a snapshot.', 0, 'error' ); if ( empty( $input->getOption( 'confirm_config_create' ) ) ) { $create_config = $helper->ask( $input, $output, new ConfirmationQuestion( 'Do you want to create a wp-config.php file? (yes|no) ', false ) ); if ( ! $create_config ) { return 1; } } $config_constants = []; if ( ! empty( $input->getOption( 'config_db_host' ) ) ) { $config_constants['DB_HOST'] = $input->getOption( 'config_db_host' ); } else { $db_host_question = new Question( 'What is your database host? ' ); $db_host_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_HOST'] = $helper->ask( $input, $output, $db_host_question ); } if ( ! empty( $input->getOption( 'config_db_name' ) ) ) { $config_constants['DB_NAME'] = $input->getOption( 'config_db_name' ); } else { $db_name_question = new Question( 'What is your database name? ' ); $db_name_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_NAME'] = $helper->ask( $input, $output, $db_name_question ); } if ( ! empty( $input->getOption( 'config_db_user' ) ) ) { $config_constants['DB_USER'] = $input->getOption( 'config_db_user' ); } else { $db_user_question = new Question( 'What is your database user? ' ); $db_user_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_USER'] = $helper->ask( $input, $output, $db_user_question ); } if ( ! empty( $input->getOption( 'config_db_password' ) ) ) { $config_constants['DB_PASSWORD'] = $input->getOption( 'config_db_password' ); } else { $db_password_question = new Question( 'What is your database password? ' ); $db_password_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_PASSWORD'] = $helper->ask( $input, $output, $db_password_question ); } Log::instance()->write( 'Creating wp-config.php file...', 1 ); Utils\create_config_file( $path . 'wp-config.php', $path . 'wp-config-sample.php', $config_constants ); Log::instance()->write( 'wp-config.php created.' ); } $extra_config_constants = [ 'WP_CACHE' => false, ]; $db_host = $input->getOption( 'db_host' ); $db_name = $input->getOption( 'db_name' ); $db_user = $input->getOption( 'db_user' ); $db_password = $input->getOption( 'db_password' ); if ( ! empty( $db_host ) ) { $extra_config_constants['DB_HOST'] = $db_host; } if ( ! empty( $db_name ) ) { $extra_config_constants['DB_NAME'] = $db_name; } if ( ! empty( $db_user ) ) { $extra_config_constants['DB_USER'] = $db_user; } if ( ! empty( $db_password ) ) { $extra_config_constants['DB_PASSWORD'] = $db_password; } /** * Make sure we don't redirect if no tables exist */ define( 'WP_INSTALLING', true ); Log::instance()->write( 'Bootstrapping WordPress...', 1 ); if ( ! WordPressBridge::instance()->load( $path, $extra_config_constants ) ) { Log::instance()->write( 'Could not connect to WordPress database.', 0, 'error' ); return 1; } $pre_update_site_url = site_url(); $pre_update_home_url = home_url(); $use_https = false; if ( ! empty( $pre_update_site_url ) ) { $pre_update_site_url_parsed = parse_url( $pre_update_site_url ); if ( 'https' === $pre_update_site_url_parsed['scheme'] ) { $use_https = true; } } /** * We make the user double confirm since this could destroy a website */ $confirm = $input->getOption( 'confirm' ); if ( empty( $confirm ) ) { $confirm = $helper->ask( $input, $output, new ConfirmationQuestion( 'Are you sure you want to do this? This is a potentially destructive operation. You should run a back up first. (yes|no) ', false ) ); if ( ! $confirm ) { return 1; } } Log::instance()->write( 'Decompressing database backup file...' ); exec( 'cd ' . Utils\escape_shell_path( $snapshot_path ) . ' && gzip -d -k -f data.sql.gz ' . $verbose_pipe ); Log::instance()->write( 'Replacing wp-content/...' ); Log::instance()->write( 'wp-content path set to ' . WP_CONTENT_DIR, 1 ); Log::instance()->write( 'Removing old wp-content/...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . '/..?* ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . '/.[!.]* ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . '/*' ); Log::instance()->write( 'Extracting snapshot wp-content/...', 1 ); exec( 'mkdir -p ' . Utils\escape_shell_path( WP_CONTENT_DIR ) ); exec( 'tar -C ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . ' -xf ' . Utils\escape_shell_path( $snapshot_path ) . 'files.tar.gz ' . $verbose_pipe ); /** * Import tables */ $args = array( 'host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASSWORD, 'database' => DB_NAME, 'execute' => 'SET GLOBAL max_allowed_packet=51200000;', ); Log::instance()->write( 'Attempting to set max_allowed_packet...', 1 ); $command_result = Utils\run_mysql_command( 'mysql --no-defaults --no-auto-rehash', $args, '', false ); if ( 0 !== $command_result ) { Log::instance()->write( 'Could not set MySQL max_allowed_packet. If MySQL import fails, try running WP Snapshots using root DB user.', 0, 'warning' ); } Log::instance()->write( 'Updating database. This may take awhile depending on the size of the database (' . Utils\format_bytes( filesize( $snapshot_path . 'data.sql' ) ) . ')...' ); $query = 'SET autocommit = 0; SET unique_checks = 0; SET foreign_key_checks = 0; SOURCE %s; COMMIT;'; $args = array( 'host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASSWORD, 'database' => DB_NAME, 'execute' => sprintf( $query, $snapshot_path . 'data.sql' ), ); if ( ! isset( $assoc_args['default-character-set'] ) && defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) { $args['default-character-set'] = constant( 'DB_CHARSET' ); } Utils\run_mysql_command( 'mysql --no-defaults --no-auto-rehash', $args ); /** * Customize DB for current install */ Log::instance()->write( 'Getting MySQL tables...', 1 ); $all_tables = Utils\get_tables( false ); global $wpdb; $main_blog_id = ( defined( 'BLOG_ID_CURRENT_SITE' ) ) ? BLOG_ID_CURRENT_SITE : null; $current_table_prefix = $wpdb->get_blog_prefix( $main_blog_id ); /** * First update table prefixes */ if ( ! empty( $snapshot->meta['table_prefix'] ) && ! empty( $current_table_prefix ) && $snapshot->meta['table_prefix'] !== $current_table_prefix ) { Log::instance()->write( 'Renaming WordPress tables...' ); foreach ( $all_tables as $table ) { if ( 0 === strpos( $table, $snapshot->meta['table_prefix'] ) ) { /** * Update this table to use the current config prefix */ $new_table = $current_table_prefix . str_replace( $snapshot->meta['table_prefix'], '', $table ); $wpdb->query( sprintf( 'RENAME TABLE `%s` TO `%s`', esc_sql( $table ), esc_sql( $new_table ) ) ); } } } global $wp_version; if ( ! empty( $snapshot->meta['wp_version'] ) && $snapshot->meta['wp_version'] !== $wp_version ) { $confirm_wp_version_change = $input->getOption( 'confirm_wp_version_change' ); $change_wp_version = true; if ( empty( $confirm_wp_version_change ) ) { $change_wp_version = $helper->ask( $input, $output, new ConfirmationQuestion( 'This snapshot is running WordPress version ' . $snapshot->meta['wp_version'] . ', and you are running ' . $wp_version . '. Do you want to change your WordPress version to ' . $snapshot->meta['wp_version'] . '? (yes|no) ', true ) ); } if ( ! empty( $change_wp_version ) ) { // Delete old WordPress exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wp-includes ' . Utils\escape_shell_path( $path ) . 'wp-admin' ); exec( 'cd ' . Utils\escape_shell_path( $path ) . ' && rm index.php && rm xmlrpc.php && rm license.txt && rm readme.html' ); exec( 'cd ' . Utils\escape_shell_path( $path ) . ' && find . -maxdepth 1 ! -path . -type f -name "wp-*.php" ! -iname "wp-config.php" -delete' ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress' ); Log::instance()->write( 'Getting WordPress download URL...', 1 ); $download_url = Utils\get_download_url( $snapshot->meta['wp_version'] ); $headers = [ 'Accept' => 'application/json' ]; $options = [ 'timeout' => 600, 'filename' => $snapshot_path . 'wp.tar.gz', ]; Log::instance()->write( 'Downloading WordPress ' . $snapshot->meta['wp_version'] . '...', 1 ); $request = Requests::get( $download_url, $headers, $options ); Log::instance()->write( 'Extracting WordPress...', 1 ); exec( 'tar -C ' . Utils\escape_shell_path( $path ) . ' -xf ' . Utils\escape_shell_path( $snapshot_path ) . 'wp.tar.gz ' . $verbose_pipe ); Log::instance()->write( 'Moving WordPress files...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress/wp-content && mv ' . Utils\escape_shell_path( $path ) . 'wordpress/* .' ); Log::instance()->write( 'Removing temporary WordPress files...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress' ); Log::instance()->write( 'WordPress version changed.' ); } } /** * Get tables again since it could have changed */ $wp_tables = Utils\get_tables(); /** * Handle url replacements */ if ( ! empty( $snapshot->meta['sites'] ) ) { Log::instance()->write( 'Preparing to replace URLs...' ); $site_mapping = []; $site_mapping_raw = $input->getOption( 'site_mapping' ); if ( ! empty( $site_mapping_raw ) ) { $site_mapping_raw = json_decode( $site_mapping_raw, true ); foreach ( $site_mapping_raw as $site ) { if ( ! empty( $site['blog_id'] ) ) { $site_mapping[ (int) $site['blog_id'] ] = $site; } else { $site_mapping[] = $site; } } if ( 1 >= count( $site_mapping ) ) { $site_mapping = array_values( $site_mapping ); } } $url_validator = function( $answer ) { if ( '' === trim( $answer ) || false !== strpos( $answer, ' ' ) || ! preg_match( '#https?:#i', $answer ) ) { throw new \RuntimeException( 'URL is not valid. Should be prefixed with http(s) and contain no spaces.' ); } return $answer; }; $skip_table_search_replace = $input->getOption( 'skip_table_search_replace' ); if ( empty( $skip_table_search_replace ) ) { $skip_table_search_replace = [ 'terms', 'term_relationships', 'term_taxonomy', ]; } if ( ! empty( $snapshot->meta['multisite'] ) ) { $used_home_urls = []; $used_site_urls = []; $skip_table_search_replace = array_merge( [ 'site', 'blogs' ], $skip_table_search_replace ); // Make WP realize we are in multisite now if ( ! defined( 'MULTISITE' ) ) { define( 'MULTISITE', true ); } if ( empty( $snapshot->meta['subdomain_install'] ) ) { Log::instance()->write( 'Multisite installation (path based install) detected.' ); } else { Log::instance()->write( 'Multisite installation (subdomain based install) detected.' ); } $i = 0; /** * First handle multisite intricacies. We need to set domains and paths for each blog. We'll copy * whatever the current path is. However, the user needs to set the domain for every blog. For * path based installed we just use the first domain. */ $main_domain = $input->getOption( 'main_domain' ); $snapshot_main_domain = ( ! empty( $snapshot->meta['domain_current_site'] ) ) ? $snapshot->meta['domain_current_site'] : ''; if ( ! empty( $snapshot_main_domain ) ) { $main_domain_question = new Question( 'Main domain (defaults to main domain in the snapshot: ' . $snapshot_main_domain . '): ', $snapshot_main_domain ); } else { $example_site = 'mysite.test'; if ( ! empty( $snapshot->meta['sites'][0]['home_url'] ) ) { $example_site = parse_url( $snapshot->meta['sites'][0]['home_url'], PHP_URL_HOST ); } $main_domain_question = new Question( 'Main domain (' . $example_site . ' for example): ' ); } $main_domain_question->setValidator( function( $answer ) { if ( '' === trim( $answer ) || false !== strpos( $answer, ' ' ) || preg_match( '#https?:#i', $answer ) ) { throw new \RuntimeException( 'Domain not valid. The domain should be in the form of `google.com`, no https:// needed' ); } return $answer; } ); if ( empty( $main_domain ) ) { $main_domain = $helper->ask( $input, $output, $main_domain_question ); } foreach ( $snapshot->meta['sites'] as $site ) { Log::instance()->write( 'Replacing URLs for blog ' . $site['blog_id'] . '.' ); if ( ! empty( $site_mapping[ (int) $site['blog_id'] ] ) ) { $new_home_url = $site_mapping[ (int) $site['blog_id'] ]['home_url']; $new_site_url = $site_mapping[ (int) $site['blog_id'] ]['site_url']; } else { $home_question = new Question( 'Home URL (defaults home URL in snapshot: ' . $site['home_url'] . '): ', $site['home_url'] ); $home_question->setValidator( $url_validator ); $new_home_url = $helper->ask( $input, $output, $home_question ); while ( in_array( $new_home_url, $used_home_urls, true ) ) { Log::instance()->write( 'Sorry, that home URL is already taken by another site.', 0, 'error' ); $home_question = new Question( 'Home URL (defaults to home URL in snapshot: ' . $site['home_url'] . '): ', $site['home_url'] ); $home_question->setValidator( $url_validator ); $new_home_url = $helper->ask( $input, $output, $home_question ); } $site_question = new Question( 'Site URL (defaults to site URL in snapshot: ' . $site['site_url'] . '): ', $site['site_url'] ); $site_question->setValidator( $url_validator ); $new_site_url = $helper->ask( $input, $output, $site_question ); while ( in_array( $new_site_url, $used_site_urls, true ) ) { Log::instance()->write( 'Sorry, that site URL is already taken by another site.', 0, 'error' ); $site_question = new Question( 'Site URL (defaults to site URL in snapshot: ' . $site['site_url'] . '): ', $site['site_url'] ); $site_question->setValidator( $url_validator ); $new_site_url = $helper->ask( $input, $output, $site_question ); } } if ( empty( $first_home_url ) ) { $first_home_url = $new_home_url; } $used_home_urls[] = $new_home_url; $used_site_urls[] = $new_site_url; Log::instance()->write( 'Updating blogs table...', 1 ); $blog_path = trailingslashit( parse_url( $new_home_url, PHP_URL_PATH ) ); if ( empty( $blog_path ) ) { $blog_path = '/'; } $blog_url = parse_url( $new_home_url, PHP_URL_HOST ); if ( ! empty( parse_url( $new_home_url, PHP_URL_PORT ) ) ) { $blog_url .= ':' . parse_url( $new_home_url, PHP_URL_PORT ); } /** * Update multisite stuff for each blog */ $wpdb->query( $wpdb->prepare( 'UPDATE ' . $current_table_prefix . 'blogs SET path=%s, domain=%s WHERE blog_id=%d', $blog_path, $blog_url, (int) $site['blog_id'] ) ); /** * Update all tables except wp_site and wp_blog since we handle that separately */ $tables_to_update = []; foreach ( $wp_tables as $table ) { if ( 1 === (int) $site['blog_id'] ) { if ( preg_match( '#^' . $current_table_prefix . '#', $table ) && ! preg_match( '#^' . $current_table_prefix . '[0-9]+_#', $table ) ) { if ( ! in_array( str_replace( $current_table_prefix, '', $table ), $skip_table_search_replace ) ) { $tables_to_update[] = $table; } } } else { if ( preg_match( '#^' . $current_table_prefix . $site['blog_id'] . '_#', $table ) ) { $raw_table = str_replace( $current_table_prefix . $site['blog_id'] . '_', '', $table ); if ( ! in_array( $raw_table, $skip_table_search_replace ) ) { $tables_to_update[] = $table; } } } } if ( ! empty( $tables_to_update ) ) { Log::instance()->write( 'Running replacement... This may take awhile depending on the size of the database.' ); Log::instance()->write( 'Search and replacing tables: ' . implode( ', ', $tables_to_update ), 1 ); new SearchReplace( $site['home_url'], $new_home_url, $tables_to_update ); if ( $site['home_url'] !== $site['site_url'] ) { new SearchReplace( $site['site_url'], $new_site_url, $tables_to_update ); } } $i++; } Log::instance()->write( 'Updating site table...', 1 ); /** * Update site domain with main domain */ $wpdb->query( $wpdb->prepare( 'UPDATE ' . $current_table_prefix . 'site SET domain=%s', $main_domain ) ); Log::instance()->write( 'URLs replaced.' ); if ( ! defined( 'BLOG_ID_CURRENT_SITE' ) || ( ! empty( $snapshot->meta['blog_id_current_site'] ) && BLOG_ID_CURRENT_SITE !== (int) $snapshot->meta['blog_id_current_site'] ) || ! defined( 'SITE_ID_CURRENT_SITE' ) || ( ! empty( $snapshot->meta['site_id_current_site'] ) && SITE_ID_CURRENT_SITE !== (int) $snapshot->meta['site_id_current_site'] ) || ! defined( 'PATH_CURRENT_SITE' ) || ( ! empty( $snapshot->meta['path_current_site'] ) && PATH_CURRENT_SITE !== $snapshot->meta['path_current_site'] ) || ! defined( 'MULTISITE' ) || ! MULTISITE || ! defined( 'DOMAIN_CURRENT_SITE' ) || DOMAIN_CURRENT_SITE !== $main_domain || ! defined( 'SUBDOMAIN_INSTALL' ) || SUBDOMAIN_INSTALL !== $snapshot->meta['subdomain_install'] ) { $update_ms_constants = $input->getOption( 'confirm_ms_constant_update' ); if ( ! $update_ms_constants ) { $update_ms_constants = $helper->ask( $input, $output, new ConfirmationQuestion( 'Constants need to be updated in your wp-config.php file. Want WP Snapshots to do this automatically? (yes|no) ', true ) ); } if ( ! $update_ms_constants ) { Log::instance()->write( 'The following code should be in your wp-config.php file:', 0, 'warning' ); Log::instance()->write( "define('WP_ALLOW_MULTISITE', true); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', " . ( ( ! empty( $snapshot->meta['subdomain_install'] ) ) ? 'true' : 'false' ) . "); define('DOMAIN_CURRENT_SITE', '" . $main_domain . "'); define('PATH_CURRENT_SITE', '" . ( ( ! empty( $snapshot->meta['path_current_site'] ) ) ? $snapshot->meta['path_current_site'] : '/' ) . "'); define('SITE_ID_CURRENT_SITE', " . ( ( ! empty( $snapshot->meta['site_id_current_site'] ) ) ? $snapshot->meta['site_id_current_site'] : '1' ) . "); define('BLOG_ID_CURRENT_SITE', " . ( ( ! empty( $snapshot->meta['blog_id_current_site'] ) ) ? $snapshot->meta['blog_id_current_site'] : '1' ) . ');', 0, 'success' ); } else { Utils\write_constants_to_wp_config( [ 'WP_ALLOW_MULTISITE' => true, 'MULTISITE' => true, 'SUBDOMAIN_INSTALL' => ( ! empty( $snapshot->meta['subdomain_install'] ) ) ? true : false, 'DOMAIN_CURRENT_SITE' => $main_domain, 'PATH_CURRENT_SITE' => ( ! empty( $snapshot->meta['path_current_site'] ) ) ? $snapshot->meta['path_current_site'] : '/', 'SITE_ID_CURRENT_SITE' => ( ! empty( $snapshot->meta['site_id_current_site'] ) ) ? $snapshot->meta['site_id_current_site'] : 1, 'BLOG_ID_CURRENT_SITE' => ( ! empty( $snapshot->meta['blog_id_current_site'] ) ) ? $snapshot->meta['blog_id_current_site'] : 1, ], $path . 'wp-config.php' ); Log::instance()->write( 'Multisite constants added to wp-config.php.' ); } } } else { if ( ! empty( $site_mapping ) ) { $new_home_url = $site_mapping[0]['home_url']; $new_site_url = $site_mapping[0]['site_url']; } else { $home_question = new Question( 'Home URL (defaults to home URL in snapshot: ' . $snapshot->meta['sites'][0]['home_url'] . '): ', $snapshot->meta['sites'][0]['home_url'] ); $home_question->setValidator( $url_validator ); $new_home_url = $helper->ask( $input, $output, $home_question ); $site_question = new Question( 'Site URL (defaults to site URL in snapshot: ' . $snapshot->meta['sites'][0]['site_url'] . '): ', $snapshot->meta['sites'][0]['site_url'] ); $site_question->setValidator( $url_validator ); $new_site_url = $helper->ask( $input, $output, $site_question ); } $first_home_url = $new_home_url; Log::instance()->write( 'Running replacement... This may take awhile depending on the size of the database.' ); $tables_to_update = []; foreach ( $wp_tables as $table ) { $raw_table = str_replace( $current_table_prefix, '', $table ); if ( ! in_array( $raw_table, $skip_table_search_replace ) ) { $tables_to_update[] = $table; } } Log::instance()->write( 'Search and replacing tables: ' . implode( ', ', $tables_to_update ), 1 ); new SearchReplace( $snapshot->meta['sites'][0]['home_url'], $new_home_url, $tables_to_update ); if ( $snapshot->meta['sites'][0]['home_url'] !== $snapshot->meta['sites'][0]['site_url'] ) { new SearchReplace( $snapshot->meta['sites'][0]['site_url'], $new_site_url, $tables_to_update ); } Log::instance()->write( 'URLs replaced.' ); } } /** * Cleaning up decompressed files */ Log::instance()->write( 'Cleaning up temporary files...', 1 ); @unlink( $snapshot_path . 'wp.tar.gz' ); @unlink( $snapshot_path . 'data.sql' ); /** * Create wpsnapshots user */ Log::instance()->write( 'Cleaning wpsnapshots user...', 1 ); $user = get_user_by( 'login', 'wpsnapshots' ); $user_args = [ 'user_login' => 'wpsnapshots', 'user_pass' => 'password', 'user_email' => 'wpsnapshots@wpsnapshots.test', 'role' => 'administrator', ]; if ( ! empty( $user ) ) { $user_args['ID'] = $user->ID; $user_args['user_pass'] = wp_hash_password( 'password' ); } $user_id = wp_insert_user( $user_args ); if ( ! empty( $snapshot->meta['multisite'] ) ) { $site_admins_rows = $wpdb->get_results( 'SELECT * FROM ' . Utils\esc_sql_name( $current_table_prefix . 'sitemeta' ) . ' WHERE meta_key="site_admins"', ARRAY_A ); if ( ! empty( $site_admins_rows ) ) { foreach ( $site_admins_rows as $site_admin_row ) { $admins = unserialize( $site_admin_row['meta_value'] ); $admins[] = 'wpsnapshots'; $wpdb->update( $current_table_prefix . 'sitemeta', [ 'meta_value' => serialize( array_unique( $admins ) ), ], [ 'meta_id' => $site_admin_row['meta_id'], ] ); } } } Log::instance()->write( 'Pull finished.', 0, 'success' ); Log::instance()->write( 'Visit in your browser: ' . $first_home_url, 0, 'success' ); if ( 'localhost' !== parse_url( $first_home_url, PHP_URL_HOST ) ) { Log::instance()->write( 'Make sure the following entry is in your hosts file: ' . parse_url( $first_home_url, PHP_URL_HOST ) . ' 127.0.0.1', 0, 'success' ); } Log::instance()->write( 'Admin login: username - "wpsnapshots", password - "password"', 0, 'success' ); }
php
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $id = $input->getArgument( 'snapshot_id' ); $path = $input->getOption( 'path' ); if ( empty( $path ) ) { $path = getcwd(); } $path = Utils\normalize_path( $path ); $snapshot_path = Utils\get_snapshot_directory() . $id . '/'; $snapshot = Snapshot::download( $id, $repository->getName() ); if ( ! is_a( $snapshot, '\WPSnapshots\Snapshot' ) ) { return 1; } $verbose = $input->getOption( 'verbose' ); $verbose_pipe = ( ! $verbose ) ? '> /dev/null' : ''; $helper = $this->getHelper( 'question' ); if ( ! Utils\is_wp_present( $path ) ) { Log::instance()->write( 'This is not a WordPress install. WordPress needs to be present in order to pull a snapshot.', 0, 'error' ); if ( empty( $input->getOption( 'confirm_wp_download' ) ) ) { $download_wp = $helper->ask( $input, $output, new ConfirmationQuestion( 'Do you want to download WordPress? (yes|no) ', false ) ); if ( ! $download_wp ) { return 1; } } /** * Download WordPress core files */ Log::instance()->write( 'Getting WordPress download URL...', 1 ); $download_url = Utils\get_download_url(); $headers = [ 'Accept' => 'application/json' ]; $options = [ 'timeout' => 600, 'filename' => $snapshot_path . 'wp.tar.gz', ]; Log::instance()->write( 'Downloading WordPress...', 1 ); $request = Requests::get( $download_url, $headers, $options ); Log::instance()->write( 'Extracting WordPress...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress && tar -C ' . Utils\escape_shell_path( $path ) . ' -xf ' . Utils\escape_shell_path( $snapshot_path ) . 'wp.tar.gz ' . $verbose_pipe ); Log::instance()->write( 'Moving WordPress files...', 1 ); exec( 'mv ' . Utils\escape_shell_path( $path ) . 'wordpress/* .' ); Log::instance()->write( 'Removing temporary WordPress files...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress' ); Log::instance()->write( 'WordPress downloaded.' ); } if ( ! Utils\locate_wp_config( $path ) ) { Log::instance()->write( 'No wp-config.php file present. wp-config.php needs to be setup in order to pull a snapshot.', 0, 'error' ); if ( empty( $input->getOption( 'confirm_config_create' ) ) ) { $create_config = $helper->ask( $input, $output, new ConfirmationQuestion( 'Do you want to create a wp-config.php file? (yes|no) ', false ) ); if ( ! $create_config ) { return 1; } } $config_constants = []; if ( ! empty( $input->getOption( 'config_db_host' ) ) ) { $config_constants['DB_HOST'] = $input->getOption( 'config_db_host' ); } else { $db_host_question = new Question( 'What is your database host? ' ); $db_host_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_HOST'] = $helper->ask( $input, $output, $db_host_question ); } if ( ! empty( $input->getOption( 'config_db_name' ) ) ) { $config_constants['DB_NAME'] = $input->getOption( 'config_db_name' ); } else { $db_name_question = new Question( 'What is your database name? ' ); $db_name_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_NAME'] = $helper->ask( $input, $output, $db_name_question ); } if ( ! empty( $input->getOption( 'config_db_user' ) ) ) { $config_constants['DB_USER'] = $input->getOption( 'config_db_user' ); } else { $db_user_question = new Question( 'What is your database user? ' ); $db_user_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_USER'] = $helper->ask( $input, $output, $db_user_question ); } if ( ! empty( $input->getOption( 'config_db_password' ) ) ) { $config_constants['DB_PASSWORD'] = $input->getOption( 'config_db_password' ); } else { $db_password_question = new Question( 'What is your database password? ' ); $db_password_question->setValidator( '\WPSnapshots\Utils\not_empty_validator' ); $config_constants['DB_PASSWORD'] = $helper->ask( $input, $output, $db_password_question ); } Log::instance()->write( 'Creating wp-config.php file...', 1 ); Utils\create_config_file( $path . 'wp-config.php', $path . 'wp-config-sample.php', $config_constants ); Log::instance()->write( 'wp-config.php created.' ); } $extra_config_constants = [ 'WP_CACHE' => false, ]; $db_host = $input->getOption( 'db_host' ); $db_name = $input->getOption( 'db_name' ); $db_user = $input->getOption( 'db_user' ); $db_password = $input->getOption( 'db_password' ); if ( ! empty( $db_host ) ) { $extra_config_constants['DB_HOST'] = $db_host; } if ( ! empty( $db_name ) ) { $extra_config_constants['DB_NAME'] = $db_name; } if ( ! empty( $db_user ) ) { $extra_config_constants['DB_USER'] = $db_user; } if ( ! empty( $db_password ) ) { $extra_config_constants['DB_PASSWORD'] = $db_password; } /** * Make sure we don't redirect if no tables exist */ define( 'WP_INSTALLING', true ); Log::instance()->write( 'Bootstrapping WordPress...', 1 ); if ( ! WordPressBridge::instance()->load( $path, $extra_config_constants ) ) { Log::instance()->write( 'Could not connect to WordPress database.', 0, 'error' ); return 1; } $pre_update_site_url = site_url(); $pre_update_home_url = home_url(); $use_https = false; if ( ! empty( $pre_update_site_url ) ) { $pre_update_site_url_parsed = parse_url( $pre_update_site_url ); if ( 'https' === $pre_update_site_url_parsed['scheme'] ) { $use_https = true; } } /** * We make the user double confirm since this could destroy a website */ $confirm = $input->getOption( 'confirm' ); if ( empty( $confirm ) ) { $confirm = $helper->ask( $input, $output, new ConfirmationQuestion( 'Are you sure you want to do this? This is a potentially destructive operation. You should run a back up first. (yes|no) ', false ) ); if ( ! $confirm ) { return 1; } } Log::instance()->write( 'Decompressing database backup file...' ); exec( 'cd ' . Utils\escape_shell_path( $snapshot_path ) . ' && gzip -d -k -f data.sql.gz ' . $verbose_pipe ); Log::instance()->write( 'Replacing wp-content/...' ); Log::instance()->write( 'wp-content path set to ' . WP_CONTENT_DIR, 1 ); Log::instance()->write( 'Removing old wp-content/...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . '/..?* ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . '/.[!.]* ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . '/*' ); Log::instance()->write( 'Extracting snapshot wp-content/...', 1 ); exec( 'mkdir -p ' . Utils\escape_shell_path( WP_CONTENT_DIR ) ); exec( 'tar -C ' . Utils\escape_shell_path( WP_CONTENT_DIR ) . ' -xf ' . Utils\escape_shell_path( $snapshot_path ) . 'files.tar.gz ' . $verbose_pipe ); /** * Import tables */ $args = array( 'host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASSWORD, 'database' => DB_NAME, 'execute' => 'SET GLOBAL max_allowed_packet=51200000;', ); Log::instance()->write( 'Attempting to set max_allowed_packet...', 1 ); $command_result = Utils\run_mysql_command( 'mysql --no-defaults --no-auto-rehash', $args, '', false ); if ( 0 !== $command_result ) { Log::instance()->write( 'Could not set MySQL max_allowed_packet. If MySQL import fails, try running WP Snapshots using root DB user.', 0, 'warning' ); } Log::instance()->write( 'Updating database. This may take awhile depending on the size of the database (' . Utils\format_bytes( filesize( $snapshot_path . 'data.sql' ) ) . ')...' ); $query = 'SET autocommit = 0; SET unique_checks = 0; SET foreign_key_checks = 0; SOURCE %s; COMMIT;'; $args = array( 'host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASSWORD, 'database' => DB_NAME, 'execute' => sprintf( $query, $snapshot_path . 'data.sql' ), ); if ( ! isset( $assoc_args['default-character-set'] ) && defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) { $args['default-character-set'] = constant( 'DB_CHARSET' ); } Utils\run_mysql_command( 'mysql --no-defaults --no-auto-rehash', $args ); /** * Customize DB for current install */ Log::instance()->write( 'Getting MySQL tables...', 1 ); $all_tables = Utils\get_tables( false ); global $wpdb; $main_blog_id = ( defined( 'BLOG_ID_CURRENT_SITE' ) ) ? BLOG_ID_CURRENT_SITE : null; $current_table_prefix = $wpdb->get_blog_prefix( $main_blog_id ); /** * First update table prefixes */ if ( ! empty( $snapshot->meta['table_prefix'] ) && ! empty( $current_table_prefix ) && $snapshot->meta['table_prefix'] !== $current_table_prefix ) { Log::instance()->write( 'Renaming WordPress tables...' ); foreach ( $all_tables as $table ) { if ( 0 === strpos( $table, $snapshot->meta['table_prefix'] ) ) { /** * Update this table to use the current config prefix */ $new_table = $current_table_prefix . str_replace( $snapshot->meta['table_prefix'], '', $table ); $wpdb->query( sprintf( 'RENAME TABLE `%s` TO `%s`', esc_sql( $table ), esc_sql( $new_table ) ) ); } } } global $wp_version; if ( ! empty( $snapshot->meta['wp_version'] ) && $snapshot->meta['wp_version'] !== $wp_version ) { $confirm_wp_version_change = $input->getOption( 'confirm_wp_version_change' ); $change_wp_version = true; if ( empty( $confirm_wp_version_change ) ) { $change_wp_version = $helper->ask( $input, $output, new ConfirmationQuestion( 'This snapshot is running WordPress version ' . $snapshot->meta['wp_version'] . ', and you are running ' . $wp_version . '. Do you want to change your WordPress version to ' . $snapshot->meta['wp_version'] . '? (yes|no) ', true ) ); } if ( ! empty( $change_wp_version ) ) { // Delete old WordPress exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wp-includes ' . Utils\escape_shell_path( $path ) . 'wp-admin' ); exec( 'cd ' . Utils\escape_shell_path( $path ) . ' && rm index.php && rm xmlrpc.php && rm license.txt && rm readme.html' ); exec( 'cd ' . Utils\escape_shell_path( $path ) . ' && find . -maxdepth 1 ! -path . -type f -name "wp-*.php" ! -iname "wp-config.php" -delete' ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress' ); Log::instance()->write( 'Getting WordPress download URL...', 1 ); $download_url = Utils\get_download_url( $snapshot->meta['wp_version'] ); $headers = [ 'Accept' => 'application/json' ]; $options = [ 'timeout' => 600, 'filename' => $snapshot_path . 'wp.tar.gz', ]; Log::instance()->write( 'Downloading WordPress ' . $snapshot->meta['wp_version'] . '...', 1 ); $request = Requests::get( $download_url, $headers, $options ); Log::instance()->write( 'Extracting WordPress...', 1 ); exec( 'tar -C ' . Utils\escape_shell_path( $path ) . ' -xf ' . Utils\escape_shell_path( $snapshot_path ) . 'wp.tar.gz ' . $verbose_pipe ); Log::instance()->write( 'Moving WordPress files...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress/wp-content && mv ' . Utils\escape_shell_path( $path ) . 'wordpress/* .' ); Log::instance()->write( 'Removing temporary WordPress files...', 1 ); exec( 'rm -rf ' . Utils\escape_shell_path( $path ) . 'wordpress' ); Log::instance()->write( 'WordPress version changed.' ); } } /** * Get tables again since it could have changed */ $wp_tables = Utils\get_tables(); /** * Handle url replacements */ if ( ! empty( $snapshot->meta['sites'] ) ) { Log::instance()->write( 'Preparing to replace URLs...' ); $site_mapping = []; $site_mapping_raw = $input->getOption( 'site_mapping' ); if ( ! empty( $site_mapping_raw ) ) { $site_mapping_raw = json_decode( $site_mapping_raw, true ); foreach ( $site_mapping_raw as $site ) { if ( ! empty( $site['blog_id'] ) ) { $site_mapping[ (int) $site['blog_id'] ] = $site; } else { $site_mapping[] = $site; } } if ( 1 >= count( $site_mapping ) ) { $site_mapping = array_values( $site_mapping ); } } $url_validator = function( $answer ) { if ( '' === trim( $answer ) || false !== strpos( $answer, ' ' ) || ! preg_match( '#https?:#i', $answer ) ) { throw new \RuntimeException( 'URL is not valid. Should be prefixed with http(s) and contain no spaces.' ); } return $answer; }; $skip_table_search_replace = $input->getOption( 'skip_table_search_replace' ); if ( empty( $skip_table_search_replace ) ) { $skip_table_search_replace = [ 'terms', 'term_relationships', 'term_taxonomy', ]; } if ( ! empty( $snapshot->meta['multisite'] ) ) { $used_home_urls = []; $used_site_urls = []; $skip_table_search_replace = array_merge( [ 'site', 'blogs' ], $skip_table_search_replace ); // Make WP realize we are in multisite now if ( ! defined( 'MULTISITE' ) ) { define( 'MULTISITE', true ); } if ( empty( $snapshot->meta['subdomain_install'] ) ) { Log::instance()->write( 'Multisite installation (path based install) detected.' ); } else { Log::instance()->write( 'Multisite installation (subdomain based install) detected.' ); } $i = 0; /** * First handle multisite intricacies. We need to set domains and paths for each blog. We'll copy * whatever the current path is. However, the user needs to set the domain for every blog. For * path based installed we just use the first domain. */ $main_domain = $input->getOption( 'main_domain' ); $snapshot_main_domain = ( ! empty( $snapshot->meta['domain_current_site'] ) ) ? $snapshot->meta['domain_current_site'] : ''; if ( ! empty( $snapshot_main_domain ) ) { $main_domain_question = new Question( 'Main domain (defaults to main domain in the snapshot: ' . $snapshot_main_domain . '): ', $snapshot_main_domain ); } else { $example_site = 'mysite.test'; if ( ! empty( $snapshot->meta['sites'][0]['home_url'] ) ) { $example_site = parse_url( $snapshot->meta['sites'][0]['home_url'], PHP_URL_HOST ); } $main_domain_question = new Question( 'Main domain (' . $example_site . ' for example): ' ); } $main_domain_question->setValidator( function( $answer ) { if ( '' === trim( $answer ) || false !== strpos( $answer, ' ' ) || preg_match( '#https?:#i', $answer ) ) { throw new \RuntimeException( 'Domain not valid. The domain should be in the form of `google.com`, no https:// needed' ); } return $answer; } ); if ( empty( $main_domain ) ) { $main_domain = $helper->ask( $input, $output, $main_domain_question ); } foreach ( $snapshot->meta['sites'] as $site ) { Log::instance()->write( 'Replacing URLs for blog ' . $site['blog_id'] . '.' ); if ( ! empty( $site_mapping[ (int) $site['blog_id'] ] ) ) { $new_home_url = $site_mapping[ (int) $site['blog_id'] ]['home_url']; $new_site_url = $site_mapping[ (int) $site['blog_id'] ]['site_url']; } else { $home_question = new Question( 'Home URL (defaults home URL in snapshot: ' . $site['home_url'] . '): ', $site['home_url'] ); $home_question->setValidator( $url_validator ); $new_home_url = $helper->ask( $input, $output, $home_question ); while ( in_array( $new_home_url, $used_home_urls, true ) ) { Log::instance()->write( 'Sorry, that home URL is already taken by another site.', 0, 'error' ); $home_question = new Question( 'Home URL (defaults to home URL in snapshot: ' . $site['home_url'] . '): ', $site['home_url'] ); $home_question->setValidator( $url_validator ); $new_home_url = $helper->ask( $input, $output, $home_question ); } $site_question = new Question( 'Site URL (defaults to site URL in snapshot: ' . $site['site_url'] . '): ', $site['site_url'] ); $site_question->setValidator( $url_validator ); $new_site_url = $helper->ask( $input, $output, $site_question ); while ( in_array( $new_site_url, $used_site_urls, true ) ) { Log::instance()->write( 'Sorry, that site URL is already taken by another site.', 0, 'error' ); $site_question = new Question( 'Site URL (defaults to site URL in snapshot: ' . $site['site_url'] . '): ', $site['site_url'] ); $site_question->setValidator( $url_validator ); $new_site_url = $helper->ask( $input, $output, $site_question ); } } if ( empty( $first_home_url ) ) { $first_home_url = $new_home_url; } $used_home_urls[] = $new_home_url; $used_site_urls[] = $new_site_url; Log::instance()->write( 'Updating blogs table...', 1 ); $blog_path = trailingslashit( parse_url( $new_home_url, PHP_URL_PATH ) ); if ( empty( $blog_path ) ) { $blog_path = '/'; } $blog_url = parse_url( $new_home_url, PHP_URL_HOST ); if ( ! empty( parse_url( $new_home_url, PHP_URL_PORT ) ) ) { $blog_url .= ':' . parse_url( $new_home_url, PHP_URL_PORT ); } /** * Update multisite stuff for each blog */ $wpdb->query( $wpdb->prepare( 'UPDATE ' . $current_table_prefix . 'blogs SET path=%s, domain=%s WHERE blog_id=%d', $blog_path, $blog_url, (int) $site['blog_id'] ) ); /** * Update all tables except wp_site and wp_blog since we handle that separately */ $tables_to_update = []; foreach ( $wp_tables as $table ) { if ( 1 === (int) $site['blog_id'] ) { if ( preg_match( '#^' . $current_table_prefix . '#', $table ) && ! preg_match( '#^' . $current_table_prefix . '[0-9]+_#', $table ) ) { if ( ! in_array( str_replace( $current_table_prefix, '', $table ), $skip_table_search_replace ) ) { $tables_to_update[] = $table; } } } else { if ( preg_match( '#^' . $current_table_prefix . $site['blog_id'] . '_#', $table ) ) { $raw_table = str_replace( $current_table_prefix . $site['blog_id'] . '_', '', $table ); if ( ! in_array( $raw_table, $skip_table_search_replace ) ) { $tables_to_update[] = $table; } } } } if ( ! empty( $tables_to_update ) ) { Log::instance()->write( 'Running replacement... This may take awhile depending on the size of the database.' ); Log::instance()->write( 'Search and replacing tables: ' . implode( ', ', $tables_to_update ), 1 ); new SearchReplace( $site['home_url'], $new_home_url, $tables_to_update ); if ( $site['home_url'] !== $site['site_url'] ) { new SearchReplace( $site['site_url'], $new_site_url, $tables_to_update ); } } $i++; } Log::instance()->write( 'Updating site table...', 1 ); /** * Update site domain with main domain */ $wpdb->query( $wpdb->prepare( 'UPDATE ' . $current_table_prefix . 'site SET domain=%s', $main_domain ) ); Log::instance()->write( 'URLs replaced.' ); if ( ! defined( 'BLOG_ID_CURRENT_SITE' ) || ( ! empty( $snapshot->meta['blog_id_current_site'] ) && BLOG_ID_CURRENT_SITE !== (int) $snapshot->meta['blog_id_current_site'] ) || ! defined( 'SITE_ID_CURRENT_SITE' ) || ( ! empty( $snapshot->meta['site_id_current_site'] ) && SITE_ID_CURRENT_SITE !== (int) $snapshot->meta['site_id_current_site'] ) || ! defined( 'PATH_CURRENT_SITE' ) || ( ! empty( $snapshot->meta['path_current_site'] ) && PATH_CURRENT_SITE !== $snapshot->meta['path_current_site'] ) || ! defined( 'MULTISITE' ) || ! MULTISITE || ! defined( 'DOMAIN_CURRENT_SITE' ) || DOMAIN_CURRENT_SITE !== $main_domain || ! defined( 'SUBDOMAIN_INSTALL' ) || SUBDOMAIN_INSTALL !== $snapshot->meta['subdomain_install'] ) { $update_ms_constants = $input->getOption( 'confirm_ms_constant_update' ); if ( ! $update_ms_constants ) { $update_ms_constants = $helper->ask( $input, $output, new ConfirmationQuestion( 'Constants need to be updated in your wp-config.php file. Want WP Snapshots to do this automatically? (yes|no) ', true ) ); } if ( ! $update_ms_constants ) { Log::instance()->write( 'The following code should be in your wp-config.php file:', 0, 'warning' ); Log::instance()->write( "define('WP_ALLOW_MULTISITE', true); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', " . ( ( ! empty( $snapshot->meta['subdomain_install'] ) ) ? 'true' : 'false' ) . "); define('DOMAIN_CURRENT_SITE', '" . $main_domain . "'); define('PATH_CURRENT_SITE', '" . ( ( ! empty( $snapshot->meta['path_current_site'] ) ) ? $snapshot->meta['path_current_site'] : '/' ) . "'); define('SITE_ID_CURRENT_SITE', " . ( ( ! empty( $snapshot->meta['site_id_current_site'] ) ) ? $snapshot->meta['site_id_current_site'] : '1' ) . "); define('BLOG_ID_CURRENT_SITE', " . ( ( ! empty( $snapshot->meta['blog_id_current_site'] ) ) ? $snapshot->meta['blog_id_current_site'] : '1' ) . ');', 0, 'success' ); } else { Utils\write_constants_to_wp_config( [ 'WP_ALLOW_MULTISITE' => true, 'MULTISITE' => true, 'SUBDOMAIN_INSTALL' => ( ! empty( $snapshot->meta['subdomain_install'] ) ) ? true : false, 'DOMAIN_CURRENT_SITE' => $main_domain, 'PATH_CURRENT_SITE' => ( ! empty( $snapshot->meta['path_current_site'] ) ) ? $snapshot->meta['path_current_site'] : '/', 'SITE_ID_CURRENT_SITE' => ( ! empty( $snapshot->meta['site_id_current_site'] ) ) ? $snapshot->meta['site_id_current_site'] : 1, 'BLOG_ID_CURRENT_SITE' => ( ! empty( $snapshot->meta['blog_id_current_site'] ) ) ? $snapshot->meta['blog_id_current_site'] : 1, ], $path . 'wp-config.php' ); Log::instance()->write( 'Multisite constants added to wp-config.php.' ); } } } else { if ( ! empty( $site_mapping ) ) { $new_home_url = $site_mapping[0]['home_url']; $new_site_url = $site_mapping[0]['site_url']; } else { $home_question = new Question( 'Home URL (defaults to home URL in snapshot: ' . $snapshot->meta['sites'][0]['home_url'] . '): ', $snapshot->meta['sites'][0]['home_url'] ); $home_question->setValidator( $url_validator ); $new_home_url = $helper->ask( $input, $output, $home_question ); $site_question = new Question( 'Site URL (defaults to site URL in snapshot: ' . $snapshot->meta['sites'][0]['site_url'] . '): ', $snapshot->meta['sites'][0]['site_url'] ); $site_question->setValidator( $url_validator ); $new_site_url = $helper->ask( $input, $output, $site_question ); } $first_home_url = $new_home_url; Log::instance()->write( 'Running replacement... This may take awhile depending on the size of the database.' ); $tables_to_update = []; foreach ( $wp_tables as $table ) { $raw_table = str_replace( $current_table_prefix, '', $table ); if ( ! in_array( $raw_table, $skip_table_search_replace ) ) { $tables_to_update[] = $table; } } Log::instance()->write( 'Search and replacing tables: ' . implode( ', ', $tables_to_update ), 1 ); new SearchReplace( $snapshot->meta['sites'][0]['home_url'], $new_home_url, $tables_to_update ); if ( $snapshot->meta['sites'][0]['home_url'] !== $snapshot->meta['sites'][0]['site_url'] ) { new SearchReplace( $snapshot->meta['sites'][0]['site_url'], $new_site_url, $tables_to_update ); } Log::instance()->write( 'URLs replaced.' ); } } /** * Cleaning up decompressed files */ Log::instance()->write( 'Cleaning up temporary files...', 1 ); @unlink( $snapshot_path . 'wp.tar.gz' ); @unlink( $snapshot_path . 'data.sql' ); /** * Create wpsnapshots user */ Log::instance()->write( 'Cleaning wpsnapshots user...', 1 ); $user = get_user_by( 'login', 'wpsnapshots' ); $user_args = [ 'user_login' => 'wpsnapshots', 'user_pass' => 'password', 'user_email' => 'wpsnapshots@wpsnapshots.test', 'role' => 'administrator', ]; if ( ! empty( $user ) ) { $user_args['ID'] = $user->ID; $user_args['user_pass'] = wp_hash_password( 'password' ); } $user_id = wp_insert_user( $user_args ); if ( ! empty( $snapshot->meta['multisite'] ) ) { $site_admins_rows = $wpdb->get_results( 'SELECT * FROM ' . Utils\esc_sql_name( $current_table_prefix . 'sitemeta' ) . ' WHERE meta_key="site_admins"', ARRAY_A ); if ( ! empty( $site_admins_rows ) ) { foreach ( $site_admins_rows as $site_admin_row ) { $admins = unserialize( $site_admin_row['meta_value'] ); $admins[] = 'wpsnapshots'; $wpdb->update( $current_table_prefix . 'sitemeta', [ 'meta_value' => serialize( array_unique( $admins ) ), ], [ 'meta_id' => $site_admin_row['meta_id'], ] ); } } } Log::instance()->write( 'Pull finished.', 0, 'success' ); Log::instance()->write( 'Visit in your browser: ' . $first_home_url, 0, 'success' ); if ( 'localhost' !== parse_url( $first_home_url, PHP_URL_HOST ) ) { Log::instance()->write( 'Make sure the following entry is in your hosts file: ' . parse_url( $first_home_url, PHP_URL_HOST ) . ' 127.0.0.1', 0, 'success' ); } Log::instance()->write( 'Admin login: username - "wpsnapshots", password - "password"', 0, 'success' ); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "Log", "::", "instance", "(", ")", "->", "setOutput", "(", "$", "output", ")", ";", "$", "repository", "=", "RepositoryManager", "::", ...
Executes the command @param InputInterface $input Console input @param OutputInterface $output Console output
[ "Executes", "the", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Pull.php#L85-L778
10up/wpsnapshots
src/classes/Command/Search.php
Search.execute
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $instances = $repository->getDB()->search( $input->getArgument( 'search_text' ) ); if ( ! $instances ) { Log::instance()->write( 'An error occured while searching.', 0, 'success' ); } if ( empty( $instances ) ) { Log::instance()->write( 'No snapshots found.', 0, 'warning' ); return; } $table = new Table( $output ); $table->setHeaders( [ 'ID', 'Project', 'Description', 'Author', 'Size', 'Multisite', 'Created' ] ); $rows = []; foreach ( $instances as $instance ) { if ( empty( $instance['time'] ) ) { $instance['time'] = time(); } $rows[ $instance['time'] ] = [ 'id' => ( ! empty( $instance['id'] ) ) ? $instance['id'] : '', 'project' => ( ! empty( $instance['project'] ) ) ? $instance['project'] : '', 'description' => ( ! empty( $instance['description'] ) ) ? $instance['description'] : '', 'author' => ( ! empty( $instance['author']['name'] ) ) ? $instance['author']['name'] : '', 'size' => ( ! empty( $instance['size'] ) ) ? Utils\format_bytes( (int) $instance['size'] ) : '', 'multisite' => ( ! empty( $instance['multisite'] ) ) ? 'Yes' : 'No', 'created' => ( ! empty( $instance['time'] ) ) ? date( 'F j, Y, g:i a', $instance['time'] ) : '', ]; } ksort( $rows ); $table->setRows( $rows ); $table->render(); }
php
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $instances = $repository->getDB()->search( $input->getArgument( 'search_text' ) ); if ( ! $instances ) { Log::instance()->write( 'An error occured while searching.', 0, 'success' ); } if ( empty( $instances ) ) { Log::instance()->write( 'No snapshots found.', 0, 'warning' ); return; } $table = new Table( $output ); $table->setHeaders( [ 'ID', 'Project', 'Description', 'Author', 'Size', 'Multisite', 'Created' ] ); $rows = []; foreach ( $instances as $instance ) { if ( empty( $instance['time'] ) ) { $instance['time'] = time(); } $rows[ $instance['time'] ] = [ 'id' => ( ! empty( $instance['id'] ) ) ? $instance['id'] : '', 'project' => ( ! empty( $instance['project'] ) ) ? $instance['project'] : '', 'description' => ( ! empty( $instance['description'] ) ) ? $instance['description'] : '', 'author' => ( ! empty( $instance['author']['name'] ) ) ? $instance['author']['name'] : '', 'size' => ( ! empty( $instance['size'] ) ) ? Utils\format_bytes( (int) $instance['size'] ) : '', 'multisite' => ( ! empty( $instance['multisite'] ) ) ? 'Yes' : 'No', 'created' => ( ! empty( $instance['time'] ) ) ? date( 'F j, Y, g:i a', $instance['time'] ) : '', ]; } ksort( $rows ); $table->setRows( $rows ); $table->render(); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "Log", "::", "instance", "(", ")", "->", "setOutput", "(", "$", "output", ")", ";", "$", "repository", "=", "RepositoryManager", "::", ...
Executes the command @param InputInterface $input Command input @param OutputInterface $output Command output
[ "Executes", "the", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Search.php#L43-L90
10up/wpsnapshots
src/classes/Command/Delete.php
Delete.execute
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $id = $input->getArgument( 'snapshot_id' ); $snapshot = $repository->getDB()->getSnapshot( $id ); if ( ! $snapshot ) { Log::instance()->write( 'Could not get snapshot from database.', 0, 'error' ); return 1; } $files_result = $repository->getS3()->deleteSnapshot( $id, $snapshot['project'] ); if ( ! $files_result ) { Log::instance()->write( 'Could not delete snapshot.', 0, 'error' ); return 1; } $db_result = $repository->getDB()->deleteSnapshot( $id ); if ( ! $db_result ) { Log::instance()->write( 'Could not delete snapshot.', 0, 'error' ); return 1; } Log::instance()->write( 'Snapshot deleted.', 0, 'success' ); }
php
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $id = $input->getArgument( 'snapshot_id' ); $snapshot = $repository->getDB()->getSnapshot( $id ); if ( ! $snapshot ) { Log::instance()->write( 'Could not get snapshot from database.', 0, 'error' ); return 1; } $files_result = $repository->getS3()->deleteSnapshot( $id, $snapshot['project'] ); if ( ! $files_result ) { Log::instance()->write( 'Could not delete snapshot.', 0, 'error' ); return 1; } $db_result = $repository->getDB()->deleteSnapshot( $id ); if ( ! $db_result ) { Log::instance()->write( 'Could not delete snapshot.', 0, 'error' ); return 1; } Log::instance()->write( 'Snapshot deleted.', 0, 'success' ); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "Log", "::", "instance", "(", ")", "->", "setOutput", "(", "$", "output", ")", ";", "$", "repository", "=", "RepositoryManager", "::", ...
Execute command @param InputInterface $input Command input @param OutputInterface $output Command output
[ "Execute", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Delete.php#L43-L80
10up/wpsnapshots
src/classes/Command/Create.php
Create.configure
protected function configure() { $this->setName( 'create' ); $this->setDescription( 'Create a snapshot locally.' ); $this->addOption( 'exclude', false, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Exclude a file or directory from the snapshot.' ); $this->addOption( 'exclude_uploads', false, InputOption::VALUE_NONE, 'Exclude uploads from pushed snapshot.' ); $this->addOption( 'repository', null, InputOption::VALUE_REQUIRED, 'Repository to use. Defaults to first repository saved in config.' ); $this->addOption( 'no_scrub', false, InputOption::VALUE_NONE, "Don't scrub personal user data." ); $this->addOption( 'path', null, InputOption::VALUE_REQUIRED, 'Path to WordPress files.' ); $this->addOption( 'db_host', null, InputOption::VALUE_REQUIRED, 'Database host.' ); $this->addOption( 'db_name', null, InputOption::VALUE_REQUIRED, 'Database name.' ); $this->addOption( 'db_user', null, InputOption::VALUE_REQUIRED, 'Database user.' ); $this->addOption( 'db_password', null, InputOption::VALUE_REQUIRED, 'Database password.' ); }
php
protected function configure() { $this->setName( 'create' ); $this->setDescription( 'Create a snapshot locally.' ); $this->addOption( 'exclude', false, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Exclude a file or directory from the snapshot.' ); $this->addOption( 'exclude_uploads', false, InputOption::VALUE_NONE, 'Exclude uploads from pushed snapshot.' ); $this->addOption( 'repository', null, InputOption::VALUE_REQUIRED, 'Repository to use. Defaults to first repository saved in config.' ); $this->addOption( 'no_scrub', false, InputOption::VALUE_NONE, "Don't scrub personal user data." ); $this->addOption( 'path', null, InputOption::VALUE_REQUIRED, 'Path to WordPress files.' ); $this->addOption( 'db_host', null, InputOption::VALUE_REQUIRED, 'Database host.' ); $this->addOption( 'db_name', null, InputOption::VALUE_REQUIRED, 'Database name.' ); $this->addOption( 'db_user', null, InputOption::VALUE_REQUIRED, 'Database user.' ); $this->addOption( 'db_password', null, InputOption::VALUE_REQUIRED, 'Database password.' ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'create'", ")", ";", "$", "this", "->", "setDescription", "(", "'Create a snapshot locally.'", ")", ";", "$", "this", "->", "addOption", "(", "'exclude'", ",", "false", ...
Setup up command
[ "Setup", "up", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Create.php#L32-L45
10up/wpsnapshots
src/classes/S3.php
S3.putSnapshot
public function putSnapshot( $id, $project, $db_path, $files_path ) { try { $db_result = $this->client->putObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/data.sql.gz', 'SourceFile' => realpath( $db_path ), ] ); $files_result = $this->client->putObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/files.tar.gz', 'SourceFile' => realpath( $files_path ), ] ); /** * Wait for files first since that will probably take longer */ $this->client->waitUntil( 'ObjectExists', [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/files.tar.gz', ] ); $this->client->waitUntil( 'ObjectExists', [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/data.sql.gz', ] ); } catch ( \Exception $e ) { if ( ! empty( $files_result ) && 'AccessDenied' === $files_result->data['aws_error_code'] ) { Log::instance()->write( 'Access denied. You might not have access to this project.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
php
public function putSnapshot( $id, $project, $db_path, $files_path ) { try { $db_result = $this->client->putObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/data.sql.gz', 'SourceFile' => realpath( $db_path ), ] ); $files_result = $this->client->putObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/files.tar.gz', 'SourceFile' => realpath( $files_path ), ] ); /** * Wait for files first since that will probably take longer */ $this->client->waitUntil( 'ObjectExists', [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/files.tar.gz', ] ); $this->client->waitUntil( 'ObjectExists', [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/data.sql.gz', ] ); } catch ( \Exception $e ) { if ( ! empty( $files_result ) && 'AccessDenied' === $files_result->data['aws_error_code'] ) { Log::instance()->write( 'Access denied. You might not have access to this project.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
[ "public", "function", "putSnapshot", "(", "$", "id", ",", "$", "project", ",", "$", "db_path", ",", "$", "files_path", ")", "{", "try", "{", "$", "db_result", "=", "$", "this", "->", "client", "->", "putObject", "(", "[", "'Bucket'", "=>", "self", ":...
Upload a snapshot to S3 given a path to files.tar.gz and data.sql.gz @param string $id Snapshot ID @param string $project Project slug @param string $db_path Path to data.sql.gz @param string $files_path Path to files.tar.gz @return bool|error
[ "Upload", "a", "snapshot", "to", "S3", "given", "a", "path", "to", "files", ".", "tar", ".", "gz", "and", "data", ".", "sql", ".", "gz" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/S3.php#L89-L137
10up/wpsnapshots
src/classes/S3.php
S3.downloadSnapshot
public function downloadSnapshot( $id, $project, $db_path, $files_path ) { try { $db_download = $this->client->getObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/data.sql.gz', 'SaveAs' => $db_path, ] ); $files_download = $this->client->getObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/files.tar.gz', 'SaveAs' => $files_path, ] ); } catch ( \Exception $e ) { if ( 'AccessDenied' === $e->getAwsErrorCode() ) { Log::instance()->write( 'Access denied. You might not have access to this snapshot.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
php
public function downloadSnapshot( $id, $project, $db_path, $files_path ) { try { $db_download = $this->client->getObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/data.sql.gz', 'SaveAs' => $db_path, ] ); $files_download = $this->client->getObject( [ 'Bucket' => self::getBucketName( $this->repository ), 'Key' => $project . '/' . $id . '/files.tar.gz', 'SaveAs' => $files_path, ] ); } catch ( \Exception $e ) { if ( 'AccessDenied' === $e->getAwsErrorCode() ) { Log::instance()->write( 'Access denied. You might not have access to this snapshot.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
[ "public", "function", "downloadSnapshot", "(", "$", "id", ",", "$", "project", ",", "$", "db_path", ",", "$", "files_path", ")", "{", "try", "{", "$", "db_download", "=", "$", "this", "->", "client", "->", "getObject", "(", "[", "'Bucket'", "=>", "self...
Download a snapshot given an id. Must specify where to download files/data @param string $id Snapshot id @param string $project Project slug @param string $db_path Where to download data.sql.gz @param string $files_path Where to download files.tar.gz @return array|error
[ "Download", "a", "snapshot", "given", "an", "id", ".", "Must", "specify", "where", "to", "download", "files", "/", "data" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/S3.php#L148-L179
10up/wpsnapshots
src/classes/S3.php
S3.deleteSnapshot
public function deleteSnapshot( $id, $project ) { try { $result = $this->client->deleteObjects( [ 'Bucket' => self::getBucketName( $this->repository ), 'Delete' => [ 'Objects' => [ [ 'Key' => $project . '/' . $id . '/files.tar.gz', ], [ 'Key' => $project . '/' . $id . '/data.sql', ], [ 'Key' => $project . '/' . $id . '/data.sql.gz', ], ], ], ] ); } catch ( \Exception $e ) { if ( 'AccessDenied' === $s3_add->data['aws_error_code'] ) { Log::instance()->write( 'Access denied. You might not have access to this snapshot.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
php
public function deleteSnapshot( $id, $project ) { try { $result = $this->client->deleteObjects( [ 'Bucket' => self::getBucketName( $this->repository ), 'Delete' => [ 'Objects' => [ [ 'Key' => $project . '/' . $id . '/files.tar.gz', ], [ 'Key' => $project . '/' . $id . '/data.sql', ], [ 'Key' => $project . '/' . $id . '/data.sql.gz', ], ], ], ] ); } catch ( \Exception $e ) { if ( 'AccessDenied' === $s3_add->data['aws_error_code'] ) { Log::instance()->write( 'Access denied. You might not have access to this snapshot.', 0, 'error' ); } Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return false; } return true; }
[ "public", "function", "deleteSnapshot", "(", "$", "id", ",", "$", "project", ")", "{", "try", "{", "$", "result", "=", "$", "this", "->", "client", "->", "deleteObjects", "(", "[", "'Bucket'", "=>", "self", "::", "getBucketName", "(", "$", "this", "->"...
Delete a snapshot given an id @param string $id Snapshot id @param string $project Project name @return bool|error
[ "Delete", "a", "snapshot", "given", "an", "id" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/S3.php#L188-L222
10up/wpsnapshots
src/classes/S3.php
S3.createBucket
public function createBucket() { $bucket_exists = false; try { $result = $this->client->listBuckets(); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return $e->getAwsErrorCode(); } $bucket_name = self::getBucketName( $this->repository ); foreach ( $result['Buckets'] as $bucket ) { if ( $bucket_name === $bucket['Name'] ) { $bucket_exists = true; } } if ( $bucket_exists ) { return 'BucketExists'; } try { $result = $this->client->createBucket( [ 'Bucket' => self::getBucketName( $this->repository ), 'LocationConstraint' => $this->region, ] ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return $e->getAwsErrorCode(); } return true; }
php
public function createBucket() { $bucket_exists = false; try { $result = $this->client->listBuckets(); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return $e->getAwsErrorCode(); } $bucket_name = self::getBucketName( $this->repository ); foreach ( $result['Buckets'] as $bucket ) { if ( $bucket_name === $bucket['Name'] ) { $bucket_exists = true; } } if ( $bucket_exists ) { return 'BucketExists'; } try { $result = $this->client->createBucket( [ 'Bucket' => self::getBucketName( $this->repository ), 'LocationConstraint' => $this->region, ] ); } catch ( \Exception $e ) { Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' ); Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' ); Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' ); Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' ); return $e->getAwsErrorCode(); } return true; }
[ "public", "function", "createBucket", "(", ")", "{", "$", "bucket_exists", "=", "false", ";", "try", "{", "$", "result", "=", "$", "this", "->", "client", "->", "listBuckets", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", ...
Create WP Snapshots S3 bucket @return bool|string
[ "Create", "WP", "Snapshots", "S3", "bucket" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/S3.php#L274-L317
10up/wpsnapshots
src/classes/Log.php
Log.setOutput
public function setOutput( OutputInterface $output ) { $this->output = $output; if ( $output->isDebug() ) { $this->verbosity = 3; } elseif ( $output->isVeryVerbose() ) { $this->verbosity = 2; } elseif ( $output->isVerbose() ) { $this->verbosity = 1; } }
php
public function setOutput( OutputInterface $output ) { $this->output = $output; if ( $output->isDebug() ) { $this->verbosity = 3; } elseif ( $output->isVeryVerbose() ) { $this->verbosity = 2; } elseif ( $output->isVerbose() ) { $this->verbosity = 1; } }
[ "public", "function", "setOutput", "(", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "output", "=", "$", "output", ";", "if", "(", "$", "output", "->", "isDebug", "(", ")", ")", "{", "$", "this", "->", "verbosity", "=", "3", ";", ...
Do we want to log to the console? If so, set the output interface. @param OutputInterface $output Output to log to.
[ "Do", "we", "want", "to", "log", "to", "the", "console?", "If", "so", "set", "the", "output", "interface", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Log.php#L54-L64
10up/wpsnapshots
src/classes/Log.php
Log.write
public function write( $message, $verbosity_level = 0, $type = 'info', $data = [] ) { $verbosity_level += $this->verbosity_offset; $entry = [ 'message' => $message, 'data' => $data, 'type' => $type, 'verbosity_level' => $verbosity_level, ]; $this->log[] = $entry; if ( ! empty( $this->output ) ) { if ( 'warning' === $type ) { $message = '<comment>' . $message . '</comment>'; } elseif ( 'success' === $type ) { $message = '<info>' . $message . '</info>'; } elseif ( 'error' === $type ) { $message = '<error>' . $message . '</error>'; } $console_verbosity_level = OutputInterface::VERBOSITY_NORMAL; if ( 1 === $verbosity_level ) { $console_verbosity_level = OutputInterface::VERBOSITY_VERBOSE; } elseif ( 2 === $verbosity_level ) { $console_verbosity_level = OutputInterface::VERBOSITY_VERY_VERBOSE; } elseif ( 3 === $verbosity_level ) { $console_verbosity_level = OutputInterface::VERBOSITY_DEBUG; } $this->output->writeln( $message, $console_verbosity_level ); } return $entry; }
php
public function write( $message, $verbosity_level = 0, $type = 'info', $data = [] ) { $verbosity_level += $this->verbosity_offset; $entry = [ 'message' => $message, 'data' => $data, 'type' => $type, 'verbosity_level' => $verbosity_level, ]; $this->log[] = $entry; if ( ! empty( $this->output ) ) { if ( 'warning' === $type ) { $message = '<comment>' . $message . '</comment>'; } elseif ( 'success' === $type ) { $message = '<info>' . $message . '</info>'; } elseif ( 'error' === $type ) { $message = '<error>' . $message . '</error>'; } $console_verbosity_level = OutputInterface::VERBOSITY_NORMAL; if ( 1 === $verbosity_level ) { $console_verbosity_level = OutputInterface::VERBOSITY_VERBOSE; } elseif ( 2 === $verbosity_level ) { $console_verbosity_level = OutputInterface::VERBOSITY_VERY_VERBOSE; } elseif ( 3 === $verbosity_level ) { $console_verbosity_level = OutputInterface::VERBOSITY_DEBUG; } $this->output->writeln( $message, $console_verbosity_level ); } return $entry; }
[ "public", "function", "write", "(", "$", "message", ",", "$", "verbosity_level", "=", "0", ",", "$", "type", "=", "'info'", ",", "$", "data", "=", "[", "]", ")", "{", "$", "verbosity_level", "+=", "$", "this", "->", "verbosity_offset", ";", "$", "ent...
Write to log @param string $message String to write @param int $verbosity_level Verbosity level. See https://symfony.com/doc/current/console/verbosity.html @param string $type Either 'info', 'success', 'warning', 'error' @param array $data Arbitrary data to write @return array
[ "Write", "to", "log" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Log.php#L85-L120
10up/wpsnapshots
src/classes/RepositoryManager.php
RepositoryManager.setup
public function setup( $repository_name = null ) { if ( empty( $this->config['repositories'] ) ) { Log::instance()->write( 'No repositories in configuration.', 1 ); return false; } if ( empty( $repository_name ) ) { $repository_name = $this->getDefault(); } if ( ! empty( $this->repositories[ $repository_name ] ) ) { return $this->repositories[ $repository_name ]; } if ( empty( $this->config['repositories'][ $repository_name ] ) ) { Log::instance()->write( 'Repository not in configuration.', 1 ); return false; } $repo_config = $this->config['repositories'][ $repository_name ]; $repository = new Repository( $repository_name, $repo_config['access_key_id'], $repo_config['secret_access_key'], $repo_config['region'] ); $this->repositories[ $repository_name ] = $repository; Log::instance()->write( 'Setup repository: ' . $repository_name ); return $repository; }
php
public function setup( $repository_name = null ) { if ( empty( $this->config['repositories'] ) ) { Log::instance()->write( 'No repositories in configuration.', 1 ); return false; } if ( empty( $repository_name ) ) { $repository_name = $this->getDefault(); } if ( ! empty( $this->repositories[ $repository_name ] ) ) { return $this->repositories[ $repository_name ]; } if ( empty( $this->config['repositories'][ $repository_name ] ) ) { Log::instance()->write( 'Repository not in configuration.', 1 ); return false; } $repo_config = $this->config['repositories'][ $repository_name ]; $repository = new Repository( $repository_name, $repo_config['access_key_id'], $repo_config['secret_access_key'], $repo_config['region'] ); $this->repositories[ $repository_name ] = $repository; Log::instance()->write( 'Setup repository: ' . $repository_name ); return $repository; }
[ "public", "function", "setup", "(", "$", "repository_name", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "config", "[", "'repositories'", "]", ")", ")", "{", "Log", "::", "instance", "(", ")", "->", "write", "(", "'No repositories...
Set up a repository. This does not test the connection. @param string $repository_name Name of repo to setup. @return Repository|bool
[ "Set", "up", "a", "repository", ".", "This", "does", "not", "test", "the", "connection", "." ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/RepositoryManager.php#L37-L67
10up/wpsnapshots
src/classes/RepositoryManager.php
RepositoryManager.getDefault
public function getDefault() { if ( empty( $this->config['repositories'] ) ) { return false; } $config = array_values( $this->config['repositories'] ); return $config[0]['repository']; }
php
public function getDefault() { if ( empty( $this->config['repositories'] ) ) { return false; } $config = array_values( $this->config['repositories'] ); return $config[0]['repository']; }
[ "public", "function", "getDefault", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "config", "[", "'repositories'", "]", ")", ")", "{", "return", "false", ";", "}", "$", "config", "=", "array_values", "(", "$", "this", "->", "config", "["...
Get default repository @return string|bool
[ "Get", "default", "repository" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/RepositoryManager.php#L74-L82
10up/wpsnapshots
src/classes/Command/Download.php
Download.execute
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $id = $input->getArgument( 'snapshot_id' ); if ( empty( $path ) ) { $path = getcwd(); } $snapshot = Snapshot::download( $id, $repository->getName() ); if ( is_a( $snapshot, '\WPSnapshots\Snapshot' ) ) { Log::instance()->write( 'Download finished!', 0, 'success' ); } }
php
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Could not setup repository.', 0, 'error' ); return 1; } $id = $input->getArgument( 'snapshot_id' ); if ( empty( $path ) ) { $path = getcwd(); } $snapshot = Snapshot::download( $id, $repository->getName() ); if ( is_a( $snapshot, '\WPSnapshots\Snapshot' ) ) { Log::instance()->write( 'Download finished!', 0, 'success' ); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "Log", "::", "instance", "(", ")", "->", "setOutput", "(", "$", "output", ")", ";", "$", "repository", "=", "RepositoryManager", "::", ...
Executes the command @param InputInterface $input Command input @param OutputInterface $output Command output
[ "Executes", "the", "command" ]
train
https://github.com/10up/wpsnapshots/blob/98ab0cf9f73492f521c23e04449daadd3f8c9f91/src/classes/Command/Download.php#L44-L65
bupt1987/html-parser
src/ParserDom.php
ParserDom.load
public function load($node = NULL) { if ($node instanceof \DOMNode) { $this->node = $node; } else { $dom = new \DOMDocument(); $dom->preserveWhiteSpace = FALSE; $dom->strictErrorChecking = FALSE; if (@$dom->loadHTML($node)) { $this->node = $dom; } else { throw new \Exception('load html error'); } } }
php
public function load($node = NULL) { if ($node instanceof \DOMNode) { $this->node = $node; } else { $dom = new \DOMDocument(); $dom->preserveWhiteSpace = FALSE; $dom->strictErrorChecking = FALSE; if (@$dom->loadHTML($node)) { $this->node = $dom; } else { throw new \Exception('load html error'); } } }
[ "public", "function", "load", "(", "$", "node", "=", "NULL", ")", "{", "if", "(", "$", "node", "instanceof", "\\", "DOMNode", ")", "{", "$", "this", "->", "node", "=", "$", "node", ";", "}", "else", "{", "$", "dom", "=", "new", "\\", "DOMDocument...
初始化的时候可以不用传入html,后面可以多次使用 @param null $node @throws \Exception
[ "初始化的时候可以不用传入html,后面可以多次使用" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L50-L63
bupt1987/html-parser
src/ParserDom.php
ParserDom.find
public function find($selector, $idx = NULL) { if (empty($this->node->childNodes)) { return FALSE; } $selectors = $this->parse_selector($selector); if (($count = count($selectors)) === 0) { return FALSE; } for ($c = 0; $c < $count; $c++) { if (($level = count($selectors [$c])) === 0) { return FALSE; } $this->search($this->node, $idx, $selectors [$c], $level); } $found = $this->_lFind; $this->_lFind = []; if ($idx !== NULL) { if ($idx < 0) { $idx = count($found) + $idx; } if (isset($found[$idx])) { return $found[$idx]; } else { return FALSE; } } return $found; }
php
public function find($selector, $idx = NULL) { if (empty($this->node->childNodes)) { return FALSE; } $selectors = $this->parse_selector($selector); if (($count = count($selectors)) === 0) { return FALSE; } for ($c = 0; $c < $count; $c++) { if (($level = count($selectors [$c])) === 0) { return FALSE; } $this->search($this->node, $idx, $selectors [$c], $level); } $found = $this->_lFind; $this->_lFind = []; if ($idx !== NULL) { if ($idx < 0) { $idx = count($found) + $idx; } if (isset($found[$idx])) { return $found[$idx]; } else { return FALSE; } } return $found; }
[ "public", "function", "find", "(", "$", "selector", ",", "$", "idx", "=", "NULL", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "node", "->", "childNodes", ")", ")", "{", "return", "FALSE", ";", "}", "$", "selectors", "=", "$", "this", "-...
深度优先查询 @param string $selector @param number $idx 找第几个,从0开始计算,null 表示都返回, 负数表示倒数第几个 @return self|self[]
[ "深度优先查询" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L94-L121
bupt1987/html-parser
src/ParserDom.php
ParserDom.innerHtml
public function innerHtml() { $innerHTML = ""; $children = $this->node->childNodes; foreach ($children as $child) { $innerHTML .= $this->node->ownerDocument->saveHTML($child) ?: ''; } return $innerHTML; }
php
public function innerHtml() { $innerHTML = ""; $children = $this->node->childNodes; foreach ($children as $child) { $innerHTML .= $this->node->ownerDocument->saveHTML($child) ?: ''; } return $innerHTML; }
[ "public", "function", "innerHtml", "(", ")", "{", "$", "innerHTML", "=", "\"\"", ";", "$", "children", "=", "$", "this", "->", "node", "->", "childNodes", ";", "foreach", "(", "$", "children", "as", "$", "child", ")", "{", "$", "innerHTML", ".=", "$"...
获取innerHtml @return string
[ "获取innerHtml" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L136-L143
bupt1987/html-parser
src/ParserDom.php
ParserDom.outerHtml
public function outerHtml() { $doc = new \DOMDocument(); $doc->appendChild($doc->importNode($this->node, TRUE)); return $doc->saveHTML($doc); }
php
public function outerHtml() { $doc = new \DOMDocument(); $doc->appendChild($doc->importNode($this->node, TRUE)); return $doc->saveHTML($doc); }
[ "public", "function", "outerHtml", "(", ")", "{", "$", "doc", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "doc", "->", "appendChild", "(", "$", "doc", "->", "importNode", "(", "$", "this", "->", "node", ",", "TRUE", ")", ")", ";", "return"...
获取outerHtml @return string|bool
[ "获取outerHtml" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L149-L153
bupt1987/html-parser
src/ParserDom.php
ParserDom.getAttr
public function getAttr($name) { $oAttr = $this->node->attributes->getNamedItem($name); if (isset($oAttr)) { return $oAttr->nodeValue; } return NULL; }
php
public function getAttr($name) { $oAttr = $this->node->attributes->getNamedItem($name); if (isset($oAttr)) { return $oAttr->nodeValue; } return NULL; }
[ "public", "function", "getAttr", "(", "$", "name", ")", "{", "$", "oAttr", "=", "$", "this", "->", "node", "->", "attributes", "->", "getNamedItem", "(", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "oAttr", ")", ")", "{", "return", "$", ...
获取html的元属值 @param string $name @return string|null
[ "获取html的元属值" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L162-L168
bupt1987/html-parser
src/ParserDom.php
ParserDom.match
private function match($exp, $pattern, $value) { $pattern = strtolower($pattern); $value = strtolower($value); switch ($exp) { case '=' : return ($value === $pattern); case '!=' : return ($value !== $pattern); case '^=' : return preg_match("/^" . preg_quote($pattern, '/') . "/", $value); case '$=' : return preg_match("/" . preg_quote($pattern, '/') . "$/", $value); case '*=' : if ($pattern [0] == '/') { return preg_match($pattern, $value); } return preg_match("/" . $pattern . "/i", $value); } return FALSE; }
php
private function match($exp, $pattern, $value) { $pattern = strtolower($pattern); $value = strtolower($value); switch ($exp) { case '=' : return ($value === $pattern); case '!=' : return ($value !== $pattern); case '^=' : return preg_match("/^" . preg_quote($pattern, '/') . "/", $value); case '$=' : return preg_match("/" . preg_quote($pattern, '/') . "$/", $value); case '*=' : if ($pattern [0] == '/') { return preg_match($pattern, $value); } return preg_match("/" . $pattern . "/i", $value); } return FALSE; }
[ "private", "function", "match", "(", "$", "exp", ",", "$", "pattern", ",", "$", "value", ")", "{", "$", "pattern", "=", "strtolower", "(", "$", "pattern", ")", ";", "$", "value", "=", "strtolower", "(", "$", "value", ")", ";", "switch", "(", "$", ...
匹配 @param string $exp @param string $pattern @param string $value @return boolean|number
[ "匹配" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L178-L197
bupt1987/html-parser
src/ParserDom.php
ParserDom.parse_selector
private function parse_selector($selector_string) { $pattern = '/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)["\']?(.*?)["\']?)?\])?([\/, ]+)/is'; preg_match_all($pattern, trim($selector_string) . ' ', $matches, PREG_SET_ORDER); $selectors = []; $result = []; foreach ($matches as $m) { $m [0] = trim($m [0]); if ($m [0] === '' || $m [0] === '/' || $m [0] === '//') continue; if ($m [1] === 'tbody') continue; list ($tag, $key, $val, $exp, $no_key) = [$m [1], NULL, NULL, '=', FALSE]; if (!empty ($m [2])) { $key = 'id'; $val = $m [2]; } if (!empty ($m [3])) { $key = 'class'; $val = $m [3]; } if (!empty ($m [4])) { $key = $m [4]; } if (!empty ($m [5])) { $exp = $m [5]; } if (!empty ($m [6])) { $val = $m [6]; } // convert to lowercase $tag = strtolower($tag); $key = strtolower($key); // elements that do NOT have the specified attribute if (isset ($key [0]) && $key [0] === '!') { $key = substr($key, 1); $no_key = TRUE; } $result [] = [$tag, $key, $val, $exp, $no_key]; if (trim($m [7]) === ',') { $selectors [] = $result; $result = []; } } if (count($result) > 0) { $selectors [] = $result; } return $selectors; }
php
private function parse_selector($selector_string) { $pattern = '/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)["\']?(.*?)["\']?)?\])?([\/, ]+)/is'; preg_match_all($pattern, trim($selector_string) . ' ', $matches, PREG_SET_ORDER); $selectors = []; $result = []; foreach ($matches as $m) { $m [0] = trim($m [0]); if ($m [0] === '' || $m [0] === '/' || $m [0] === '//') continue; if ($m [1] === 'tbody') continue; list ($tag, $key, $val, $exp, $no_key) = [$m [1], NULL, NULL, '=', FALSE]; if (!empty ($m [2])) { $key = 'id'; $val = $m [2]; } if (!empty ($m [3])) { $key = 'class'; $val = $m [3]; } if (!empty ($m [4])) { $key = $m [4]; } if (!empty ($m [5])) { $exp = $m [5]; } if (!empty ($m [6])) { $val = $m [6]; } // convert to lowercase $tag = strtolower($tag); $key = strtolower($key); // elements that do NOT have the specified attribute if (isset ($key [0]) && $key [0] === '!') { $key = substr($key, 1); $no_key = TRUE; } $result [] = [$tag, $key, $val, $exp, $no_key]; if (trim($m [7]) === ',') { $selectors [] = $result; $result = []; } } if (count($result) > 0) { $selectors [] = $result; } return $selectors; }
[ "private", "function", "parse_selector", "(", "$", "selector_string", ")", "{", "$", "pattern", "=", "'/([\\w-:\\*]*)(?:\\#([\\w-]+)|\\.([\\w-]+))?(?:\\[@?(!?[\\w-:]+)(?:([!*^$]?=)[\"\\']?(.*?)[\"\\']?)?\\])?([\\/, ]+)/is'", ";", "preg_match_all", "(", "$", "pattern", ",", "trim"...
分析查询语句 @param string $selector_string @return array
[ "分析查询语句" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L205-L252
bupt1987/html-parser
src/ParserDom.php
ParserDom.search
private function search(&$search, $idx, $selectors, $level, $search_level = 0) { if ($search_level >= $level) { $rs = $this->seek($search, $selectors, $level - 1); if ($rs !== FALSE && $idx !== NULL) { if ($idx == count($this->_lFind)) { $this->_lFind[] = new self($rs); return TRUE; } else { $this->_lFind[] = new self($rs); } } elseif ($rs !== FALSE) { $this->_lFind[] = new self($rs); } } if (!empty($search->childNodes)) { foreach ($search->childNodes as $val) { if ($this->search($val, $idx, $selectors, $level, $search_level + 1)) { return TRUE; } } } return FALSE; }
php
private function search(&$search, $idx, $selectors, $level, $search_level = 0) { if ($search_level >= $level) { $rs = $this->seek($search, $selectors, $level - 1); if ($rs !== FALSE && $idx !== NULL) { if ($idx == count($this->_lFind)) { $this->_lFind[] = new self($rs); return TRUE; } else { $this->_lFind[] = new self($rs); } } elseif ($rs !== FALSE) { $this->_lFind[] = new self($rs); } } if (!empty($search->childNodes)) { foreach ($search->childNodes as $val) { if ($this->search($val, $idx, $selectors, $level, $search_level + 1)) { return TRUE; } } } return FALSE; }
[ "private", "function", "search", "(", "&", "$", "search", ",", "$", "idx", ",", "$", "selectors", ",", "$", "level", ",", "$", "search_level", "=", "0", ")", "{", "if", "(", "$", "search_level", ">=", "$", "level", ")", "{", "$", "rs", "=", "$", ...
深度查询 @param \DOMNode $search @param $idx @param $selectors @param $level @param int $search_level @return bool
[ "深度查询" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L264-L286
bupt1987/html-parser
src/ParserDom.php
ParserDom.seek
private function seek($search, $selectors, $current) { if (!($search instanceof \DOMElement)) { return FALSE; } list ($tag, $key, $val, $exp, $no_key) = $selectors [$current]; $pass = TRUE; if ($tag === '*' && !$key) { exit('tag为*时,key不能为空'); } if ($tag && $tag != $search->tagName && $tag !== '*') { $pass = FALSE; } if ($pass && $key) { if ($no_key) { if ($search->hasAttribute($key)) { $pass = FALSE; } } else { if ($key != "plaintext" && !$search->hasAttribute($key)) { $pass = FALSE; } } } if ($pass && $key && $val && $val !== '*') { if ($key == "plaintext") { $nodeKeyValue = $this->text($search); } else { $nodeKeyValue = $search->getAttribute($key); } $check = $this->match($exp, $val, $nodeKeyValue); if (!$check && strcasecmp($key, 'class') === 0) { foreach (explode(' ', $search->getAttribute($key)) as $k) { if (!empty ($k)) { $check = $this->match($exp, $val, $k); if ($check) { break; } } } } if (!$check) { $pass = FALSE; } } if ($pass) { $current--; if ($current < 0) { return $search; } elseif ($this->seek($this->getParent($search), $selectors, $current)) { return $search; } else { return FALSE; } } else { return FALSE; } }
php
private function seek($search, $selectors, $current) { if (!($search instanceof \DOMElement)) { return FALSE; } list ($tag, $key, $val, $exp, $no_key) = $selectors [$current]; $pass = TRUE; if ($tag === '*' && !$key) { exit('tag为*时,key不能为空'); } if ($tag && $tag != $search->tagName && $tag !== '*') { $pass = FALSE; } if ($pass && $key) { if ($no_key) { if ($search->hasAttribute($key)) { $pass = FALSE; } } else { if ($key != "plaintext" && !$search->hasAttribute($key)) { $pass = FALSE; } } } if ($pass && $key && $val && $val !== '*') { if ($key == "plaintext") { $nodeKeyValue = $this->text($search); } else { $nodeKeyValue = $search->getAttribute($key); } $check = $this->match($exp, $val, $nodeKeyValue); if (!$check && strcasecmp($key, 'class') === 0) { foreach (explode(' ', $search->getAttribute($key)) as $k) { if (!empty ($k)) { $check = $this->match($exp, $val, $k); if ($check) { break; } } } } if (!$check) { $pass = FALSE; } } if ($pass) { $current--; if ($current < 0) { return $search; } elseif ($this->seek($this->getParent($search), $selectors, $current)) { return $search; } else { return FALSE; } } else { return FALSE; } }
[ "private", "function", "seek", "(", "$", "search", ",", "$", "selectors", ",", "$", "current", ")", "{", "if", "(", "!", "(", "$", "search", "instanceof", "\\", "DOMElement", ")", ")", "{", "return", "FALSE", ";", "}", "list", "(", "$", "tag", ",",...
匹配节点,由于采取的倒序查找,所以时间复杂度为n+m*l n为总节点数,m为匹配最后一个规则的个数,l为规则的深度, @codeCoverageIgnore @param \DOMNode $search @param array $selectors @param int $current @return boolean|\DOMNode
[ "匹配节点", "由于采取的倒序查找,所以时间复杂度为n", "+", "m", "*", "l", "n为总节点数,m为匹配最后一个规则的个数,l为规则的深度" ]
train
https://github.com/bupt1987/html-parser/blob/ae5d325bbcf653793f65c176e1a0d2743663dcfd/src/ParserDom.php#L306-L362
bryanjhv/slim-session
src/Slim/Middleware/Session.php
Session.startSession
protected function startSession() { $inactive = session_status() === PHP_SESSION_NONE; if (!$inactive) return; $settings = $this->settings; $name = $settings['name']; session_set_cookie_params( $settings['lifetime'], $settings['path'], $settings['domain'], $settings['secure'], $settings['httponly'] ); // Refresh session cookie when "inactive", // else PHP won't know we want this to refresh if ($settings['autorefresh'] && isset($_COOKIE[$name])) { setcookie( $name, $_COOKIE[$name], time() + $settings['lifetime'], $settings['path'], $settings['domain'], $settings['secure'], $settings['httponly'] ); } session_name($name); $handler = $settings['handler']; if ($handler) { if (!($handler instanceof \SessionHandlerInterface)) { $handler = new $handler; } session_set_save_handler($handler, true); } session_cache_limiter(false); session_start(); }
php
protected function startSession() { $inactive = session_status() === PHP_SESSION_NONE; if (!$inactive) return; $settings = $this->settings; $name = $settings['name']; session_set_cookie_params( $settings['lifetime'], $settings['path'], $settings['domain'], $settings['secure'], $settings['httponly'] ); // Refresh session cookie when "inactive", // else PHP won't know we want this to refresh if ($settings['autorefresh'] && isset($_COOKIE[$name])) { setcookie( $name, $_COOKIE[$name], time() + $settings['lifetime'], $settings['path'], $settings['domain'], $settings['secure'], $settings['httponly'] ); } session_name($name); $handler = $settings['handler']; if ($handler) { if (!($handler instanceof \SessionHandlerInterface)) { $handler = new $handler; } session_set_save_handler($handler, true); } session_cache_limiter(false); session_start(); }
[ "protected", "function", "startSession", "(", ")", "{", "$", "inactive", "=", "session_status", "(", ")", "===", "PHP_SESSION_NONE", ";", "if", "(", "!", "$", "inactive", ")", "return", ";", "$", "settings", "=", "$", "this", "->", "settings", ";", "$", ...
Start session
[ "Start", "session" ]
train
https://github.com/bryanjhv/slim-session/blob/0205470a35c716823ededae04d84a7f27fba400a/src/Slim/Middleware/Session.php#L84-L126
bryanjhv/slim-session
src/SlimSession/Helper.php
Helper.merge
public function merge($key, $value) { if (is_array($value) && is_array($old = $this->get($key))) { $value = array_merge_recursive($old, $value); } return $this->set($key, $value); }
php
public function merge($key, $value) { if (is_array($value) && is_array($old = $this->get($key))) { $value = array_merge_recursive($old, $value); } return $this->set($key, $value); }
[ "public", "function", "merge", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "is_array", "(", "$", "old", "=", "$", "this", "->", "get", "(", "$", "key", ")", ")", ")", "{", "$", "value", "...
Merge values recursively. @param string $key @param mixed $value @return $this
[ "Merge", "values", "recursively", "." ]
train
https://github.com/bryanjhv/slim-session/blob/0205470a35c716823ededae04d84a7f27fba400a/src/SlimSession/Helper.php#L53-L60
bryanjhv/slim-session
src/SlimSession/Helper.php
Helper.destroy
public static function destroy() { if (self::id()) { session_unset(); session_destroy(); session_write_close(); if (ini_get('session.use_cookies')) { $params = session_get_cookie_params(); setcookie( session_name(), '', time() - 4200, $params['path'], $params['domain'], $params['secure'], $params['httponly'] ); } } }
php
public static function destroy() { if (self::id()) { session_unset(); session_destroy(); session_write_close(); if (ini_get('session.use_cookies')) { $params = session_get_cookie_params(); setcookie( session_name(), '', time() - 4200, $params['path'], $params['domain'], $params['secure'], $params['httponly'] ); } } }
[ "public", "static", "function", "destroy", "(", ")", "{", "if", "(", "self", "::", "id", "(", ")", ")", "{", "session_unset", "(", ")", ";", "session_destroy", "(", ")", ";", "session_write_close", "(", ")", ";", "if", "(", "ini_get", "(", "'session.us...
Destroy the session.
[ "Destroy", "the", "session", "." ]
train
https://github.com/bryanjhv/slim-session/blob/0205470a35c716823ededae04d84a7f27fba400a/src/SlimSession/Helper.php#L121-L141
railt/railt
src/Component/Compiler/Grammar/LookaheadIterator.php
LookaheadIterator.next
public function next(): void { $innerIterator = $this->getInnerIterator(); $this->valid = $innerIterator->valid(); if ($this->valid === false) { return; } $this->key = $innerIterator->key(); $this->current = $innerIterator->current(); $innerIterator->next(); }
php
public function next(): void { $innerIterator = $this->getInnerIterator(); $this->valid = $innerIterator->valid(); if ($this->valid === false) { return; } $this->key = $innerIterator->key(); $this->current = $innerIterator->current(); $innerIterator->next(); }
[ "public", "function", "next", "(", ")", ":", "void", "{", "$", "innerIterator", "=", "$", "this", "->", "getInnerIterator", "(", ")", ";", "$", "this", "->", "valid", "=", "$", "innerIterator", "->", "valid", "(", ")", ";", "if", "(", "$", "this", ...
Move forward to next element. @return void
[ "Move", "forward", "to", "next", "element", "." ]
train
https://github.com/railt/railt/blob/8f17cd620fd0eecb9aa9a09fda87fa6f7afbc7dd/src/Component/Compiler/Grammar/LookaheadIterator.php#L77-L90
railt/railt
src/Component/Json/Rfc7159/NativeJsonDecoder.php
NativeJsonDecoder.decode
public function decode(string $json, int $options = null) { if ($options !== null) { return (clone $this)->decode($json); } $shouldBeArray = $this->hasOption(\JSON_OBJECT_AS_ARRAY); return $this->wrap(function () use ($json, $shouldBeArray) { return @\json_decode($json, $shouldBeArray, $this->getRecursionDepth(), $this->getOptions()); }); }
php
public function decode(string $json, int $options = null) { if ($options !== null) { return (clone $this)->decode($json); } $shouldBeArray = $this->hasOption(\JSON_OBJECT_AS_ARRAY); return $this->wrap(function () use ($json, $shouldBeArray) { return @\json_decode($json, $shouldBeArray, $this->getRecursionDepth(), $this->getOptions()); }); }
[ "public", "function", "decode", "(", "string", "$", "json", ",", "int", "$", "options", "=", "null", ")", "{", "if", "(", "$", "options", "!==", "null", ")", "{", "return", "(", "clone", "$", "this", ")", "->", "decode", "(", "$", "json", ")", ";...
Wrapper for json_decode with predefined options that throws a Railt\Component\Json\Exception\JsonException when an error occurs. @see http://www.php.net/manual/en/function.json-decode.php @see http://php.net/manual/en/class.jsonexception.php @param string $json @param int|null $options @return mixed @throws JsonException
[ "Wrapper", "for", "json_decode", "with", "predefined", "options", "that", "throws", "a", "Railt", "\\", "Component", "\\", "Json", "\\", "Exception", "\\", "JsonException", "when", "an", "error", "occurs", "." ]
train
https://github.com/railt/railt/blob/8f17cd620fd0eecb9aa9a09fda87fa6f7afbc7dd/src/Component/Json/Rfc7159/NativeJsonDecoder.php#L41-L52
railt/railt
src/Component/Json/OptionsTrait.php
OptionsTrait.setOption
public function setOption(int $option, bool $enable = true): OptionsInterface { if ($enable && ! $this->hasOption($option)) { $this->withOptions($option); } if (! $enable && $this->hasOption($option)) { $this->withoutOptions($option); } return $this; }
php
public function setOption(int $option, bool $enable = true): OptionsInterface { if ($enable && ! $this->hasOption($option)) { $this->withOptions($option); } if (! $enable && $this->hasOption($option)) { $this->withoutOptions($option); } return $this; }
[ "public", "function", "setOption", "(", "int", "$", "option", ",", "bool", "$", "enable", "=", "true", ")", ":", "OptionsInterface", "{", "if", "(", "$", "enable", "&&", "!", "$", "this", "->", "hasOption", "(", "$", "option", ")", ")", "{", "$", "...
Enables or disables the passed option ($option) depending on the second argument $enable. @param int $option @param bool $enable @return OptionsInterface|$this
[ "Enables", "or", "disables", "the", "passed", "option", "(", "$option", ")", "depending", "on", "the", "second", "argument", "$enable", "." ]
train
https://github.com/railt/railt/blob/8f17cd620fd0eecb9aa9a09fda87fa6f7afbc7dd/src/Component/Json/OptionsTrait.php#L73-L84
railt/railt
src/Component/Json/OptionsTrait.php
OptionsTrait.withOptions
public function withOptions(int ...$options): OptionsInterface { foreach ($options as $option) { $this->options |= $option; } return $this; }
php
public function withOptions(int ...$options): OptionsInterface { foreach ($options as $option) { $this->options |= $option; } return $this; }
[ "public", "function", "withOptions", "(", "int", "...", "$", "options", ")", ":", "OptionsInterface", "{", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "$", "this", "->", "options", "|=", "$", "option", ";", "}", "return", "$", "this"...
Adds a list of passed options to existing ones. @param int ...$options @return OptionsInterface|$this
[ "Adds", "a", "list", "of", "passed", "options", "to", "existing", "ones", "." ]
train
https://github.com/railt/railt/blob/8f17cd620fd0eecb9aa9a09fda87fa6f7afbc7dd/src/Component/Json/OptionsTrait.php#L92-L99
railt/railt
src/Component/Json/OptionsTrait.php
OptionsTrait.withoutOptions
public function withoutOptions(int ...$options): OptionsInterface { foreach ($options as $option) { $this->options &= ~$option; } return $this; }
php
public function withoutOptions(int ...$options): OptionsInterface { foreach ($options as $option) { $this->options &= ~$option; } return $this; }
[ "public", "function", "withoutOptions", "(", "int", "...", "$", "options", ")", ":", "OptionsInterface", "{", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "$", "this", "->", "options", "&=", "~", "$", "option", ";", "}", "return", "$"...
Removes the list of passed options from existing ones. @param int ...$options @return OptionsInterface|$this
[ "Removes", "the", "list", "of", "passed", "options", "from", "existing", "ones", "." ]
train
https://github.com/railt/railt/blob/8f17cd620fd0eecb9aa9a09fda87fa6f7afbc7dd/src/Component/Json/OptionsTrait.php#L107-L114
railt/railt
src/Component/Container/SimpleContainer.php
SimpleContainer.has
public function has($id): bool { \assert(\is_scalar($id), 'Invalid format of the entry identifier.'); return \array_key_exists($id, $this->values) || $this->hasInProxy($id); }
php
public function has($id): bool { \assert(\is_scalar($id), 'Invalid format of the entry identifier.'); return \array_key_exists($id, $this->values) || $this->hasInProxy($id); }
[ "public", "function", "has", "(", "$", "id", ")", ":", "bool", "{", "\\", "assert", "(", "\\", "is_scalar", "(", "$", "id", ")", ",", "'Invalid format of the entry identifier.'", ")", ";", "return", "\\", "array_key_exists", "(", "$", "id", ",", "$", "th...
Returns `true` if the container can return an entry for the given identifier. Returns `false` otherwise. @param int|float|string|bool $id Identifier of the entry to look for. @return bool
[ "Returns", "true", "if", "the", "container", "can", "return", "an", "entry", "for", "the", "given", "identifier", ".", "Returns", "false", "otherwise", "." ]
train
https://github.com/railt/railt/blob/8f17cd620fd0eecb9aa9a09fda87fa6f7afbc7dd/src/Component/Container/SimpleContainer.php#L61-L66