Initial commit
This commit is contained in:
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\CSSList; use Sabberworm\CSS\Property\AtRule; class AtRuleBlockList extends CSSBlockList implements AtRule { private $sType; private $sArgs; public function __construct($sType, $sArgs = '', $iLineNo = 0) { parent::__construct($iLineNo); $this->sType = $sType; $this->sArgs = $sArgs; } public function atRuleName() { return $this->sType; } public function atRuleArgs() { return $this->sArgs; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $sArgs = $this->sArgs; if($sArgs) { $sArgs = ' ' . $sArgs; } $sResult = "@{$this->sType}$sArgs{$oOutputFormat->spaceBeforeOpeningBrace()}{"; $sResult .= parent::render($oOutputFormat); $sResult .= '}'; return $sResult; } public function isRootList() { return false; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\CSSList; use Sabberworm\CSS\RuleSet\DeclarationBlock; use Sabberworm\CSS\RuleSet\RuleSet; use Sabberworm\CSS\Property\Selector; use Sabberworm\CSS\Rule\Rule; use Sabberworm\CSS\Value\ValueList; use Sabberworm\CSS\Value\CSSFunction; abstract class CSSBlockList extends CSSList { public function __construct($iLineNo = 0) { parent::__construct($iLineNo); } protected function allDeclarationBlocks(&$aResult) { foreach ($this->aContents as $mContent) { if ($mContent instanceof DeclarationBlock) { $aResult[] = $mContent; } else if ($mContent instanceof CSSBlockList) { $mContent->allDeclarationBlocks($aResult); } } } protected function allRuleSets(&$aResult) { foreach ($this->aContents as $mContent) { if ($mContent instanceof RuleSet) { $aResult[] = $mContent; } else if ($mContent instanceof CSSBlockList) { $mContent->allRuleSets($aResult); } } } protected function allValues($oElement, &$aResult, $sSearchString = null, $bSearchInFunctionArguments = false) { if ($oElement instanceof CSSBlockList) { foreach ($oElement->getContents() as $oContent) { $this->allValues($oContent, $aResult, $sSearchString, $bSearchInFunctionArguments); } } else if ($oElement instanceof RuleSet) { foreach ($oElement->getRules($sSearchString) as $oRule) { $this->allValues($oRule, $aResult, $sSearchString, $bSearchInFunctionArguments); } } else if ($oElement instanceof Rule) { $this->allValues($oElement->getValue(), $aResult, $sSearchString, $bSearchInFunctionArguments); } else if ($oElement instanceof ValueList) { if ($bSearchInFunctionArguments || !($oElement instanceof CSSFunction)) { foreach ($oElement->getListComponents() as $mComponent) { $this->allValues($mComponent, $aResult, $sSearchString, $bSearchInFunctionArguments); } } } else { $aResult[] = $oElement; } } protected function allSelectors(&$aResult, $sSpecificitySearch = null) { $aDeclarationBlocks = array(); $this->allDeclarationBlocks($aDeclarationBlocks); foreach ($aDeclarationBlocks as $oBlock) { foreach ($oBlock->getSelectors() as $oSelector) { if ($sSpecificitySearch === null) { $aResult[] = $oSelector; } else { $sComparison = "\$bRes = {$oSelector->getSpecificity()} $sSpecificitySearch;"; eval($sComparison); if ($bRes) { $aResult[] = $oSelector; } } } } } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\CSSList; use Sabberworm\CSS\Renderable; use Sabberworm\CSS\RuleSet\DeclarationBlock; use Sabberworm\CSS\RuleSet\RuleSet; use Sabberworm\CSS\Property\Selector; use Sabberworm\CSS\Comment\Commentable; abstract class CSSList implements Renderable, Commentable { protected $aComments; protected $aContents; protected $iLineNo; public function __construct($iLineNo = 0) { $this->aComments = array(); $this->aContents = array(); $this->iLineNo = $iLineNo; } public function getLineNo() { return $this->iLineNo; } public function append($oItem) { $this->aContents[] = $oItem; } public function remove($oItemToRemove) { $iKey = array_search($oItemToRemove, $this->aContents, true); if ($iKey !== false) { unset($this->aContents[$iKey]); return true; } return false; } public function setContents(array $aContents) { $this->aContents = array(); foreach ($aContents as $content) { $this->append($content); } } public function removeDeclarationBlockBySelector($mSelector, $bRemoveAll = false) { if ($mSelector instanceof DeclarationBlock) { $mSelector = $mSelector->getSelectors(); } if (!is_array($mSelector)) { $mSelector = explode(',', $mSelector); } foreach ($mSelector as $iKey => &$mSel) { if (!($mSel instanceof Selector)) { $mSel = new Selector($mSel); } } foreach ($this->aContents as $iKey => $mItem) { if (!($mItem instanceof DeclarationBlock)) { continue; } if ($mItem->getSelectors() == $mSelector) { unset($this->aContents[$iKey]); if (!$bRemoveAll) { return; } } } } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $sResult = ''; $bIsFirst = true; $oNextLevel = $oOutputFormat; if(!$this->isRootList()) { $oNextLevel = $oOutputFormat->nextLevel(); } foreach ($this->aContents as $oContent) { $sRendered = $oOutputFormat->safely(function() use ($oNextLevel, $oContent) { return $oContent->render($oNextLevel); }); if($sRendered === null) { continue; } if($bIsFirst) { $bIsFirst = false; $sResult .= $oNextLevel->spaceBeforeBlocks(); } else { $sResult .= $oNextLevel->spaceBetweenBlocks(); } $sResult .= $sRendered; } if(!$bIsFirst) { $sResult .= $oOutputFormat->spaceAfterBlocks(); } return $sResult; } public abstract function isRootList(); public function getContents() { return $this->aContents; } public function addComments(array $aComments) { $this->aComments = array_merge($this->aComments, $aComments); } public function getComments() { return $this->aComments; } public function setComments(array $aComments) { $this->aComments = $aComments; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\CSSList; class Document extends CSSBlockList { public function __construct($iLineNo = 0) { parent::__construct($iLineNo); } public function getAllDeclarationBlocks() { $aResult = array(); $this->allDeclarationBlocks($aResult); return $aResult; } public function getAllSelectors() { return $this->getAllDeclarationBlocks(); } public function getAllRuleSets() { $aResult = array(); $this->allRuleSets($aResult); return $aResult; } public function getAllValues($mElement = null, $bSearchInFunctionArguments = false) { $sSearchString = null; if ($mElement === null) { $mElement = $this; } else if (is_string($mElement)) { $sSearchString = $mElement; $mElement = $this; } $aResult = array(); $this->allValues($mElement, $aResult, $sSearchString, $bSearchInFunctionArguments); return $aResult; } public function getSelectorsBySpecificity($sSpecificitySearch = null) { if (is_numeric($sSpecificitySearch) || is_numeric($sSpecificitySearch[0])) { $sSpecificitySearch = "== $sSpecificitySearch"; } $aResult = array(); $this->allSelectors($aResult, $sSpecificitySearch); return $aResult; } public function expandShorthands() { foreach ($this->getAllDeclarationBlocks() as $oDeclaration) { $oDeclaration->expandShorthands(); } } public function createShorthands() { foreach ($this->getAllDeclarationBlocks() as $oDeclaration) { $oDeclaration->createShorthands(); } } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat = null) { if($oOutputFormat === null) { $oOutputFormat = new \Sabberworm\CSS\OutputFormat(); } return parent::render($oOutputFormat); } public function isRootList() { return true; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\CSSList; use Sabberworm\CSS\Property\AtRule; class KeyFrame extends CSSList implements AtRule { private $vendorKeyFrame; private $animationName; public function __construct($iLineNo = 0) { parent::__construct($iLineNo); $this->vendorKeyFrame = null; $this->animationName = null; } public function setVendorKeyFrame($vendorKeyFrame) { $this->vendorKeyFrame = $vendorKeyFrame; } public function getVendorKeyFrame() { return $this->vendorKeyFrame; } public function setAnimationName($animationName) { $this->animationName = $animationName; } public function getAnimationName() { return $this->animationName; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $sResult = "@{$this->vendorKeyFrame} {$this->animationName}{$oOutputFormat->spaceBeforeOpeningBrace()}{"; $sResult .= parent::render($oOutputFormat); $sResult .= '}'; return $sResult; } public function isRootList() { return false; } public function atRuleName() { return $this->vendorKeyFrame; } public function atRuleArgs() { return $this->animationName; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Comment; use Sabberworm\CSS\Renderable; class Comment implements Renderable { protected $iLineNo; protected $sComment; public function __construct($sComment = '', $iLineNo = 0) { $this->sComment = $sComment; $this->iLineNo = $iLineNo; } public function getComment() { return $this->sComment; } public function getLineNo() { return $this->iLineNo; } public function setComment($sComment) { $this->sComment = $sComment; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return '/*' . $this->sComment . '*/'; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Comment; interface Commentable { public function addComments(array $aComments); public function getComments(); public function setComments(array $aComments); }
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Parsing; class OutputException extends SourceException { public function __construct($sMessage, $iLineNo = 0) { parent::__construct($sMessage, $iLineNo); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Parsing; class SourceException extends \Exception { private $iLineNo; public function __construct($sMessage, $iLineNo = 0) { $this->iLineNo = $iLineNo; if (!empty($iLineNo)) { $sMessage .= " [line no: $iLineNo]"; } parent::__construct($sMessage); } public function getLineNo() { return $this->iLineNo; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Parsing; class UnexpectedTokenException extends SourceException { private $sExpected; private $sFound; private $sMatchType; public function __construct($sExpected, $sFound, $sMatchType = 'literal', $iLineNo = 0) { $this->sExpected = $sExpected; $this->sFound = $sFound; $this->sMatchType = $sMatchType; $sMessage = "Token “{$sExpected}” ({$sMatchType}) not found. Got “{$sFound}”."; if($this->sMatchType === 'search') { $sMessage = "Search for “{$sExpected}” returned no results. Context: “{$sFound}”."; } else if($this->sMatchType === 'count') { $sMessage = "Next token was expected to have {$sExpected} chars. Context: “{$sFound}”."; } else if($this->sMatchType === 'identifier') { $sMessage = "Identifier expected. Got “{$sFound}”"; } else if($this->sMatchType === 'custom') { $sMessage = trim("$sExpected $sFound"); } parent::__construct($sMessage, $iLineNo); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Property; use Sabberworm\CSS\Renderable; use Sabberworm\CSS\Comment\Commentable; interface AtRule extends Renderable, Commentable { const BLOCK_RULES = 'media/document/supports/region-style/font-feature-values'; const SET_RULES = 'font-face/counter-style/page/swash/styleset/annotation'; public function atRuleName(); public function atRuleArgs(); }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Property; class CSSNamespace implements AtRule { private $mUrl; private $sPrefix; private $iLineNo; protected $aComments; public function __construct($mUrl, $sPrefix = null, $iLineNo = 0) { $this->mUrl = $mUrl; $this->sPrefix = $sPrefix; $this->iLineNo = $iLineNo; $this->aComments = array(); } public function getLineNo() { return $this->iLineNo; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return '@namespace '.($this->sPrefix === null ? '' : $this->sPrefix.' ').$this->mUrl->render($oOutputFormat).';'; } public function getUrl() { return $this->mUrl; } public function getPrefix() { return $this->sPrefix; } public function setUrl($mUrl) { $this->mUrl = $mUrl; } public function setPrefix($sPrefix) { $this->sPrefix = $sPrefix; } public function atRuleName() { return 'namespace'; } public function atRuleArgs() { $aResult = array($this->mUrl); if($this->sPrefix) { array_unshift($aResult, $this->sPrefix); } return $aResult; } public function addComments(array $aComments) { $this->aComments = array_merge($this->aComments, $aComments); } public function getComments() { return $this->aComments; } public function setComments(array $aComments) { $this->aComments = $aComments; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Property; class Charset implements AtRule { private $sCharset; protected $iLineNo; protected $aComment; public function __construct($sCharset, $iLineNo = 0) { $this->sCharset = $sCharset; $this->iLineNo = $iLineNo; $this->aComments = array(); } public function getLineNo() { return $this->iLineNo; } public function setCharset($sCharset) { $this->sCharset = $sCharset; } public function getCharset() { return $this->sCharset; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return "@charset {$this->sCharset->render($oOutputFormat)};"; } public function atRuleName() { return 'charset'; } public function atRuleArgs() { return $this->sCharset; } public function addComments(array $aComments) { $this->aComments = array_merge($this->aComments, $aComments); } public function getComments() { return $this->aComments; } public function setComments(array $aComments) { $this->aComments = $aComments; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Property; use Sabberworm\CSS\Value\URL; class Import implements AtRule { private $oLocation; private $sMediaQuery; protected $iLineNo; protected $aComments; public function __construct(URL $oLocation, $sMediaQuery, $iLineNo = 0) { $this->oLocation = $oLocation; $this->sMediaQuery = $sMediaQuery; $this->iLineNo = $iLineNo; $this->aComments = array(); } public function getLineNo() { return $this->iLineNo; } public function setLocation($oLocation) { $this->oLocation = $oLocation; } public function getLocation() { return $this->oLocation; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return "@import ".$this->oLocation->render($oOutputFormat).($this->sMediaQuery === null ? '' : ' '.$this->sMediaQuery).';'; } public function atRuleName() { return 'import'; } public function atRuleArgs() { $aResult = array($this->oLocation); if($this->sMediaQuery) { array_push($aResult, $this->sMediaQuery); } return $aResult; } public function addComments(array $aComments) { $this->aComments = array_merge($this->aComments, $aComments); } public function getComments() { return $this->aComments; } public function setComments(array $aComments) { $this->aComments = $aComments; } }
|
@ -0,0 +1,25 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Property; class Selector { const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX = '/
|
||||
(\.[\w]+) # classes
|
||||
|
|
||||
\[(\w+) # attributes
|
||||
|
|
||||
(\:( # pseudo classes
|
||||
link|visited|active
|
||||
|hover|focus
|
||||
|lang
|
||||
|target
|
||||
|enabled|disabled|checked|indeterminate
|
||||
|root
|
||||
|nth-child|nth-last-child|nth-of-type|nth-last-of-type
|
||||
|first-child|last-child|first-of-type|last-of-type
|
||||
|only-child|only-of-type
|
||||
|empty|contains
|
||||
))
|
||||
/ix'; const ELEMENTS_AND_PSEUDO_ELEMENTS_RX = '/
|
||||
((^|[\s\+\>\~]+)[\w]+ # elements
|
||||
|
|
||||
\:{1,2}( # pseudo-elements
|
||||
after|before|first-letter|first-line|selection
|
||||
))
|
||||
/ix'; private $sSelector; private $iSpecificity; public function __construct($sSelector, $bCalculateSpecificity = false) { $this->setSelector($sSelector); if ($bCalculateSpecificity) { $this->getSpecificity(); } } public function getSelector() { return $this->sSelector; } public function setSelector($sSelector) { $this->sSelector = trim($sSelector); $this->iSpecificity = null; } public function __toString() { return $this->getSelector(); } public function getSpecificity() { if ($this->iSpecificity === null) { $a = 0; $aMatches = null; $b = substr_count($this->sSelector, '#'); $c = preg_match_all(self::NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX, $this->sSelector, $aMatches); $d = preg_match_all(self::ELEMENTS_AND_PSEUDO_ELEMENTS_RX, $this->sSelector, $aMatches); $this->iSpecificity = ($a * 1000) + ($b * 100) + ($c * 10) + $d; } return $this->iSpecificity; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS; interface Renderable { public function __toString(); public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat); public function getLineNo(); }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Rule; use Sabberworm\CSS\Renderable; use Sabberworm\CSS\Value\RuleValueList; use Sabberworm\CSS\Value\Value; use Sabberworm\CSS\Comment\Commentable; class Rule implements Renderable, Commentable { private $sRule; private $mValue; private $bIsImportant; private $aIeHack; protected $iLineNo; protected $aComments; public function __construct($sRule, $iLineNo = 0) { $this->sRule = $sRule; $this->mValue = null; $this->bIsImportant = false; $this->aIeHack = array(); $this->iLineNo = $iLineNo; $this->aComments = array(); } public function getLineNo() { return $this->iLineNo; } public function setRule($sRule) { $this->sRule = $sRule; } public function getRule() { return $this->sRule; } public function getValue() { return $this->mValue; } public function setValue($mValue) { $this->mValue = $mValue; } public function setValues($aSpaceSeparatedValues) { $oSpaceSeparatedList = null; if (count($aSpaceSeparatedValues) > 1) { $oSpaceSeparatedList = new RuleValueList(' ', $this->iLineNo); } foreach ($aSpaceSeparatedValues as $aCommaSeparatedValues) { $oCommaSeparatedList = null; if (count($aCommaSeparatedValues) > 1) { $oCommaSeparatedList = new RuleValueList(',', $this->iLineNo); } foreach ($aCommaSeparatedValues as $mValue) { if (!$oSpaceSeparatedList && !$oCommaSeparatedList) { $this->mValue = $mValue; return $mValue; } if ($oCommaSeparatedList) { $oCommaSeparatedList->addListComponent($mValue); } else { $oSpaceSeparatedList->addListComponent($mValue); } } if (!$oSpaceSeparatedList) { $this->mValue = $oCommaSeparatedList; return $oCommaSeparatedList; } else { $oSpaceSeparatedList->addListComponent($oCommaSeparatedList); } } $this->mValue = $oSpaceSeparatedList; return $oSpaceSeparatedList; } public function getValues() { if (!$this->mValue instanceof RuleValueList) { return array(array($this->mValue)); } if ($this->mValue->getListSeparator() === ',') { return array($this->mValue->getListComponents()); } $aResult = array(); foreach ($this->mValue->getListComponents() as $mValue) { if (!$mValue instanceof RuleValueList || $mValue->getListSeparator() !== ',') { $aResult[] = array($mValue); continue; } if ($this->mValue->getListSeparator() === ' ' || count($aResult) === 0) { $aResult[] = array(); } foreach ($mValue->getListComponents() as $mValue) { $aResult[count($aResult) - 1][] = $mValue; } } return $aResult; } public function addValue($mValue, $sType = ' ') { if (!is_array($mValue)) { $mValue = array($mValue); } if (!$this->mValue instanceof RuleValueList || $this->mValue->getListSeparator() !== $sType) { $mCurrentValue = $this->mValue; $this->mValue = new RuleValueList($sType, $this->iLineNo); if ($mCurrentValue) { $this->mValue->addListComponent($mCurrentValue); } } foreach ($mValue as $mValueItem) { $this->mValue->addListComponent($mValueItem); } } public function addIeHack($iModifier) { $this->aIeHack[] = $iModifier; } public function setIeHack(array $aModifiers) { $this->aIeHack = $aModifiers; } public function getIeHack() { return $this->aIeHack; } public function setIsImportant($bIsImportant) { $this->bIsImportant = $bIsImportant; } public function getIsImportant() { return $this->bIsImportant; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $sResult = "{$this->sRule}:{$oOutputFormat->spaceAfterRuleName()}"; if ($this->mValue instanceof Value) { $sResult .= $this->mValue->render($oOutputFormat); } else { $sResult .= $this->mValue; } if (!empty($this->aIeHack)) { $sResult .= ' \\' . implode('\\', $this->aIeHack); } if ($this->bIsImportant) { $sResult .= ' !important'; } $sResult .= ';'; return $sResult; } public function addComments(array $aComments) { $this->aComments = array_merge($this->aComments, $aComments); } public function getComments() { return $this->aComments; } public function setComments(array $aComments) { $this->aComments = $aComments; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\RuleSet; use Sabberworm\CSS\Property\AtRule; class AtRuleSet extends RuleSet implements AtRule { private $sType; private $sArgs; public function __construct($sType, $sArgs = '', $iLineNo = 0) { parent::__construct($iLineNo); $this->sType = $sType; $this->sArgs = $sArgs; } public function atRuleName() { return $this->sType; } public function atRuleArgs() { return $this->sArgs; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $sArgs = $this->sArgs; if($sArgs) { $sArgs = ' ' . $sArgs; } $sResult = "@{$this->sType}$sArgs{$oOutputFormat->spaceBeforeOpeningBrace()}{"; $sResult .= parent::render($oOutputFormat); $sResult .= '}'; return $sResult; } }
|
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\RuleSet; use Sabberworm\CSS\Rule\Rule; use Sabberworm\CSS\Renderable; use Sabberworm\CSS\Comment\Commentable; abstract class RuleSet implements Renderable, Commentable { private $aRules; protected $iLineNo; protected $aComments; public function __construct($iLineNo = 0) { $this->aRules = array(); $this->iLineNo = $iLineNo; $this->aComments = array(); } public function getLineNo() { return $this->iLineNo; } public function addRule(Rule $oRule, Rule $oSibling = null) { $sRule = $oRule->getRule(); if(!isset($this->aRules[$sRule])) { $this->aRules[$sRule] = array(); } $iPosition = count($this->aRules[$sRule]); if ($oSibling !== null) { $iSiblingPos = array_search($oSibling, $this->aRules[$sRule], true); if ($iSiblingPos !== false) { $iPosition = $iSiblingPos; } } array_splice($this->aRules[$sRule], $iPosition, 0, array($oRule)); } public function getRules($mRule = null) { if ($mRule instanceof Rule) { $mRule = $mRule->getRule(); } $aResult = array(); foreach($this->aRules as $sName => $aRules) { if(!$mRule || $sName === $mRule || (strrpos($mRule, '-') === strlen($mRule) - strlen('-') && (strpos($sName, $mRule) === 0 || $sName === substr($mRule, 0, -1)))) { $aResult = array_merge($aResult, $aRules); } } return $aResult; } public function setRules(array $aRules) { $this->aRules = array(); foreach ($aRules as $rule) { $this->addRule($rule); } } public function getRulesAssoc($mRule = null) { $aResult = array(); foreach($this->getRules($mRule) as $oRule) { $aResult[$oRule->getRule()] = $oRule; } return $aResult; } public function removeRule($mRule) { if($mRule instanceof Rule) { $sRule = $mRule->getRule(); if(!isset($this->aRules[$sRule])) { return; } foreach($this->aRules[$sRule] as $iKey => $oRule) { if($oRule === $mRule) { unset($this->aRules[$sRule][$iKey]); } } } else { foreach($this->aRules as $sName => $aRules) { if(!$mRule || $sName === $mRule || (strrpos($mRule, '-') === strlen($mRule) - strlen('-') && (strpos($sName, $mRule) === 0 || $sName === substr($mRule, 0, -1)))) { unset($this->aRules[$sName]); } } } } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $sResult = ''; $bIsFirst = true; foreach ($this->aRules as $aRules) { foreach($aRules as $oRule) { $sRendered = $oOutputFormat->safely(function() use ($oRule, $oOutputFormat) { return $oRule->render($oOutputFormat->nextLevel()); }); if($sRendered === null) { continue; } if($bIsFirst) { $bIsFirst = false; $sResult .= $oOutputFormat->nextLevel()->spaceBeforeRules(); } else { $sResult .= $oOutputFormat->nextLevel()->spaceBetweenRules(); } $sResult .= $sRendered; } } if(!$bIsFirst) { $sResult .= $oOutputFormat->spaceAfterRules(); } return $oOutputFormat->removeLastSemicolon($sResult); } public function addComments(array $aComments) { $this->aComments = array_merge($this->aComments, $aComments); } public function getComments() { return $this->aComments; } public function setComments(array $aComments) { $this->aComments = $aComments; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS; use Sabberworm\CSS\Rule\Rule; class Settings { public $bMultibyteSupport; public $sDefaultCharset = 'utf-8'; public $bLenientParsing = true; private function __construct() { $this->bMultibyteSupport = extension_loaded('mbstring'); } public static function create() { return new Settings(); } public function withMultibyteSupport($bMultibyteSupport = true) { $this->bMultibyteSupport = $bMultibyteSupport; return $this; } public function withDefaultCharset($sDefaultCharset) { $this->sDefaultCharset = $sDefaultCharset; return $this; } public function withLenientParsing($bLenientParsing = true) { $this->bLenientParsing = $bLenientParsing; return $this; } public function beStrict() { return $this->withLenientParsing(false); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class CSSFunction extends ValueList { protected $sName; public function __construct($sName, $aArguments, $sSeparator = ',', $iLineNo = 0) { if($aArguments instanceof RuleValueList) { $sSeparator = $aArguments->getListSeparator(); $aArguments = $aArguments->getListComponents(); } $this->sName = $sName; $this->iLineNo = $iLineNo; parent::__construct($aArguments, $sSeparator, $iLineNo); } public function getName() { return $this->sName; } public function setName($sName) { $this->sName = $sName; } public function getArguments() { return $this->aComponents; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $aArguments = parent::render($oOutputFormat); return "{$this->sName}({$aArguments})"; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class CSSString extends PrimitiveValue { private $sString; public function __construct($sString, $iLineNo = 0) { $this->sString = $sString; parent::__construct($iLineNo); } public function setString($sString) { $this->sString = $sString; } public function getString() { return $this->sString; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $sString = addslashes($this->sString); $sString = str_replace("\n", '\A', $sString); return $oOutputFormat->getStringQuotingType() . $sString . $oOutputFormat->getStringQuotingType(); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class CalcFunction extends CSSFunction { const T_OPERAND = 1; const T_OPERATOR = 2; }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class CalcRuleValueList extends RuleValueList { public function __construct($iLineNo = 0) { parent::__construct(array(), ',', $iLineNo); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return $oOutputFormat->implode(' ', $this->aComponents); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class Color extends CSSFunction { public function __construct($aColor, $iLineNo = 0) { parent::__construct(implode('', array_keys($aColor)), $aColor, ',', $iLineNo); } public function getColor() { return $this->aComponents; } public function setColor($aColor) { $this->setName(implode('', array_keys($aColor))); $this->aComponents = $aColor; } public function getColorDescription() { return $this->getName(); } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { if($oOutputFormat->getRGBHashNotation() && implode('', array_keys($this->aComponents)) === 'rgb') { $sResult = sprintf( '%02x%02x%02x', $this->aComponents['r']->getSize(), $this->aComponents['g']->getSize(), $this->aComponents['b']->getSize() ); return '#'.(($sResult[0] == $sResult[1]) && ($sResult[2] == $sResult[3]) && ($sResult[4] == $sResult[5]) ? "$sResult[0]$sResult[2]$sResult[4]" : $sResult); } return parent::render($oOutputFormat); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class LineName extends ValueList { public function __construct($aComponents = array(), $iLineNo = 0) { parent::__construct($aComponents, ' ', $iLineNo); } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return '[' . parent::render(\Sabberworm\CSS\OutputFormat::createCompact()) . ']'; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; abstract class PrimitiveValue extends Value { public function __construct($iLineNo = 0) { parent::__construct($iLineNo); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class RuleValueList extends ValueList { public function __construct($sSeparator = ',', $iLineNo = 0) { parent::__construct(array(), $sSeparator, $iLineNo); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class Size extends PrimitiveValue { const ABSOLUTE_SIZE_UNITS = 'px/cm/mm/mozmm/in/pt/pc/vh/vw/vm/vmin/vmax/rem'; const RELATIVE_SIZE_UNITS = '%/em/ex/ch/fr'; const NON_SIZE_UNITS = 'deg/grad/rad/s/ms/turns/Hz/kHz'; private $fSize; private $sUnit; private $bIsColorComponent; public function __construct($fSize, $sUnit = null, $bIsColorComponent = false, $iLineNo = 0) { parent::__construct($iLineNo); $this->fSize = floatval($fSize); $this->sUnit = $sUnit; $this->bIsColorComponent = $bIsColorComponent; } public function setUnit($sUnit) { $this->sUnit = $sUnit; } public function getUnit() { return $this->sUnit; } public function setSize($fSize) { $this->fSize = floatval($fSize); } public function getSize() { return $this->fSize; } public function isColorComponent() { return $this->bIsColorComponent; } public function isSize() { if (in_array($this->sUnit, explode('/', self::NON_SIZE_UNITS))) { return false; } return !$this->isColorComponent(); } public function isRelative() { if (in_array($this->sUnit, explode('/', self::RELATIVE_SIZE_UNITS))) { return true; } if ($this->sUnit === null && $this->fSize != 0) { return true; } return false; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { $l = localeconv(); $sPoint = preg_quote($l['decimal_point'], '/'); return preg_replace(array("/$sPoint/", "/^(-?)0\./"), array('.', '$1.'), $this->fSize) . ($this->sUnit === null ? '' : $this->sUnit); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; class URL extends PrimitiveValue { private $oURL; public function __construct(CSSString $oURL, $iLineNo = 0) { parent::__construct($iLineNo); $this->oURL = $oURL; } public function setURL(CSSString $oURL) { $this->oURL = $oURL; } public function getURL() { return $this->oURL; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return "url({$this->oURL->render($oOutputFormat)})"; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; use Sabberworm\CSS\Renderable; abstract class Value implements Renderable { protected $iLineNo; public function __construct($iLineNo = 0) { $this->iLineNo = $iLineNo; } public function getLineNo() { return $this->iLineNo; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace Sabberworm\CSS\Value; abstract class ValueList extends Value { protected $aComponents; protected $sSeparator; public function __construct($aComponents = array(), $sSeparator = ',', $iLineNo = 0) { parent::__construct($iLineNo); if (!is_array($aComponents)) { $aComponents = array($aComponents); } $this->aComponents = $aComponents; $this->sSeparator = $sSeparator; } public function addListComponent($mComponent) { $this->aComponents[] = $mComponent; } public function getListComponents() { return $this->aComponents; } public function setListComponents($aComponents) { $this->aComponents = $aComponents; } public function getListSeparator() { return $this->sSeparator; } public function setListSeparator($sSeparator) { $this->sSeparator = $sSeparator; } public function __toString() { return $this->render(new \Sabberworm\CSS\OutputFormat()); } public function render(\Sabberworm\CSS\OutputFormat $oOutputFormat) { return $oOutputFormat->implode($oOutputFormat->spaceBeforeListArgumentSeparator($this->sSeparator) . $this->sSeparator . $oOutputFormat->spaceAfterListArgumentSeparator($this->sSeparator), $this->aComponents); } }
|
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace FtpClient; class FtpException extends \Exception {}
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
namespace FtpClient; class FtpWrapper { protected $conn; public function __construct(&$connection) { $this->conn = &$connection; } public function __call($function, array $arguments) { $function = 'ftp_' . $function; if (function_exists($function)) { array_unshift($arguments, $this->conn); return call_user_func_array($function, $arguments); } throw new FtpException("{$function} is not a valid FTP function"); } public function connect($host, $port = 21, $timeout = 90) { return ftp_connect($host, $port, $timeout); } public function ssl_connect($host, $port = 21, $timeout = 90) { return ftp_ssl_connect($host, $port, $timeout); } }
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class Archive extends WP2Static { public function __construct() { $this->loadSettings( array( 'wpenv' ) ); $this->path = ''; $this->name = ''; $this->crawl_list = ''; $this->export_log = ''; } public function setToCurrentArchive() { $handle = fopen( $this->settings['wp_uploads_path'] . '/WP2STATIC-CURRENT-ARCHIVE.txt', 'r' ); $this->path = stream_get_line( $handle, 0 ); $this->name = basename( $this->path ); } public function currentArchiveExists() { return is_file( $this->settings['wp_uploads_path'] . '/WP2STATIC-CURRENT-ARCHIVE.txt' ); } public function create() { $this->name = $this->settings['wp_uploads_path'] . '/wp-static-html-output-' . time(); $this->path = $this->name . '/'; $this->name = basename( $this->path ); if ( wp_mkdir_p( $this->path ) ) { $result = file_put_contents( $this->settings['wp_uploads_path'] . '/WP2STATIC-CURRENT-ARCHIVE.txt', $this->path ); if ( ! $result ) { require_once dirname( __FILE__ ) . '/../WP2Static/WsLog.php'; WsLog::l( 'USER WORKING DIRECTORY NOT WRITABLE' ); } chmod( $this->settings['wp_uploads_path'] . '/WP2STATIC-CURRENT-ARCHIVE.txt', 0664 ); } else { error_log( "Couldn't create archive directory at " . $this->path ); } } }
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WPSHO_DBSettings { public static function get( $sets = array() ) { $plugin = WP2Static_Controller::getInstance(); $settings = array(); $key_sets = array(); $target_keys = array(); $key_sets['general'] = array( 'baseUrl', 'debug_mode', 'selected_deployment_option', ); $key_sets['crawling'] = array( 'additionalUrls', 'excludeURLs', 'useBasicAuth', 'basicAuthPassword', 'basicAuthUser', 'detection_level', 'crawl_delay', 'crawlPort', ); $key_sets['processing'] = array( 'removeConditionalHeadComments', 'allowOfflineUsage', 'baseHREF', 'rewrite_rules', 'rename_rules', 'removeWPMeta', 'removeWPLinks', 'useBaseHref', 'useRelativeURLs', 'removeConditionalHeadComments', 'removeWPMeta', 'removeWPLinks', 'removeHTMLComments', ); $key_sets['advanced'] = array( 'crawl_increment', 'completionEmail', 'delayBetweenAPICalls', 'deployBatchSize', ); $key_sets['folder'] = array( 'baseUrl-folder', 'targetFolder', ); $key_sets['zip'] = array( 'baseUrl-zip', 'allowOfflineUsage', ); $key_sets['github'] = array( 'baseUrl-github', 'ghBranch', 'ghPath', 'ghToken', 'ghRepo', 'ghCommitMessage', ); $key_sets['bitbucket'] = array( 'baseUrl-bitbucket', 'bbBranch', 'bbPath', 'bbToken', 'bbRepo', ); $key_sets['gitlab'] = array( 'baseUrl-gitlab', 'glBranch', 'glPath', 'glToken', 'glProject', ); $key_sets['ftp'] = array( 'baseUrl-ftp', 'ftpPassword', 'ftpRemotePath', 'ftpServer', 'ftpPort', 'ftpTLS', 'ftpUsername', 'useActiveFTP', ); $key_sets['bunnycdn'] = array( 'baseUrl-bunnycdn', 'bunnycdnStorageZoneAccessKey', 'bunnycdnPullZoneAccessKey', 'bunnycdnPullZoneID', 'bunnycdnStorageZoneName', 'bunnycdnRemotePath', ); $key_sets['s3'] = array( 'baseUrl-s3', 'cfDistributionId', 's3Bucket', 's3Key', 's3Region', 's3RemotePath', 's3Secret', ); $key_sets['netlify'] = array( 'baseUrl-netlify', 'netlifyHeaders', 'netlifyPersonalAccessToken', 'netlifyRedirects', 'netlifySiteID', ); $key_sets['wpenv'] = array( 'wp_site_url', 'wp_site_path', 'wp_site_subdir', 'wp_uploads_path', 'wp_uploads_url', 'wp_active_theme', 'wp_themes', 'wp_uploads', 'wp_plugins', 'wp_content', 'wp_inc', ); foreach ( $sets as $set ) { $target_keys = array_merge( $target_keys, $key_sets[ $set ] ); } foreach ( $target_keys as $key ) { $settings[ $key ] = $plugin->options->{ $key }; } require_once dirname( __FILE__ ) . '/../WP2Static/WPSite.php'; $wp_site = new WPSite(); foreach ( $key_sets['wpenv'] as $key ) { $settings[ $key ] = $wp_site->{ $key }; } $settings['crawl_increment'] = isset( $plugin->options->crawl_increment ) ? (int) $plugin->options->crawl_increment : 1; $settings['baseUrl'] = rtrim( $plugin->options->baseUrl, '/' ) . '/'; return array_filter( $settings ); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class Deployer extends WP2Static { public function __construct() { $this->loadSettings( array( 'advanced', ) ); } public function deploy( $test = false ) { $method = $this->settings['selected_deployment_option']; WP_CLI::log( 'Deploying static site via: ' . $method ); $start_time = microtime( true ); $deployers_dir = dirname( __FILE__ ) . '/../deployers'; switch ( $this->settings['selected_deployment_option'] ) { case 'folder': break; case 'zip': break; case 's3': require_once dirname( __FILE__ ) . '/../WP2Static/SitePublisher.php'; require_once $deployers_dir . '/S3.php'; if ( $test ) { error_log( 'testing s3 deploy' ); $s3->test_s3(); return; } $s3->bootstrap(); $s3->loadArchive(); $s3->prepareDeploy(); $s3->upload_files(); $s3->cloudfront_invalidate_all_items(); break; case 'bitbucket': require_once dirname( __FILE__ ) . '/../WP2Static/SitePublisher.php'; require_once $deployers_dir . '/Bitbucket.php'; if ( $test ) { error_log( 'testing bitbucket deploy' ); $bitbucket->test_upload(); return; } $bitbucket->bootstrap(); $bitbucket->loadArchive(); $bitbucket->prepareDeploy( true ); $bitbucket->upload_files(); break; case 'bunnycdn': require_once dirname( __FILE__ ) . '/../WP2Static/SitePublisher.php'; require_once $deployers_dir . '/BunnyCDN.php'; if ( $test ) { error_log( 'testing BunnyCDN deploy' ); $bunny->test_deploy(); return; } $bunny->bootstrap(); $bunny->loadArchive(); $bunny->prepareDeploy( true ); $bunny->upload_files(); $bunny->purge_all_cache(); break; case 'ftp': require_once dirname( __FILE__ ) . '/../WP2Static/SitePublisher.php'; require_once $deployers_dir . '/FTP.php'; if ( $test ) { error_log( 'testing FTP deploy' ); $ftp->test_ftp(); return; } $ftp->bootstrap(); $ftp->loadArchive(); $ftp->prepareDeploy(); $ftp->upload_files(); break; case 'github': require_once dirname( __FILE__ ) . '/../WP2Static/SitePublisher.php'; require_once $deployers_dir . '/GitHub.php'; if ( $test ) { error_log( 'testing GitHub deploy' ); $github->test_upload(); return; } $github->bootstrap(); $github->loadArchive(); $github->prepareDeploy( true ); $github->upload_files(); break; case 'gitlab': require_once dirname( __FILE__ ) . '/../WP2Static/SitePublisher.php'; require_once $deployers_dir . '/GitLab.php'; if ( $test ) { error_log( 'testing GitLab deploy' ); $gitlab->test_file_create(); return; } $gitlab->bootstrap(); $gitlab->loadArchive(); $gitlab->getListOfFilesInRepo(); $gitlab->prepareDeploy( true ); $gitlab->upload_files(); break; case 'netlify': require_once dirname( __FILE__ ) . '/../WP2Static/SitePublisher.php'; require_once $deployers_dir . '/Netlify.php'; if ( $test ) { error_log( 'testing Netlify deploy' ); $gitlab->loadArchive(); $netlify->test_netlify(); return; } $netlify->bootstrap(); $netlify->loadArchive(); $netlify->deploy(); break; } $end_time = microtime( true ); $duration = $end_time - $start_time; WP_CLI::success( 'Deployed to: ' . $method . ' in ' . date( 'H:i:s', $duration ) ); $this->finalizeDeployment(); } public function finalizeDeployment() { $this->emailDeployNotification(); $this->triggerPostDeployHooks(); } public function emailDeployNotification() { if ( ! isset( $this->settings['completionEmail'] ) ) { return; } if ( defined( 'WP_CLI' ) ) { WP_CLI::line( 'Sending confirmation email...' ); } $current_user = wp_get_current_user(); $to = $current_user->user_email; $subject = 'Static site deployment: ' . $site_title = get_bloginfo( 'name' ); $body = 'Your WordPress site has been automatically deployed.'; $headers = array( 'Content-Type: text/html; charset=UTF-8' ); wp_mail( $to, $subject, $body, $headers ); } public function triggerPostDeployHooks() { require_once dirname( __FILE__ ) . '/Archive.php'; $this->archive = new Archive(); $this->archive->setToCurrentArchive(); do_action( 'wp2static_post_deploy_trigger', $this->archive ); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
$ajax_action = isset( $_POST['ajax_action'] ) ? $_POST['ajax_action'] : ''; $deployers_dir = dirname( __FILE__ ) . '/../deployers'; if ( $ajax_action === 'crawl_site' || $ajax_action === 'crawl_again' ) { require_once dirname( __FILE__ ) . '/WP2Static.php'; require_once dirname( __FILE__ ) . '/SiteCrawler.php'; wp_die(); return null; } elseif ( $ajax_action == 'bitbucket_prepare_export' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/Bitbucket.php'; wp_die(); return null; } elseif ( $ajax_action == 'bitbucket_upload_files' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/Bitbucket.php'; wp_die(); return null; } elseif ( $ajax_action == 'github_prepare_export' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/GitHub.php'; wp_die(); return null; } elseif ( $ajax_action == 'github_upload_files' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/GitHub.php'; wp_die(); return null; } elseif ( $ajax_action == 'test_github' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/GitHub.php'; wp_die(); return null; } elseif ( $ajax_action == 'gitlab_prepare_export' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/GitLab.php'; wp_die(); return null; } elseif ( $ajax_action == 'gitlab_upload_files' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/GitLab.php'; wp_die(); return null; } elseif ( $ajax_action == 'test_gitlab' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/GitLab.php'; wp_die(); return null; } elseif ( $ajax_action == 'test_bitbucket' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/Bitbucket.php'; wp_die(); return null; } elseif ( $ajax_action == 'test_netlify' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/Netlify.php'; wp_die(); return null; } elseif ( $ajax_action == 'netlify_do_export' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/Netlify.php'; wp_die(); return null; } elseif ( $ajax_action == 'test_s3' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/S3.php'; wp_die(); return null; } elseif ( $ajax_action == 's3_prepare_export' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/S3.php'; wp_die(); return null; } elseif ( $ajax_action == 's3_transfer_files' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/S3.php'; wp_die(); return null; } elseif ( $ajax_action == 'cloudfront_invalidate_all_items' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/S3.php'; wp_die(); return null; } elseif ( $ajax_action == 'test_ftp' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/FTP.php'; wp_die(); return null; } elseif ( $ajax_action == 'ftp_prepare_export' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/FTP.php'; wp_die(); return null; } elseif ( $ajax_action == 'ftp_transfer_files' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/FTP.php'; wp_die(); return null; } elseif ( $ajax_action == 'test_bunny' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/BunnyCDN.php'; wp_die(); return null; } elseif ( $ajax_action == 'bunnycdn_prepare_export' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/BunnyCDN.php'; wp_die(); return null; } elseif ( $ajax_action == 'bunnycdn_transfer_files' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/BunnyCDN.php'; wp_die(); return null; } elseif ( $ajax_action == 'bunnycdn_purge_cache' ) { require_once dirname( __FILE__ ) . '/SitePublisher.php'; require_once $deployers_dir . '/BunnyCDN.php'; wp_die(); return null; }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class Exporter extends WP2Static { public function __construct() { $this->loadSettings( array( 'wpenv', 'crawling', 'advanced', ) ); } public function pre_export_cleanup() { $files_to_clean = array( 'WP-STATIC-2ND-CRAWL-LIST.txt', 'WP-STATIC-404-LOG.txt', 'WP-STATIC-CRAWLED-LINKS.txt', 'WP-STATIC-DISCOVERED-URLS-LOG.txt', 'WP-STATIC-DISCOVERED-URLS.txt', 'WP2STATIC-FILES-TO-DEPLOY.txt', 'WP-STATIC-EXPORT-LOG.txt', 'WP-STATIC-FINAL-2ND-CRAWL-LIST.txt', 'WP-STATIC-FINAL-CRAWL-LIST.txt', 'WP2STATIC-GITLAB-FILES-IN-REPO.txt', ); foreach ( $files_to_clean as $file_to_clean ) { if ( file_exists( $this->settings['wp_uploads_path'] . '/' . $file_to_clean ) ) { unlink( $this->settings['wp_uploads_path'] . '/' . $file_to_clean ); } } } public function cleanup_working_files() { if ( is_file( $this->settings['wp_uploads_path'] . '/WP2STATIC-CURRENT-ARCHIVE.txt' ) ) { $handle = fopen( $this->settings['wp_uploads_path'] . '/WP2STATIC-CURRENT-ARCHIVE.txt', 'r' ); $this->settings['archive_dir'] = stream_get_line( $handle, 0 ); } $files_to_clean = array( '/WP-STATIC-2ND-CRAWL-LIST.txt', '/WP-STATIC-CRAWLED-LINKS.txt', '/WP-STATIC-DISCOVERED-URLS.txt', '/WP2STATIC-FILES-TO-DEPLOY.txt', '/WP-STATIC-FINAL-2ND-CRAWL-LIST.txt', '/WP-STATIC-FINAL-CRAWL-LIST.txt', '/WP2STATIC-GITLAB-FILES-IN-REPO.txt', ); foreach ( $files_to_clean as $file_to_clean ) { if ( file_exists( $this->settings['wp_uploads_path'] . '/' . $file_to_clean ) ) { unlink( $this->settings['wp_uploads_path'] . '/' . $file_to_clean ); } } } public function initialize_cache_files() { $crawled_links_file = $this->settings['wp_uploads_path'] . '/WP-STATIC-CRAWLED-LINKS.txt'; $resource = fopen( $crawled_links_file, 'w' ); fwrite( $resource, '' ); fclose( $resource ); } public function cleanup_leftover_archives() { $leftover_files = preg_grep( '/^([^.])/', scandir( $this->settings['wp_uploads_path'] ) ); foreach ( $leftover_files as $filename ) { if ( strpos( $filename, 'wp-static-html-output-' ) !== false ) { $deletion_target = $this->settings['wp_uploads_path'] . '/' . $filename; if ( is_dir( $deletion_target ) ) { WP2Static_FilesHelper::delete_dir_with_files( $deletion_target ); } else { unlink( $deletion_target ); } } } if ( ! defined( 'WP_CLI' ) ) { echo 'SUCCESS'; } } public function generateModifiedFileList() { copy( $this->settings['wp_uploads_path'] . '/WP-STATIC-INITIAL-CRAWL-LIST.txt', $this->settings['wp_uploads_path'] . '/WP-STATIC-MODIFIED-CRAWL-LIST.txt' ); chmod( $this->settings['wp_uploads_path'] . '/WP-STATIC-MODIFIED-CRAWL-LIST.txt', 0664 ); if ( ! isset( $this->settings['excludeURLs'] ) && ! isset( $this->settings['additionalUrls'] ) ) { copy( $this->settings['wp_uploads_path'] . '/WP-STATIC-INITIAL-CRAWL-LIST.txt', $this->settings['wp_uploads_path'] . '/WP-STATIC-FINAL-CRAWL-LIST.txt' ); return; } $modified_crawl_list = array(); $crawl_list = file( $this->settings['wp_uploads_path'] . '/WP-STATIC-MODIFIED-CRAWL-LIST.txt' ); if ( isset( $this->settings['excludeURLs'] ) ) { $exclusions = explode( "\n", str_replace( "\r", '', $this->settings['excludeURLs'] ) ); foreach ( $crawl_list as $url_to_crawl ) { $url_to_crawl = trim( $url_to_crawl ); $match = false; foreach ( $exclusions as $exclusion ) { $exclusion = trim( $exclusion ); if ( $exclusion != '' ) { if ( strpos( $url_to_crawl, $exclusion ) !== false ) { $this->logAction( 'Excluding ' . $url_to_crawl . ' because of rule ' . $exclusion ); $match = true; } } if ( ! $match ) { $modified_crawl_list[] = $url_to_crawl; } } } } else { $modified_crawl_list = $crawl_list; } if ( isset( $this->settings['additionalUrls'] ) ) { $inclusions = explode( "\n", str_replace( "\r", '', $this->settings['additionalUrls'] ) ); foreach ( $inclusions as $inclusion ) { $inclusion = trim( $inclusion ); $inclusion = $inclusion; $modified_crawl_list[] = $inclusion; } } $modified_crawl_list = array_unique( $modified_crawl_list ); $str = implode( PHP_EOL, $modified_crawl_list ); file_put_contents( $this->settings['wp_uploads_path'] . '/WP-STATIC-FINAL-CRAWL-LIST.txt', $str ); chmod( $this->settings['wp_uploads_path'] . '/WP-STATIC-FINAL-CRAWL-LIST.txt', 0664 ); } public function logAction( $action ) { if ( ! isset( $this->settings['debug_mode'] ) ) { return; } require_once dirname( __FILE__ ) . '/../WP2Static/WsLog.php'; WsLog::l( $action ); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class FileCopier { public function __construct( $url, $wp_site_url, $wp_site_path ) { $this->url = $url; $this->wp_site_url = $wp_site_url; $this->wp_site_path = $wp_site_path; } public function getLocalFileForURL() { $local_file = str_replace( $this->wp_site_url, $this->wp_site_path, $this->url ); if ( is_file( $local_file ) ) { return $local_file; } else { require_once dirname( __FILE__ ) . '/../WP2Static/WsLog.php'; WsLog::l( 'ERROR: trying to copy local file: ' . $local_file . ' for URL: ' . $this->url . ' (FILE NOT FOUND/UNREADABLE)' ); } } public function copyFile( $archive_dir ) { $url_info = parse_url( $this->url ); $path_info = array(); $local_file = $this->getLocalFileForURL(); if ( ! isset( $url_info['path'] ) ) { return false; } $path_info = pathinfo( $url_info['path'] ); $directory_in_archive = isset( $path_info['dirname'] ) ? $path_info['dirname'] : ''; if ( ! empty( $this->settings['wp_site_subdir'] ) ) { $directory_in_archive = str_replace( $this->settings['wp_site_subdir'], '', $directory_in_archive ); } $file_dir = $archive_dir . ltrim( $directory_in_archive, '/' ); if ( ! file_exists( $file_dir ) ) { wp_mkdir_p( $file_dir ); } $file_extension = $path_info['extension']; $basename = $path_info['filename'] . '.' . $file_extension; $filename = $file_dir . '/' . $basename; $filename = str_replace( '//', '/', $filename ); if ( is_file( $local_file ) ) { copy( $local_file, $filename ); } else { require_once dirname( __FILE__ ) . '/../WP2Static/WsLog.php'; WsLog::l( 'ERROR: trying to copy local file: ' . $local_file . ' to: ' . $filename . ' in archive dir: ' . $archive_dir . ' (FILE NOT FOUND/UNREADABLE)' ); } } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class FileWriter extends WP2Static { public function __construct( $url, $content, $file_type, $content_type ) { $this->url = $url; $this->content = $content; $this->file_type = $file_type; $this->content_type = $content_type; $this->loadSettings( array( 'wpenv', ) ); } public function saveFile( $archive_dir ) { $url_info = parse_url( $this->url ); $path_info = array(); if ( ! isset( $url_info['path'] ) ) { return false; } if ( $url_info['path'] != '/' ) { $path_info = pathinfo( $url_info['path'] ); } else { $path_info = pathinfo( 'index.html' ); } $directory_in_archive = isset( $path_info['dirname'] ) ? $path_info['dirname'] : ''; if ( ! empty( $this->settings['wp_site_subdir'] ) ) { $directory_in_archive = str_replace( $this->settings['wp_site_subdir'], '', $directory_in_archive ); } $file_dir = $archive_dir . ltrim( $directory_in_archive, '/' ); if ( empty( $path_info['extension'] ) && $path_info['basename'] === $path_info['filename'] ) { $file_dir .= '/' . $path_info['basename']; $path_info['filename'] = 'index'; } if ( ! file_exists( $file_dir ) ) { wp_mkdir_p( $file_dir ); } $file_extension = ''; if ( isset( $path_info['extension'] ) ) { $file_extension = $path_info['extension']; } elseif ( $this->file_type == 'html' ) { $file_extension = 'html'; } elseif ( $this->file_type == 'xml' ) { $file_extension = 'html'; } $filename = ''; if ( $url_info['path'] == '/' ) { $filename = rtrim( $file_dir, '.' ) . 'index.html'; } else { if ( ! empty( $this->settings['wp_site_subdir'] ) ) { $file_dir = str_replace( '/' . $this->settings['wp_site_subdir'], '/', $file_dir ); } $filename = $file_dir . '/' . $path_info['filename'] . '.' . $file_extension; } $file_contents = $this->content; if ( $file_contents ) { $this->logAction( 'SAVING ' . $this->url . ' to ' . $filename ); file_put_contents( $filename, $file_contents ); chmod( $filename, 0664 ); } else { $this->logAction( 'NOT SAVING EMTPY FILE ' . $this->url ); } } public function logAction( $action ) { if ( ! isset( $this->settings['debug_mode'] ) ) { return; } require_once dirname( __FILE__ ) . '/WsLog.php'; WsLog::l( $action ); } }
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WP2Static_Options { protected $wp2static_options = array(); protected $wp2static_option_key = null; protected $wp2static_options_keys = array( 'additionalUrls', 'allowOfflineUsage', 'baseHREF', 'baseUrl', 'baseUrl-bitbucket', 'baseUrl-bunnycdn', 'baseUrl-folder', 'baseUrl-ftp', 'baseUrl-github', 'baseUrl-gitlab', 'baseUrl-netlify', 'baseUrl-s3', 'baseUrl-zip', 'baseUrl-zip', 'basicAuthPassword', 'basicAuthUser', 'bbBranch', 'bbPath', 'bbRepo', 'bbToken', 'bunnycdnStorageZoneAccessKey', 'bunnycdnPullZoneAccessKey', 'bunnycdnPullZoneID', 'bunnycdnStorageZoneName', 'bunnycdnRemotePath', 'cfDistributionId', 'completionEmail', 'crawl_delay', 'crawl_increment', 'crawlPort', 'debug_mode', 'detection_level', 'delayBetweenAPICalls', 'deployBatchSize', 'excludeURLs', 'ftpPassword', 'ftpRemotePath', 'ftpServer', 'ftpPort', 'ftpTLS', 'ftpUsername', 'ghBranch', 'ghCommitMessage', 'ghPath', 'ghRepo', 'ghToken', 'glBranch', 'glPath', 'glProject', 'glToken', 'netlifyHeaders', 'netlifyPersonalAccessToken', 'netlifyRedirects', 'netlifySiteID', 'removeConditionalHeadComments', 'removeHTMLComments', 'removeWPLinks', 'removeWPMeta', 'rewrite_rules', 'rename_rules', 's3Bucket', 's3Key', 's3Region', 's3RemotePath', 's3Secret', 'selected_deployment_option', 'targetFolder', 'useActiveFTP', 'useBaseHref', 'useBasicAuth', 'useRelativeURLs', ); protected $whitelisted_keys = array( 'additionalUrls', 'allowOfflineUsage', 'baseHREF', 'baseUrl', 'baseUrl-bitbucket', 'baseUrl-bunnycdn', 'baseUrl-folder', 'baseUrl-ftp', 'baseUrl-github', 'baseUrl-gitlab', 'baseUrl-netlify', 'baseUrl-s3', 'baseUrl-zip', 'baseUrl-zip', 'basicAuthUser', 'bbBranch', 'bbPath', 'bbRepo', 'bunnycdnPullZoneID', 'bunnycdnStorageZoneName', 'bunnycdnRemotePath', 'cfDistributionId', 'completionEmail', 'crawl_delay', 'crawl_increment', 'crawlPort', 'debug_mode', 'detection_level', 'delayBetweenAPICalls', 'deployBatchSize', 'excludeURLs', 'ftpRemotePath', 'ftpServer', 'ftpPort', 'ftpTLS', 'ftpUsername', 'ghBranch', 'ghCommitMessage', 'ghPath', 'ghRepo', 'glBranch', 'glPath', 'glProject', 'netlifyHeaders', 'netlifyRedirects', 'netlifySiteID', 'removeConditionalHeadComments', 'removeHTMLComments', 'removeWPLinks', 'removeWPMeta', 'rewrite_rules', 'rename_rules', 's3Bucket', 's3Key', 's3Region', 's3RemotePath', 'selected_deployment_option', 'targetFolder', 'useActiveFTP', 'useBaseHref', 'useBasicAuth', 'useRelativeURLs', ); public function __construct( $option_key ) { $options = get_option( $option_key ); if ( false === $options ) { $options = array(); } $this->wp2static_options = $options; $this->wp2static_option_key = $option_key; } public function __set( $name, $value ) { $this->wp2static_options[ $name ] = $value; return $this; } public function setOption( $name, $value ) { return $this->__set( $name, $value ); } public function __get( $name ) { $value = array_key_exists( $name, $this->wp2static_options ) ? $this->wp2static_options[ $name ] : null; return $value; } public function getOption( $name ) { return $this->__get( $name ); } public function getAllOptions( $reveal_sensitive_values = false ) { $options_array = array(); foreach ( $this->wp2static_options_keys as $key ) { $value = '*******************'; if ( in_array( $key, $this->whitelisted_keys ) ) { $value = $this->__get( $key ); } elseif ( $reveal_sensitive_values ) { $value = $this->__get( $key ); } $options_array[] = array( 'Option name' => $key, 'Value' => $value, ); } return $options_array; } public function optionExists( $name ) { return in_array( $name, $this->wp2static_options_keys ); } public function save() { return update_option( $this->wp2static_option_key, $this->wp2static_options ); } public function delete() { return delete_option( $this->wp2static_option_key ); } public function saveAllPostData() { foreach ( $this->wp2static_options_keys as $option ) { $this->setOption( $option, filter_input( INPUT_POST, $option ) ); $this->save(); } } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WPSHO_PostSettings { public static function get( $sets = array() ) { $settings = array(); $key_sets = array(); $target_keys = array(); $key_sets['general'] = array( 'baseUrl', 'debug_mode', 'selected_deployment_option', ); $key_sets['crawling'] = array( 'additionalUrls', 'excludeURLs', 'useBasicAuth', 'basicAuthPassword', 'basicAuthUser', 'detection_level', 'crawl_delay', 'crawlPort', ); $key_sets['processing'] = array( 'removeConditionalHeadComments', 'allowOfflineUsage', 'baseHREF', 'rewrite_rules', 'rename_rules', 'removeWPMeta', 'removeWPLinks', 'useBaseHref', 'useRelativeURLs', 'removeConditionalHeadComments', 'removeWPMeta', 'removeWPLinks', 'removeHTMLComments', ); $key_sets['advanced'] = array( 'crawl_increment', 'completionEmail', 'delayBetweenAPICalls', 'deployBatchSize', ); $key_sets['folder'] = array( 'baseUrl-folder', 'targetFolder', ); $key_sets['zip'] = array( 'baseUrl-zip', 'allowOfflineUsage', ); $key_sets['github'] = array( 'baseUrl-github', 'ghBranch', 'ghPath', 'ghToken', 'ghRepo', 'ghCommitMessage', ); $key_sets['bitbucket'] = array( 'baseUrl-bitbucket', 'bbBranch', 'bbPath', 'bbToken', 'bbRepo', ); $key_sets['gitlab'] = array( 'baseUrl-gitlab', 'glBranch', 'glPath', 'glToken', 'glProject', ); $key_sets['ftp'] = array( 'baseUrl-ftp', 'ftpPassword', 'ftpRemotePath', 'ftpServer', 'ftpPort', 'ftpTLS', 'ftpUsername', 'useActiveFTP', ); $key_sets['bunnycdn'] = array( 'baseUrl-bunnycdn', 'bunnycdnStorageZoneAccessKey', 'bunnycdnPullZoneAccessKey', 'bunnycdnPullZoneID', 'bunnycdnStorageZoneName', 'bunnycdnRemotePath', ); $key_sets['s3'] = array( 'baseUrl-s3', 'cfDistributionId', 's3Bucket', 's3Key', 's3Region', 's3RemotePath', 's3Secret', ); $key_sets['netlify'] = array( 'baseUrl-netlify', 'netlifyHeaders', 'netlifyPersonalAccessToken', 'netlifyRedirects', 'netlifySiteID', ); $key_sets['wpenv'] = array( 'wp_site_url', 'wp_site_path', 'wp_site_subdir', 'wp_uploads_path', 'wp_uploads_url', 'baseUrl', 'wp_active_theme', 'wp_themes', 'wp_uploads', 'wp_plugins', 'wp_content', 'wp_inc', ); foreach ( $sets as $set ) { $target_keys = array_merge( $target_keys, $key_sets[ $set ] ); } foreach ( $target_keys as $key ) { $settings[ $key ] = isset( $_POST[ $key ] ) ? $_POST[ $key ] : null; } $settings['crawl_increment'] = isset( $_POST['crawl_increment'] ) ? (int) $_POST['crawl_increment'] : 1; $settings['baseUrl'] = isset( $_POST['baseUrl'] ) ? rtrim( $_POST['baseUrl'], '/' ) . '/' : 'http://OFFLINEZIP.wpsho'; return array_filter( $settings ); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class ProgressLog { public static function l( $portion, $total ) { if ( $total === 0 ) { return; } $target_settings = array( 'wpenv', ); $wp_uploads_path = ''; if ( defined( 'WP_CLI' ) ) { require_once dirname( __FILE__ ) . '/DBSettings.php'; $settings = WPSHO_DBSettings::get( $target_settings ); $wp_uploads_path = $settings['wp_uploads_path']; } else { $wp_uploads_path = $_POST['wp_uploads_path']; } $log_file_path = $wp_uploads_path . '/WP-STATIC-PROGRESS.txt'; $progress_percent = floor( $portion / $total * 100 ); file_put_contents( $log_file_path, $progress_percent . PHP_EOL, LOCK_EX ); chmod( $log_file_path, 0664 ); } }
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class TXTProcessor extends WP2Static { public function __construct() { $this->loadSettings( array( 'crawling', 'wpenv', 'processing', 'advanced', ) ); } public function processTXT( $txt_document, $page_url ) { if ( $txt_document == '' ) { return false; } $this->txt_doc = $txt_document; $this->destination_protocol = $this->getTargetSiteProtocol( $this->settings['baseUrl'] ); $this->placeholder_url = $this->destination_protocol . 'PLACEHOLDER.wpsho/'; $this->rewriteSiteURLsToPlaceholder(); return true; } public function getTXT() { $processed_txt = $this->txt_doc; $processed_txt = $this->detectEscapedSiteURLs( $processed_txt ); $processed_txt = $this->detectUnchangedURLs( $processed_txt ); return $processed_txt; } public function detectEscapedSiteURLs( $processed_txt ) { $escaped_site_url = addcslashes( $this->placeholder_url, '/' ); if ( strpos( $processed_txt, $escaped_site_url ) !== false ) { return $this->rewriteEscapedURLs( $processed_txt ); } return $processed_txt; } public function detectUnchangedURLs( $processed_txt ) { $site_url = $this->placeholder_url; if ( strpos( $processed_txt, $site_url ) !== false ) { return $this->rewriteUnchangedURLs( $processed_txt ); } return $processed_txt; } public function rewriteUnchangedURLs( $processed_txt ) { if ( ! isset( $this->settings['rewrite_rules'] ) ) { $this->settings['rewrite_rules'] = ''; } $this->settings['rewrite_rules'] .= PHP_EOL . $this->placeholder_url . ',' . $this->settings['baseUrl']; $this->settings['rewrite_rules'] .= PHP_EOL . $this->getProtocolRelativeURL( $this->placeholder_url ) . ',' . $this->getProtocolRelativeURL( $this->settings['baseUrl'] ); $rewrite_from = array(); $rewrite_to = array(); $rewrite_rules = explode( "\n", str_replace( "\r", '', $this->settings['rewrite_rules'] ) ); foreach ( $rewrite_rules as $rewrite_rule_line ) { if ( $rewrite_rule_line ) { list($from, $to) = explode( ',', $rewrite_rule_line ); $rewrite_from[] = $from; $rewrite_to[] = $to; } } $rewritten_source = str_replace( $rewrite_from, $rewrite_to, $processed_txt ); return $rewritten_source; } public function rewriteEscapedURLs( $processed_txt ) { $processed_txt = str_replace( '%5C/', '\\/', $processed_txt ); $site_url = addcslashes( $this->placeholder_url, '/' ); $destination_url = addcslashes( $this->settings['baseUrl'], '/' ); if ( ! isset( $this->settings['rewrite_rules'] ) ) { $this->settings['rewrite_rules'] = ''; } $this->settings['rewrite_rules'] .= PHP_EOL . $site_url . ',' . $destination_url; $rewrite_from = array(); $rewrite_to = array(); $rewrite_rules = explode( "\n", str_replace( "\r", '', $this->settings['rewrite_rules'] ) ); foreach ( $rewrite_rules as $rewrite_rule_line ) { if ( $rewrite_rule_line ) { list($from, $to) = explode( ',', $rewrite_rule_line ); $rewrite_from[] = addcslashes( $from, '/' ); $rewrite_to[] = addcslashes( $to, '/' ); } } $rewritten_source = str_replace( $rewrite_from, $rewrite_to, $processed_txt ); return $rewritten_source; } public function rewriteSiteURLsToPlaceholder() { $patterns = array( $this->settings['wp_site_url'], $this->getProtocolRelativeURL( $this->settings['wp_site_url'] ), $this->getProtocolRelativeURL( rtrim( $this->settings['wp_site_url'], '/' ) ), $this->getProtocolRelativeURL( $this->settings['wp_site_url'] . '//' ), $this->getProtocolRelativeURL( addcslashes( $this->settings['wp_site_url'], '/' ) ), ); $replacements = array( $this->placeholder_url, $this->getProtocolRelativeURL( $this->placeholder_url ), $this->getProtocolRelativeURL( $this->placeholder_url ), $this->getProtocolRelativeURL( $this->placeholder_url . '/' ), $this->getProtocolRelativeURL( addcslashes( $this->placeholder_url, '/' ) ), ); if ( $this->destination_protocol === 'https' ) { $patterns[] = str_replace( 'http:', 'https:', $this->settings['wp_site_url'] ); $replacements[] = $this->placeholder_url; } $rewritten_source = str_replace( $patterns, $replacements, $this->txt_doc ); $this->txt_doc = $rewritten_source; } public function getTargetSiteProtocol( $url ) { $protocol = '//'; if ( strpos( $url, 'https://' ) !== false ) { $protocol = 'https://'; } elseif ( strpos( $url, 'http://' ) !== false ) { $protocol = 'http://'; } else { $protocol = '//'; } return $protocol; } public function getProtocolRelativeURL( $url ) { $this->destination_protocol_relative_url = str_replace( array( 'https:', 'http:', ), array( '', '', ), $url ); return $this->destination_protocol_relative_url; } }
|
@ -0,0 +1,17 @@
|
||||
<?php
|
||||
class TemplateHelper { public function __construct() { } public function displayCheckbox( $tpl_vars, $field_name, $field_label ) { echo "
|
||||
<fieldset>
|
||||
<label for='{$field_name}'>
|
||||
<input name='{$field_name}' id='{$field_name}' value='1' type='checkbox' " . ( $tpl_vars->options->{$field_name} === '1' ? 'checked' : '' ) . ' />
|
||||
<span>' . __( $field_label, 'static-html-output-plugin' ) . '</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
'; } public function displayTextfield( $tpl_vars, $field_name, $field_label, $description, $type = 'text' ) { echo "
|
||||
<input name='{$field_name}' class='regular-text' id='{$field_name}' type='{$type}' value='" . esc_attr( $tpl_vars->options->{$field_name} ) . "' placeholder='" . __( $field_label, 'static-html-output-plugin' ) . "' />
|
||||
<span class='description'>$description</span>
|
||||
<br>
|
||||
"; } public function displaySelectMenu( $tpl_vars, $menu_options, $field_name, $field_label, $description, $type = 'text' ) { $menu_code = "
|
||||
<select name='{$field_name}' id='{$field_name}'>
|
||||
<option></option>"; foreach ( $menu_options as $value => $text ) { if ( $tpl_vars->options->{$field_name} === $value ) { $menu_code .= "
|
||||
<option value='{$value}' selected>{$text}</option>"; } else { $menu_code .= "
|
||||
<option value='{$value}'>{$text}</option>"; } } $menu_code .= '</select>'; echo $menu_code; } public function ifNotEmpty( $value, $substitute = '' ) { $value = $value ? $value : $substitute; echo $value; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WP2Static_View { protected $variables = array(); protected $path = null; protected $directory = 'views'; protected $extension = '.phtml'; protected $template = null; public function __construct() { list($plugin_dir) = explode( '/', plugin_basename( __FILE__ ) ); $path_array = array( WP_PLUGIN_DIR, $plugin_dir, $this->directory ); $this->path = implode( '/', $path_array ); } public function setTemplate( $tpl ) { $this->template = $tpl; $this->variables = array(); return $this; } public function __set( $name, $value ) { $this->variables[ $name ] = $value; return $this; } public function assign( $name, $value ) { return $this->__set( $name, $value ); } public function __get( $name ) { $value = array_key_exists( $name, $this->variables ) ? $this->variables[ $name ] : null; return $value; } public function render() { $file = $this->path . '/' . $this->template . $this->extension; if ( ! is_readable( $file ) ) { error_log( 'Can\'t find view template: ' . $file ); } include $file; return $this; } public function fetch() { ob_start(); $this->render(); $contents = ob_get_contents(); ob_end_clean(); return $contents; } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WP2Static { public function loadSettings( $target_settings ) { $general_settings = array( 'general', ); $target_settings = array_merge( $general_settings, $target_settings ); if ( isset( $_POST['selected_deployment_option'] ) ) { require_once dirname( __FILE__ ) . '/PostSettings.php'; $this->settings = WPSHO_PostSettings::get( $target_settings ); } else { require_once dirname( __FILE__ ) . '/DBSettings.php'; $this->settings = WPSHO_DBSettings::get( $target_settings ); } } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WPSite { public function __construct() { $wp_upload_path_and_url = wp_upload_dir(); $this->uploads_url = $wp_upload_path_and_url['baseurl']; $this->site_url = get_home_url() . '/'; $this->parent_theme_url = get_template_directory_uri(); $this->wp_content_url = content_url(); $this->site_path = ABSPATH; $this->plugins_path = $this->getWPDirFullPath( 'plugins' ); $this->wp_uploads_path = $this->getWPDirFullPath( 'uploads' ); $this->wp_includes_path = $this->getWPDirFullPath( 'wp-includes' ); $this->wp_content_path = $this->getWPDirFullPath( 'wp-content' ); $this->theme_root_path = $this->getWPDirFullPath( 'theme-root' ); $this->parent_theme_path = $this->getWPDirFullPath( 'parent-theme' ); $this->child_theme_path = $this->getWPDirFullPath( 'child-theme' ); $this->child_theme_active = $this->parent_theme_path !== $this->child_theme_path; $this->permalink_structure = get_option( 'permalink_structure' ); $this->wp_inc = '/' . WPINC; $this->wp_content = WP_CONTENT_DIR; $this->wp_uploads = str_replace( ABSPATH, '/', $this->wp_uploads_path ); $this->wp_plugins = str_replace( ABSPATH, '/', WP_PLUGIN_DIR ); $this->wp_themes = str_replace( ABSPATH, '/', get_theme_root() ); $this->wp_active_theme = str_replace( home_url(), '', get_template_directory_uri() ); $this->detect_base_url(); $this->subdirectory = $this->isSiteInstalledInSubDirectory(); $this->wp_site_subdir = $this->subdirectory; $this->wp_site_url = $this->site_url; $this->wp_site_path = $this->site_path; $this->wp_uploads_url = $this->uploads_url; $this->uploads_writable = $this->uploadsPathIsWritable(); $this->permalinks_set = $this->permalinksAreDefined(); $this->curl_enabled = $this->hasCurlSupport(); } public function isSiteInstalledInSubDirectory() { $parsed_site_url = parse_url( rtrim( $this->site_url, '/' ) ); if ( isset( $parsed_site_url['path'] ) ) { return $parsed_site_url['path']; } return false; } public function uploadsPathIsWritable() { return $this->wp_uploads_path && is_writable( $this->wp_uploads_path ); } public function hasCurlSupport() { return extension_loaded( 'curl' ); } public function permalinksAreDefined() { return strlen( get_option( 'permalink_structure' ) ); } public function detect_base_url() { $site_url = get_option( 'siteurl' ); $home = get_option( 'home' ); } public function getWPDirFullPath( $wp_dir ) { $full_path = ''; switch ( $wp_dir ) { case 'wp-content': $full_path = WP_CONTENT_DIR; break; case 'uploads': $upload_dir_info = wp_upload_dir(); $full_path = $upload_dir_info['basedir']; break; case 'wp-includes': $full_path = ABSPATH . WPINC; break; case 'plugins': $full_path = WP_PLUGIN_DIR; break; case 'theme-root': $full_path = get_theme_root(); break; case 'parent-theme': $full_path = get_template_directory(); break; case 'child-theme': $full_path = get_stylesheet_directory(); break; } return rtrim( $full_path, '/' ); } public function getWPDirNameOnly( $wp_dir ) { $wp_dir_name = ''; switch ( $wp_dir ) { case 'child-theme': case 'parent-theme': case 'wp-content': case 'wp-includes': case 'uploads': case 'theme-root': case 'plugins': $wp_dir_name = $this->getLastPathSegment( $this->getWPDirFullPath( $wp_dir ) ); break; } return rtrim( $wp_dir_name, '/' ); } public function getLastPathSegment( $path ) { $path_segments = explode( '/', $path ); return end( $path_segments ); } public function getWPContentSubDirectory() { $parsed_url = parse_url( $this->parent_theme_url ); $path_segments = explode( '/', $parsed_url['path'] ); if ( count( $path_segments ) === 5 ) { return $path_segments[1] . '/'; } else { return ''; } } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WsLog { public static function l( $text ) { $target_settings = array( 'general', 'wpenv', ); $wp_uploads_path = ''; $settings = ''; if ( defined( 'WP_CLI' ) ) { require_once dirname( __FILE__ ) . '/DBSettings.php'; $settings = WPSHO_DBSettings::get( $target_settings ); } else { require_once dirname( __FILE__ ) . '/PostSettings.php'; $settings = WPSHO_PostSettings::get( $target_settings ); } if ( ! isset( $settings['debug_mode'] ) ) { return; } $wp_uploads_path = $settings['wp_uploads_path']; $log_file_path = $wp_uploads_path . '/WP-STATIC-EXPORT-LOG.txt'; file_put_contents( $log_file_path, $text . PHP_EOL, FILE_APPEND | LOCK_EX ); chmod( $log_file_path, 0664 ); } }
|
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WP2Static_BitBucket extends WP2Static_SitePublisher { public function __construct() { $this->loadSettings( 'bitbucket' ); list($this->user, $this->repository) = explode( '/', $this->settings['bbRepo'] ); $this->api_base = 'https://api.bitbucket.org/2.0/repositories/'; $this->previous_hashes_path = $this->settings['wp_uploads_path'] . '/WP2STATIC-BITBUCKET-PREVIOUS-HASHES.txt'; if ( defined( 'WP_CLI' ) ) { return; } switch ( $_POST['ajax_action'] ) { case 'bitbucket_prepare_export': $this->bootstrap(); $this->loadArchive(); $this->prepareDeploy( true ); break; case 'bitbucket_upload_files': $this->bootstrap(); $this->loadArchive(); $this->upload_files(); break; case 'test_bitbucket': $this->test_upload(); break; } } public function upload_files() { $this->files_remaining = $this->getRemainingItemsCount(); if ( $this->files_remaining < 0 ) { echo 'ERROR'; die(); } $this->initiateProgressIndicator(); $batch_size = $this->settings['deployBatchSize']; if ( $batch_size > $this->files_remaining ) { $batch_size = $this->files_remaining; } $lines = $this->getItemsToDeploy( $batch_size ); $this->openPreviousHashesFile(); $this->files_data = array(); foreach ( $lines as $line ) { $this->addFileToBatchForCommitting( $line ); $this->updateProgress(); } $this->sendBatchToBitbucket(); $this->writeFilePathAndHashesToFile(); $this->pauseBetweenAPICalls(); if ( $this->uploadsCompleted() ) { $this->finalizeDeployment(); } } public function test_upload() { require_once dirname( __FILE__ ) . '/../WP2Static/Request.php'; $this->client = new WP2Static_Request(); try { $remote_path = $this->api_base . $this->settings['bbRepo'] . '/src'; $post_options = array( '.tmp_wp2static.txt' => 'Test WP2Static connectivity', '.tmp_wp2static.txt' => 'Test WP2Static connectivity #2', 'message' => 'WP2Static deployment test', ); $this->client->postWithArray( $remote_path, $post_options, $curl_options = array( CURLOPT_USERPWD => $this->user . ':' . $this->settings['bbToken'], ) ); $this->checkForValidResponses( $this->client->status_code, array( '200', '201', '301', '302', '304' ) ); } catch ( Exception $e ) { $this->handleException( $e ); } $this->finalizeDeployment(); } public function addFileToBatchForCommitting( $line ) { list($local_file, $this->target_path) = explode( ',', $line ); $local_file = $this->archive->path . $local_file; $this->files_data['message'] = 'WP2Static deployment'; if ( ! is_file( $local_file ) ) { return; } if ( isset( $this->settings['bbPath'] ) ) { $this->target_path = $this->settings['bbPath'] . '/' . $this->target_path; } $this->local_file_contents = file_get_contents( $local_file ); if ( isset( $this->file_paths_and_hashes[ $this->target_path ] ) ) { $prev = $this->file_paths_and_hashes[ $this->target_path ]; $current = crc32( $this->local_file_contents ); if ( $prev != $current ) { $this->files_data[ '/' . rtrim( $this->target_path ) ] = new CURLFile( $local_file ); $this->recordFilePathAndHashInMemory( $this->target_path, $this->local_file_contents ); } } else { $this->files_data[ '/' . rtrim( $this->target_path ) ] = new CURLFile( $local_file ); $this->recordFilePathAndHashInMemory( $this->target_path, $this->local_file_contents ); } } public function sendBatchToBitbucket() { require_once dirname( __FILE__ ) . '/../WP2Static/Request.php'; $this->client = new WP2Static_Request(); $remote_path = $this->api_base . $this->settings['bbRepo'] . '/src'; $post_options = $this->files_data; try { $this->client->postWithArray( $remote_path, $post_options, $curl_options = array( CURLOPT_USERPWD => $this->user . ':' . $this->settings['bbToken'], ) ); $this->checkForValidResponses( $this->client->status_code, array( '200', '201', '301', '302', '304' ) ); } catch ( Exception $e ) { $this->handleException( $e ); } } } $bitbucket = new WP2Static_BitBucket();
|
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WP2Static_FTP extends WP2Static_SitePublisher { public function __construct() { $this->loadSettings( 'ftp' ); $this->previous_hashes_path = $this->settings['wp_uploads_path'] . '/WP2STATIC-FTP-PREVIOUS-HASHES.txt'; if ( defined( 'WP_CLI' ) ) { return; } switch ( $_POST['ajax_action'] ) { case 'ftp_prepare_export': $this->bootstrap(); $this->loadArchive(); $this->prepareDeploy(); break; case 'ftp_transfer_files': $this->bootstrap(); $this->loadArchive(); $this->upload_files(); break; case 'test_ftp': $this->test_ftp(); break; } } public function upload_files() { $this->files_remaining = $this->getRemainingItemsCount(); if ( $this->files_remaining < 0 ) { echo 'ERROR'; die(); } $this->initiateProgressIndicator(); $batch_size = $this->settings['deployBatchSize']; if ( $batch_size > $this->files_remaining ) { $batch_size = $this->files_remaining; } $lines = $this->getItemsToDeploy( $batch_size ); $this->openPreviousHashesFile(); require_once __DIR__ . '/../FTP/FtpClient.php'; require_once __DIR__ . '/../FTP/FtpException.php'; require_once __DIR__ . '/../FTP/FtpWrapper.php'; $this->ftp = new \FtpClient\FtpClient(); $port = isset( $this->settings['ftpPort'] ) ? $this->settings['ftpPort'] : 21; $use_ftps = isset( $this->settings['ftpTLS'] ); $this->ftp->connect( $this->settings['ftpServer'], $use_ftps, $port ); $this->ftp->login( $this->settings['ftpUsername'], $this->settings['ftpPassword'] ); if ( isset( $this->settings['activeFTP'] ) ) { $this->ftp->pasv( false ); } else { $this->ftp->pasv( true ); } foreach ( $lines as $line ) { list($this->local_file, $this->target_path) = explode( ',', $line ); $this->local_file = $this->archive->path . $this->local_file; if ( ! is_file( $this->local_file ) ) { continue; } if ( isset( $this->settings['ftpRemotePath'] ) ) { $this->target_path = $this->settings['ftpRemotePath'] . '/' . $this->target_path; } $this->local_file_contents = file_get_contents( $this->local_file ); $this->hash_key = $this->target_path . basename( $this->local_file ); if ( isset( $this->file_paths_and_hashes[ $this->hash_key ] ) ) { $prev = $this->file_paths_and_hashes[ $this->hash_key ]; $current = crc32( $this->local_file_contents ); if ( $prev != $current ) { $this->putFileViaFTP(); } } else { $this->putFileViaFTP(); } $this->recordFilePathAndHashInMemory( $this->hash_key, $this->local_file_contents ); $this->updateProgress(); } unset( $this->ftp ); $this->writeFilePathAndHashesToFile(); $this->pauseBetweenAPICalls(); if ( $this->uploadsCompleted() ) { $this->finalizeDeployment(); } } public function test_ftp() { require_once __DIR__ . '/../FTP/FtpClient.php'; require_once __DIR__ . '/../FTP/FtpException.php'; require_once __DIR__ . '/../FTP/FtpWrapper.php'; $this->ftp = new \FtpClient\FtpClient(); $port = isset( $this->settings['ftpPort'] ) ? $this->settings['ftpPort'] : 21; $use_ftps = isset( $this->settings['ftpTLS'] ); $this->ftp->connect( $this->settings['ftpServer'], $use_ftps, $port ); try { $this->ftp->login( $this->settings['ftpUsername'], $this->settings['ftpPassword'] ); if ( ! defined( 'WP_CLI' ) ) { echo 'SUCCESS'; } unset( $this->ftp ); return; } catch ( Exception $e ) { unset( $this->ftp ); $this->handleException( $e ); } } public function putFileViaFTP() { if ( ! $this->ftp->isdir( $this->target_path ) ) { $mkdir_result = $this->ftp->mkdir( $this->target_path, true ); } $this->ftp->chdir( $this->target_path ); $this->ftp->putFromPath( $this->local_file ); $this->ftp->chdir( '/' ); } } $ftp = new WP2Static_FTP();
|
@ -0,0 +1,14 @@
|
||||
<?php
|
||||
class WP2Static_GitHub extends WP2Static_SitePublisher { public function __construct() { $this->loadSettings( 'github' ); list($this->user, $this->repository) = explode( '/', $this->settings['ghRepo'] ); $this->api_base = 'https://api.github.com/repos/'; $this->previous_hashes_path = $this->settings['wp_uploads_path'] . '/WP2STATIC-GITHUB-PREVIOUS-HASHES.txt'; if ( defined( 'WP_CLI' ) ) { return; } switch ( $_POST['ajax_action'] ) { case 'github_prepare_export': $this->bootstrap(); $this->loadArchive(); $this->prepareDeploy( true ); break; case 'github_upload_files': $this->bootstrap(); $this->loadArchive(); $this->upload_files(); break; case 'test_github': $this->test_upload(); break; } } public function upload_files() { $this->files_remaining = $this->getRemainingItemsCount(); if ( $this->files_remaining < 0 ) { echo 'ERROR'; die(); } $this->initiateProgressIndicator(); $batch_size = $this->settings['deployBatchSize']; if ( $batch_size > $this->files_remaining ) { $batch_size = $this->files_remaining; } $lines = $this->getItemsToDeploy( $batch_size ); $this->openPreviousHashesFile(); foreach ( $lines as $line ) { list($local_file, $this->target_path) = explode( ',', $line ); $local_file = $this->archive->path . $local_file; if ( ! is_file( $local_file ) ) { continue; } if ( isset( $this->settings['ghPath'] ) ) { $this->target_path = $this->settings['ghPath'] . '/' . $this->target_path; } $this->logAction( "Uploading {$local_file} to {$this->target_path} in GitHub" ); $this->local_file_contents = file_get_contents( $local_file ); if ( isset( $this->file_paths_and_hashes[ $this->target_path ] ) ) { $prev = $this->file_paths_and_hashes[ $this->target_path ]; $current = crc32( $this->local_file_contents ); if ( $prev != $current ) { if ( $this->fileExistsInGitHub() ) { $this->updateFileInGitHub(); } else { $this->createFileInGitHub(); } $this->recordFilePathAndHashInMemory( $this->target_path, $this->local_file_contents ); } else { $this->logAction( "Skipping {$this->target_path} as identical " . 'to deploy cache' ); } } else { if ( $this->fileExistsInGitHub() ) { $this->updateFileInGitHub(); } else { $this->createFileInGitHub(); } $this->recordFilePathAndHashInMemory( $this->target_path, $this->local_file_contents ); } $this->updateProgress(); } $this->writeFilePathAndHashesToFile(); $this->pauseBetweenAPICalls(); if ( $this->uploadsCompleted() ) { $this->finalizeDeployment(); } } public function test_upload() { try { $this->remote_path = $this->api_base . $this->settings['ghRepo'] . '/contents/' . '.WP2Static/' . uniqid(); $b64_file_contents = base64_encode( 'WP2Static test upload' ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $this->remote_path ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); curl_setopt( $ch, CURLOPT_HEADER, 0 ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); curl_setopt( $ch, CURLOPT_POST, 1 ); curl_setopt( $ch, CURLOPT_USERAGENT, 'WP2Static.com' ); curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' ); $post_options = array( 'message' => 'Test WP2Static connectivity', 'content' => $b64_file_contents, 'branch' => $this->settings['ghBranch'], ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post_options ) ); curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Authorization: ' . 'token ' . $this->settings['ghToken'], ) ); $output = curl_exec( $ch ); $status_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); curl_close( $ch ); $good_response_codes = array( '200', '201', '301', '302', '304' ); if ( ! in_array( $status_code, $good_response_codes ) ) { require_once dirname( __FILE__ ) . '/../WP2Static/WsLog.php'; WsLog::l( 'BAD RESPONSE STATUS (' . $status_code . '): ' ); throw new Exception( 'GitHub API bad response status' ); } } catch ( Exception $e ) { require_once dirname( __FILE__ ) . '/../WP2Static/WsLog.php'; WsLog::l( 'GITHUB EXPORT: error encountered' ); WsLog::l( $e ); throw new Exception( $e ); return; } if ( ! defined( 'WP_CLI' ) ) { echo 'SUCCESS'; } } public function fileExistsInGitHub() { $this->remote_path = $this->api_base . $this->settings['ghRepo'] . '/contents/' . $this->target_path; $this->query = <<<JSON
|
||||
query{
|
||||
repository(owner: "{$this->user}", name: "{$this->repository}") {
|
||||
object(expression: "{$this->settings['ghBranch']}:{$this->target_path}") {
|
||||
... on Blob {
|
||||
oid
|
||||
byteSize
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
JSON;
|
||||
require_once dirname( __FILE__ ) . '/../WP2Static/Request.php'; $this->client = new WP2Static_Request(); $post_options = array( 'query' => $this->query, 'variables' => '', ); $headers = array( 'Authorization: ' . 'token ' . $this->settings['ghToken'], ); $this->client->postWithJSONPayloadCustomHeaders( 'https://api.github.com/graphql', $post_options, $headers, $curl_options = array( CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2, ) ); $this->logAction( "API response code {$this->client->status_code}" ); $this->logAction( "API response body {$this->client->body}" ); $this->checkForValidResponses( $this->client->status_code, array( '200', '201', '301', '302', '304' ) ); $gh_file_info = json_decode( $this->client->body, true ); $this->existing_file_object = $gh_file_info['data']['repository']['object']; $action = ''; $commit_message = ''; if ( ! empty( $this->existing_file_object ) ) { $this->logAction( "{$this->target_path} path exists in GitHub" ); return true; } } public function updateFileInGitHub() { $this->logAction( "Updating {$this->target_path} in GitHub" ); $action = 'UPDATE'; $existing_sha = $this->existing_file_object['oid']; $existing_bytesize = $this->existing_file_object['byteSize']; $b64_file_contents = base64_encode( $this->local_file_contents ); if ( isset( $this->settings['ghCommitMessage'] ) ) { $commit_message = str_replace( array( '%ACTION%', '%FILENAME%', ), array( $action, $this->target_path, ), $this->settings['ghCommitMessage'] ); } else { $commit_message = 'WP2Static ' . $action . ' ' . $this->target_path; } try { $post_options = array( 'message' => $commit_message, 'content' => $b64_file_contents, 'branch' => $this->settings['ghBranch'], 'sha' => $existing_sha, ); $headers = array( 'Authorization: ' . 'token ' . $this->settings['ghToken'], ); $this->client->putWithJSONPayloadCustomHeaders( $this->remote_path, $post_options, $headers, $curl_options = array( CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2, ) ); $this->logAction( "API response code {$this->client->status_code}" ); $this->logAction( "API response body {$this->client->body}" ); $this->checkForValidResponses( $this->client->status_code, array( '200', '201', '301', '302', '304' ) ); } catch ( Exception $e ) { $this->handleException( $e ); } } public function createFileInGitHub() { $this->logAction( "Creating {$this->target_path} in GitHub" ); $action = 'CREATE'; $b64_file_contents = base64_encode( $this->local_file_contents ); if ( isset( $this->settings['ghCommitMessage'] ) ) { $commit_message = str_replace( array( '%ACTION%', '%FILENAME%', ), array( $action, $this->target_path, ), $this->settings['ghCommitMessage'] ); } else { $commit_message = 'WP2Static ' . $action . ' ' . $this->target_path; } try { $post_options = array( 'message' => $commit_message, 'content' => $b64_file_contents, 'branch' => $this->settings['ghBranch'], ); $headers = array( 'Authorization: ' . 'token ' . $this->settings['ghToken'], ); $this->client->putWithJSONPayloadCustomHeaders( $this->remote_path, $post_options, $headers, $curl_options = array( CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2, ) ); $this->logAction( "API response code {$this->client->status_code}" ); $this->logAction( "API response body {$this->client->body}" ); $this->checkForValidResponses( $this->client->status_code, array( '200', '201', '301', '302', '304' ) ); } catch ( Exception $e ) { $this->handleException( $e ); } } } $github = new WP2Static_GitHub();
|
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WP2Static_Netlify extends WP2Static_SitePublisher { public function __construct() { $this->loadSettings( 'netlify' ); $this->settings['netlifySiteID']; $this->settings['netlifyPersonalAccessToken']; $this->base_url = 'https://api.netlify.com'; $this->detectSiteID(); if ( defined( 'WP_CLI' ) ) { return; } switch ( $_POST['ajax_action'] ) { case 'test_netlify': $this->loadArchive(); $this->test_netlify(); break; case 'netlify_do_export': $this->bootstrap(); $this->loadArchive(); $this->deploy(); break; } } public function detectSiteID() { $this->site_id = $this->settings['netlifySiteID']; if ( strpos( $this->site_id, 'netlify.com' ) !== false ) { return; } elseif ( strpos( $this->site_id, '.' ) !== false ) { return; } elseif ( strlen( $this->site_id ) === 37 ) { return; } else { $this->site_id .= '.netlify.com'; } } public function deploy() { $this->zip_archive_path = $this->settings['wp_uploads_path'] . '/' . $this->archive->name . '.zip'; $zip_deploy_endpoint = $this->base_url . '/api/v1/sites/' . $this->site_id . '/deploys'; try { $headers = array( 'Authorization: Bearer ' . $this->settings['netlifyPersonalAccessToken'], 'Content-Type: application/zip', ); require_once dirname( __FILE__ ) . '/../WP2Static/Request.php'; $this->client = new WP2Static_Request(); $this->client->postWithFileStreamAndHeaders( $zip_deploy_endpoint, $this->zip_archive_path, $headers ); $this->checkForValidResponses( $this->client->status_code, array( '200', '201', '301', '302', '304' ) ); $this->finalizeDeployment(); } catch ( Exception $e ) { $this->handleException( $e ); } } public function test_netlify() { $this->zip_archive_path = $this->settings['wp_uploads_path'] . '/' . $this->archive->name . '.zip'; $site_info_endpoint = $this->base_url . '/api/v1/sites/' . $this->site_id; try { $headers = array( 'Authorization: Bearer ' . $this->settings['netlifyPersonalAccessToken'], ); require_once dirname( __FILE__ ) . '/../WP2Static/Request.php'; $this->client = new WP2Static_Request(); $this->client->getWithCustomHeaders( $site_info_endpoint, $headers ); if ( isset( $this->client->headers['x-ratelimit-limit'] ) ) { if ( ! defined( 'WP_CLI' ) ) { echo 'SUCCESS'; } } else { $code = 404; require_once dirname( __FILE__ ) . '/../WP2Static/WsLog.php'; WsLog::l( 'BAD RESPONSE STATUS FROM API (' . $code . ')' ); http_response_code( $code ); echo 'Netlify test error'; } } catch ( Exception $e ) { $this->handleException( $e ); } } } $netlify = new WP2Static_Netlify();
|
File diff suppressed because one or more lines are too long
@ -0,0 +1,2 @@
|
||||
<?php
|
||||
class WP2Static_CLI { public function diagnostics() { WP_CLI::line( PHP_EOL . 'WP2Static' . PHP_EOL ); $environmental_info = array( array( 'key' => 'PLUGIN VERSION', 'value' => WP2Static_Controller::VERSION, ), array( 'key' => 'PHP_VERSION', 'value' => phpversion(), ), array( 'key' => 'PHP MAX EXECUTION TIME', 'value' => ini_get( 'max_execution_time' ), ), array( 'key' => 'OS VERSION', 'value' => php_uname(), ), array( 'key' => 'WP VERSION', 'value' => get_bloginfo( 'version' ), ), array( 'key' => 'WP URL', 'value' => get_bloginfo( 'url' ), ), array( 'key' => 'WP SITEURL', 'value' => get_option( 'siteurl' ), ), array( 'key' => 'WP HOME', 'value' => get_option( 'home' ), ), array( 'key' => 'WP ADDRESS', 'value' => get_bloginfo( 'wpurl' ), ), ); WP_CLI\Utils\format_items( 'table', $environmental_info, array( 'key', 'value' ) ); $active_plugins = get_option( 'active_plugins' ); WP_CLI::line( PHP_EOL . 'Active plugins:' . PHP_EOL ); foreach ( $active_plugins as $active_plugin ) { WP_CLI::line( $active_plugin ); } WP_CLI::line( PHP_EOL ); WP_CLI::line( 'There are a total of ' . count( $active_plugins ) . ' active plugins on this site.' . PHP_EOL ); } public function microtime_diff( $start, $end = null ) { if ( ! $end ) { $end = microtime(); } list( $start_usec, $start_sec ) = explode( ' ', $start ); list( $end_usec, $end_sec ) = explode( ' ', $end ); $diff_sec = intval( $end_sec ) - intval( $start_sec ); $diff_usec = floatval( $end_usec ) - floatval( $start_usec ); return floatval( $diff_sec ) + $diff_usec; } public function generate() { $start_time = microtime(); $plugin = WP2Static_Controller::getInstance(); $plugin->generate_filelist_preview(); $plugin->prepare_for_export(); require_once dirname( __FILE__ ) . '/WP2Static/WP2Static.php'; require_once dirname( __FILE__ ) . '/WP2Static/SiteCrawler.php'; $site_crawler->crawl_site(); $site_crawler->crawl_discovered_links(); $plugin->post_process_archive_dir(); $end_time = microtime(); $duration = $this->microtime_diff( $start_time, $end_time ); WP_CLI::success( "Generated static site archive in $duration seconds" ); } public function deploy( $args, $assoc_args ) { $test = false; if ( ! empty( $assoc_args['test'] ) ) { $test = true; } if ( ! empty( $assoc_args['selected_deployment_option'] ) ) { switch ( $assoc_args['selected_deployment_option'] ) { case 'zip': break; } } require_once dirname( __FILE__ ) . '/WP2Static/Deployer.php'; $deployer = new Deployer(); $deployer->deploy( $test ); } } function wp2static_options( $args, $assoc_args ) { $action = isset( $args[0] ) ? $args[0] : null; $option_name = isset( $args[1] ) ? $args[1] : null; $value = isset( $args[2] ) ? $args[2] : null; $reveal_sensitive_values = false; if ( empty( $action ) ) { WP_CLI::error( 'Missing required argument: <get|set|list>' ); } $plugin = WP2Static_Controller::getInstance(); if ( $action === 'get' ) { if ( empty( $option_name ) ) { WP_CLI::error( 'Missing required argument: <option-name>' ); } if ( ! $plugin->options->optionExists( $option_name ) ) { WP_CLI::error( 'Invalid option name' ); } else { $option_value = $plugin->options->getOption( $option_name ); WP_CLI::line( $option_value ); } } if ( $action === 'set' ) { if ( empty( $option_name ) ) { WP_CLI::error( 'Missing required argument: <option-name>' ); } if ( empty( $value ) ) { WP_CLI::error( 'Missing required argument: <value>' ); } if ( ! $plugin->options->optionExists( $option_name ) ) { WP_CLI::error( 'Invalid option name' ); } else { $plugin->options->setOption( $option_name, $value ); $plugin->options->save(); $result = $plugin->options->getOption( $option_name ); if ( ! $result === $value ) { WP_CLI::error( 'Option not able to be updated' ); } } } if ( $action === 'list' ) { if ( isset( $assoc_args['reveal-sensitive-values'] ) ) { $reveal_sensitive_values = true; } $options = $plugin->options->getAllOptions( $reveal_sensitive_values ); WP_CLI\Utils\format_items( 'table', $options, array( 'Option name', 'Value' ) ); } } WP_CLI::add_command( 'wp2static', 'wp2static_cli' ); WP_CLI::add_command( 'wp2static options', 'wp2static_options' );
|
Reference in New Issue
Block a user