diff --git a/.phpstorm.meta.php/magento_models_methods.meta.php b/.phpstorm.meta.php/magento_models_methods.meta.php index ed3e9584bea..fa6d33a1112 100644 --- a/.phpstorm.meta.php/magento_models_methods.meta.php +++ b/.phpstorm.meta.php/magento_models_methods.meta.php @@ -1807,7 +1807,6 @@ 'install/installer_db_mysql4' => \Mage_Install_Model_Installer_Db_Mysql4::class, 'install/installer_env' => \Mage_Install_Model_Installer_Env::class, 'install/installer_filesystem' => \Mage_Install_Model_Installer_Filesystem::class, - 'install/installer_pear' => \Mage_Install_Model_Installer_Pear::class, 'install/observer' => \Mage_Install_Model_Observer::class, 'install/session' => \Mage_Install_Model_Session::class, 'install/wizard' => \Mage_Install_Model_Wizard::class, @@ -22421,4 +22420,4 @@ 'moneybookers/wlt' => \Phoenix_Moneybookers_Model_Wlt::class, ]) ); -} \ No newline at end of file +} diff --git a/app/code/core/Mage/Adminhtml/Model/Extension.php b/app/code/core/Mage/Adminhtml/Model/Extension.php deleted file mode 100644 index 282dfc7b327..00000000000 --- a/app/code/core/Mage/Adminhtml/Model/Extension.php +++ /dev/null @@ -1,395 +0,0 @@ -setLocalExtensionPackageFormData($this->getData()); - - Varien_Pear::$reloadOnRegistryUpdate = false; - $pkg = new Varien_Pear_Package; - #$pkg->getPear()->runHtmlConsole(array('command'=>'list-channels')); - $pfm = $pkg->getPfm(); - $pfm->setOptions(array( - 'packagedirectory'=>'.', - 'baseinstalldir'=>'.', - 'simpleoutput'=>true, - )); - - $this->_setPackage($pfm); - $this->_setRelease($pfm); - $this->_setMaintainers($pfm); - $this->_setDependencies($pfm); - $this->_setContents($pfm); -#echo "
".print_r($pfm,1)."
"; - if (!$pfm->validate(PEAR_VALIDATE_NORMAL)) { - //echo "
".print_r($this->getData(),1)."
"; - //echo "TEST:"; - //echo "
".print_r($pfm->getValidationWarnings(), 1)."
"; - $message = $pfm->getValidationWarnings(); - //$message = $message[0]['message']; - throw Mage::exception('Mage_Adminhtml', Mage::helper('adminhtml')->__($message[0]['message'])); - - return $this; - } - - $this->setPackageXml($pfm->getDefaultGenerator()->toXml(PEAR_VALIDATE_NORMAL)); - return $this; - } - - protected function _setPackage($pfm) - { - $pfm->setPackageType('php'); - $pfm->setChannel($this->getData('channel')); - - $pfm->setLicense($this->getData('license'), $this->getData('license_uri')); - - $pfm->setPackage($this->getData('name')); - $pfm->setSummary($this->getData('summary')); - $pfm->setDescription($this->getData('description')); - } - - protected function _setRelease($pfm) - { - $pfm->addRelease(); - $pfm->setDate(date('Y-m-d')); - - $pfm->setAPIVersion($this->getData('api_version')); - $pfm->setReleaseVersion($this->getData('release_version')); - $pfm->setAPIStability($this->getData('api_stability')); - $pfm->setReleaseStability($this->getData('release_stability')); - $pfm->setNotes($this->getData('notes')); - } - - protected function _setMaintainers($pfm) - { - $maintainers = $this->getData('maintainers'); - foreach ($maintainers['role'] as $i=>$role) { - if (0===$i) { - continue; - } - $handle = $maintainers['handle'][$i]; - $name = $maintainers['name'][$i]; - $email = $maintainers['email'][$i]; - $active = !empty($maintainers['active'][$i]) ? 'yes' : 'no'; - $pfm->addMaintainer($role, $handle, $name, $email, $active); - } - } - - protected function _setDependencies($pfm) - { - $pfm->clearDeps(); - $exclude = $this->getData('depends_php_exclude')!=='' ? explode(',', $this->getData('depends_php_exclude')) : false; - $pfm->setPhpDep($this->getData('depends_php_min'), $this->getData('depends_php_max'), $exclude); - $pfm->setPearinstallerDep('1.6.2'); - - foreach ($this->getData('depends') as $deptype=>$deps) { - foreach ($deps['type'] as $i=>$type) { - if (0===$i) { - continue; - } - $name = $deps['name'][$i]; - $min = !empty($deps['min'][$i]) ? $deps['min'][$i] : false; - $max = !empty($deps['max'][$i]) ? $deps['max'][$i] : false; - $recommended = !empty($deps['recommended'][$i]) ? $deps['recommended'][$i] : false; - $exclude = !empty($deps['exclude'][$i]) ? explode(',', $deps['exclude'][$i]) : false; - if ($deptype!=='extension') { - $channel = !empty($deps['channel'][$i]) ? $deps['channel'][$i] : 'connect.magentocommerce.com/core'; - } - switch ($deptype) { - case 'package': - if ($type==='conflicts') { - $pfm->addConflictingPackageDepWithChannel( - $name, $channel, false, $min, $max, $recommended, $exclude); - } else { - $pfm->addPackageDepWithChannel( - $type, $name, $channel, $min, $max, $recommended, $exclude); - } - break; - - case 'subpackage': - if ($type==='conflicts') { - Mage::throwException(Mage::helper('adminhtml')->__("Subpackage cannot be conflicting.")); - } - $pfm->addSubpackageDepWithChannel( - $type, $name, $channel, $min, $max, $recommended, $exclude); - break; - - case 'extension': - $pfm->addExtensionDep( - $type, $name, $min, $max, $recommended, $exclude); - break; - } - } - } - } - - protected function _setContents($pfm) - { - $baseDir = $this->getRoleDir('mage').DS; - - $pfm->clearContents(); - $contents = $this->getData('contents'); - $usesRoles = array(); - foreach ($contents['role'] as $i=>$role) { - if (0===$i) { - continue; - } - - $usesRoles[$role] = 1; - - $roleDir = $this->getRoleDir($role).DS; - $fullPath = $roleDir.$contents['path'][$i]; - - switch ($contents['type'][$i]) { - case 'file': - if (!is_file($fullPath)) { - Mage::throwException(Mage::helper('adminhtml')->__("Invalid file: %s", $fullPath)); - } - $pfm->addFile('/', $contents['path'][$i], array('role'=>$role, 'md5sum'=>md5_file($fullPath))); - break; - - case 'dir': - if (!is_dir($fullPath)) { - Mage::throwException(Mage::helper('adminhtml')->__("Invalid directory: %s", $fullPath)); - } - $path = $contents['path'][$i]; - $include = $contents['include'][$i]; - $ignore = $contents['ignore'][$i]; - $this->_addDir($pfm, $role, $roleDir, $path, $include, $ignore); - break; - } - } - - $pearRoles = $this->getRoles(); -#echo "
".print_r($usesRoles,1)."
"; - foreach ($usesRoles as $role=>$dummy) { - if (empty($pearRoles[$role]['package'])) { - continue; - } - $pfm->addUsesrole($role, $pearRoles[$role]['package']); - } - } - - protected function _addDir($pfm, $role, $roleDir, $path, $include, $ignore) - { - $roleDirLen = strlen($roleDir); - $entries = @glob($roleDir.$path.DS."*"); - if (!empty($entries)) { - foreach ($entries as $entry) { - $filePath = substr($entry, $roleDirLen); - if (!empty($include) && !preg_match($include, $filePath)) { - continue; - } - if (!empty($ignore) && preg_match($ignore, $filePath)) { - continue; - } - if (is_dir($entry)) { - $baseName = basename($entry); - if ('.'===$baseName || '..'===$baseName) { - continue; - } - $this->_addDir($pfm, $role, $roleDir, $filePath, $include, $ignore); - } elseif (is_file($entry)) { - $pfm->addFile('/', $filePath, array('role'=>$role, 'md5sum'=>md5_file($entry))); - } - } - } - } - - public function getRoles() - { - if (!$this->_roles) { - $frontend = $this->getPear()->getFrontend(); - $config = $this->getPear()->getConfig(); - $pearMage = new PEAR_Command_Mage($frontend, $config); - $this->_roles = $pearMage->getRoles(); - } - return $this->_roles; - } - - public function getRoleDir($role) - { - $roles = $this->getRoles(); - return Varien_Pear::getInstance()->getConfig()->get($roles[$role]['dir_config']); - } - - public function getMaintainerRoles() - { - return array( - 'lead'=>'Lead', - 'developer'=>'Developer', - 'contributor'=>'Contributor', - 'helper'=>'Helper' - ); - } - - public function savePackage() - { - if ($this->getData('file_name') != '') { - $fileName = $this->getData('file_name'); - $this->unsetData('file_name'); - } else { - $fileName = $this->getName(); - } - - if (!preg_match('/^[a-z0-9]+[a-z0-9\-\_\.]*([\/\\\\]{1}[a-z0-9]+[a-z0-9\-\_\.]*)*$/i', $fileName)) { - return false; - } - - if (!$this->getPackageXml()) { - $this->generatePackageXml(); - } - if (!$this->getPackageXml()) { - return false; - } - - $pear = Varien_Pear::getInstance(); - $dir = Mage::getBaseDir('var').DS.'pear'; - if (!@file_put_contents($dir.DS.'package.xml', $this->getPackageXml())) { - return false; - } - - $pkgver = $this->getName().'-'.$this->getReleaseVersion(); - $this->unsPackageXml(); - $this->unsRoles(); - $xml = Mage::helper('core')->assocToXml($this->getData()); - $xml = new Varien_Simplexml_Element($xml->asXML()); - - // prepare dir to save - $parts = explode(DS, $fileName); - array_pop($parts); - $newDir = implode(DS, $parts); - if ((!empty($newDir)) && (!is_dir($dir . DS . $newDir))) { - if (!@mkdir($dir . DS . $newDir, 0777, true)) { - return false; - } - } - - if (!@file_put_contents($dir . DS . $fileName . '.xml', $xml->asNiceXml())) { - return false; - } - - return true; - } - - public function createPackage() - { - $pear = Varien_Pear::getInstance(); - $dir = Mage::getBaseDir('var').DS.'pear'; - if (!Mage::getConfig()->createDirIfNotExists($dir)) { - return false; - } - $curDir = getcwd(); - chdir($dir); - $result = $pear->run('mage-package', array(), array('package.xml')); - chdir($curDir); - if ($result instanceof PEAR_Error) { - return $result; - } - return true; - } - - - public function getStabilityOptions() - { - return array( - 'devel'=>'Development', - 'alpha'=>'Alpha', - 'beta'=>'Beta', - 'stable'=>'Stable', - ); - } - - public function getKnownChannels() - { - /* - $pear = Varien_Pear::getInstance(); - $pear->run('list-channels'); - $output = $pear->getOutput(); - $pear->getFrontend()->clear(); - - $data = $output[0]['output']['data']; - $arr = array(); - foreach ($data as $channel) { - $arr[$channel[0]] = $channel[1].' ('.$channel[0].')'; - } - */ - $arr = array( - 'connect.magentocommerce.com/core' => 'Magento Core Team', - 'connect.magentocommerce.com/community' => 'Magento Community', - #'pear.php.net' => 'PEAR', - #'pear.phpunit.de' => 'PHPUnit', - ); - return $arr; - } - - public function loadLocal($package, $options=array()) - { - $pear = $this->getPear(); - - $pear->getFrontend()->clear(); - - $result = $pear->run('info', $options, array($package)); - if ($result instanceof PEAR_Error) { - Mage::throwException($result->message); - } - - $output = $pear->getOutput(); - $pkg = new PEAR_PackageFile_v2; - $pkg->fromArray($output[0]['output']['raw']); - - return $pkg; - } - - public function loadRemote($package, $options=array()) - { - $pear = $this->getPear(); - - $pear->getFrontend()->clear(); - - $result = $pear->run('remote-info', $options, array($package)); - if ($result instanceof PEAR_Error) { - Mage::throwException($result->message); - } - - $output = $pear->getOutput(); - $this->setData($output[0]['output']); - - return $this; - } -} diff --git a/app/code/core/Mage/Adminhtml/etc/adminhtml.xml b/app/code/core/Mage/Adminhtml/etc/adminhtml.xml index c9255ab70b3..2b9ba41ccab 100644 --- a/app/code/core/Mage/Adminhtml/etc/adminhtml.xml +++ b/app/code/core/Mage/Adminhtml/etc/adminhtml.xml @@ -245,19 +245,6 @@ Cache Management - - Magento Connect - - - Magento Connect Manager - 0 - - - Package Extensions - 5 - - - diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit.php deleted file mode 100644 index 56a98f8796b..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit.php +++ /dev/null @@ -1,83 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit extends Mage_Adminhtml_Block_Widget_Form_Container -{ - /** - * Constructor - * - * Initializes edit form container, adds necessary buttons - */ - public function __construct() - { - $this->_objectId = 'id'; - $this->_blockGroup = 'connect'; - $this->_controller = 'adminhtml_extension_custom'; - - parent::__construct(); - - $this->_removeButton('back'); - $this->_updateButton('reset', 'onclick', "resetPackage()"); - - $this->_addButton('create', array( - 'label' => Mage::helper('connect')->__('Save Data and Create Package'), - 'class' => 'save', - 'onclick' => "createPackage()", - )); - $this->_addButton('save_as', array( - 'label' => Mage::helper('connect')->__('Save As...'), - 'title' => Mage::helper('connect')->__('Save package with custom package file name'), - 'onclick' => 'saveAsPackage()' - )); - } - - /** - * Get header of page - * - * @return string - */ - public function getHeaderText() - { - return Mage::helper('connect')->__('New Extension'); - } - - /* - * Get form submit URL - * - * @return string - */ - public function getFormActionUrl() - { - return $this->getUrl('*/*/save'); - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Form.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Form.php deleted file mode 100644 index f617e94a14b..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Form.php +++ /dev/null @@ -1,55 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Form extends Mage_Adminhtml_Block_Widget_Form -{ - /** - * Prepare Extension Package Form - * - * @return $this - */ - protected function _prepareForm() - { - $form = new Varien_Data_Form(array( - 'id' => 'edit_form', - 'action' => $this->getData('action'), - 'method' => 'post' - )); - - $form->setUseContainer(true); - $this->setForm($form); - - return parent::_prepareForm(); - } - -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Abstract.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Abstract.php deleted file mode 100644 index c1f860281d8..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Abstract.php +++ /dev/null @@ -1,173 +0,0 @@ - - */ -abstract class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Abstract - extends Mage_Adminhtml_Block_Widget_Form - implements Mage_Adminhtml_Block_Widget_Tab_Interface -{ - /** - * TODO - */ - protected $_addRowButtonHtml; - - /** - * TODO - */ - protected $_removeRowButtonHtml; - - /** - * TODO - */ - protected $_addFileDepButtonHtml; - - /** - * TODO - */ - public function __construct() - { - parent::__construct(); - $this->setData(Mage::getSingleton('connect/session')->getCustomExtensionPackageFormData()); - } - - /** - * TODO remove ??? - */ - public function initForm() - { - return $this; - } - - /** - * TODO - */ - public function getValue($key, $default='') - { - $value = $this->getData($key); - return htmlspecialchars($value ? $value : $default); - } - - /** - * TODO - */ - public function getSelected($key, $value) - { - return $this->getData($key)==$value ? 'selected="selected"' : ''; - } - - /** - * TODO - */ - public function getChecked($key) - { - return $this->getData($key) ? 'checked="checked"' : ''; - } - - /** - * TODO - */ - public function getAddRowButtonHtml($container, $template, $title='Add') - { - if (!isset($this->_addRowButtonHtml[$container])) { - $this->_addRowButtonHtml[$container] = $this->getLayout() - ->createBlock('adminhtml/widget_button') - ->setType('button') - ->setClass('add') - ->setLabel($this->__($title)) - ->setOnClick("addRow('".$container."', '".$template."')") - ->toHtml(); - } - return $this->_addRowButtonHtml[$container]; - } - - /** - * TODO - */ - public function getRemoveRowButtonHtml($selector='span') - { - if (!$this->_removeRowButtonHtml) { - $this->_removeRowButtonHtml = $this->getLayout() - ->createBlock('adminhtml/widget_button') - ->setType('button') - ->setClass('delete') - ->setLabel($this->__('Remove')) - ->setOnClick("removeRow(this, '".$selector."')") - ->toHtml(); - } - return $this->_removeRowButtonHtml; - } - - public function getAddFileDepsRowButtonHtml($selector='span', $filesClass='files') - { - if (!$this->_addFileDepButtonHtml) { - $this->_addFileDepButtonHtml = $this->getLayout() - ->createBlock('adminhtml/widget_button') - ->setType('button') - ->setClass('add') - ->setLabel($this->__('Add files')) - ->setOnClick("showHideFiles(this, '".$selector."', '".$filesClass."')") - ->toHtml(); - } - return $this->_addFileDepButtonHtml; - - } - - /** - * Get Tab Label - * - * @return string - */ - public function getTabLabel() - { - return ''; - } - - /** - * Get Tab Title - * - * @return string - */ - public function getTabTitle() - { - return ''; - } - - public function canShowTab() - { - return true; - } - - public function isHidden() - { - return false; - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Authors.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Authors.php deleted file mode 100644 index 082fe5b9f83..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Authors.php +++ /dev/null @@ -1,95 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Authors - extends Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Abstract -{ - /** - * Get Tab Label - * - * @return string - */ - public function getTabLabel() - { - return Mage::helper('connect')->__('Authors'); - } - - /** - * Get Tab Title - * - * @return string - */ - public function getTabTitle() - { - return Mage::helper('connect')->__('Authors'); - } - - /** - * Return add author button html - * - * @return string - */ - public function getAddAuthorButtonHtml() - { - return $this->getLayout()->createBlock('adminhtml/widget_button') - ->setType('button') - ->setClass('add') - ->setLabel($this->__('Add Author')) - ->setOnClick('addAuthor()') - ->toHtml(); - } - - /** - * Return array of authors - * - * @return array - */ - public function getAuthors() - { - $authors = array(); - if ($this->getData('authors')) { - $temp = array(); - foreach ($this->getData('authors') as $param => $values) { - if (is_array($values)) { - foreach ($values as $key => $value) { - $temp[$key][$param] =$value; - } - } - } - foreach ($temp as $key => $value) { - $authors[$key] = Mage::helper('core')->jsonEncode($value); - } - } - return $authors; - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Contents.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Contents.php deleted file mode 100644 index f1038f8d009..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Contents.php +++ /dev/null @@ -1,70 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Contents - extends Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Abstract -{ - /** - * Retrieve list of targets - * - * @return array - */ - public function getMageTargets() - { - $targets = Mage::getModel('connect/extension')->getLabelTargets(); - if (!is_array($targets)) { - $targets = array(); - } - return $targets; - } - - /** - * Get Tab Label - * - * @return string - */ - public function getTabLabel() - { - return Mage::helper('connect')->__('Contents'); - } - - /** - * Get Tab Title - * - * @return string - */ - public function getTabTitle() - { - return Mage::helper('connect')->__('Contents'); - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Depends.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Depends.php deleted file mode 100644 index 9f2589c59cf..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Depends.php +++ /dev/null @@ -1,108 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Depends - extends Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Abstract -{ - - /** - * Prepare Dependencies Form before rendering HTML - * - * @return Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Package - */ - protected function _prepareForm() - { - parent::_prepareForm(); - - $form = new Varien_Data_Form(); - $form->setHtmlIdPrefix('_depends'); - - $fieldset = $form->addFieldset('depends_php_fieldset', array( - 'legend' => Mage::helper('connect')->__('PHP Version') - )); - - $fieldset->addField('depends_php_min', 'text', array( - 'name' => 'depends_php_min', - 'label' => Mage::helper('connect')->__('Minimum'), - 'required' => true, - 'value' => '5.2.0', - )); - - $fieldset->addField('depends_php_max', 'text', array( - 'name' => 'depends_php_max', - 'label' => Mage::helper('connect')->__('Maximum'), - 'required' => true, - 'value' => '5.2.20', - )); - - $form->setValues($this->getData()); - $this->setForm($form); - - return $this; - } - - /** - * Retrieve list of loaded PHP extensions - * - * @return array - */ - public function getExtensions() - { - $extensions = array(); - foreach (get_loaded_extensions() as $ext) { - $extensions[$ext] = $ext; - } - asort($extensions, SORT_STRING); - return $extensions; - } - - /** - * Get Tab Label - * - * @return string - */ - public function getTabLabel() - { - return Mage::helper('connect')->__('Dependencies'); - } - - /** - * Get Tab Title - * - * @return string - */ - public function getTabTitle() - { - return Mage::helper('connect')->__('Dependencies'); - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Grid.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Grid.php deleted file mode 100644 index f4c68d9c479..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Grid.php +++ /dev/null @@ -1,117 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Grid extends Mage_Adminhtml_Block_Widget_Grid -{ - /** - * Initialize Grid block - * - */ - public function __construct() - { - parent::__construct(); - $this->_defaultLimit = 200; - $this->setId('extension_custom_edit_grid'); - $this->setUseAjax(true); - } - - /** - * Creates extension collection if it has not been created yet - * - * @return Mage_Connect_Model_Extension_Collection - */ - public function getCollection() - { - if (!$this->_collection) { - $this->_collection = Mage::getModel('connect/extension_collection'); - } - return $this->_collection; - } - - /** - * Prepare Local Package Collection for Grid - * - * @return $this - */ - protected function _prepareCollection() - { - $this->setCollection($this->getCollection()); - return parent::_prepareCollection(); - } - - /** - * Prepare grid columns - * - * @return Mage_Adminhtml_Block_Extension_Custom_Edit_Tab_Grid - */ - protected function _prepareColumns() - { - $this->addColumn('folder', array( - 'header' => Mage::helper('connect')->__('Folder'), - 'index' => 'folder', - 'width' => 100, - 'type' => 'options', - 'options' => $this->getCollection()->collectFolders() - )); - - $this->addColumn('package', array( - 'header' => Mage::helper('connect')->__('Package'), - 'index' => 'package', - )); - - return parent::_prepareColumns(); - } - - /** - * Self URL getter - * - * @return string - */ - public function getCurrentUrl($params = array()) - { - if (!isset($params['_current'])) { - $params['_current'] = true; - } - return $this->getUrl('*/*/grid', $params); - } - - /** - * Row URL getter - * - * @return string - */ - public function getRowUrl($row) - { - return $this->getUrl('*/*/load', array('id' => strtr(base64_encode($row->getFilenameId()), '+/=', '-_,'))); - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Load.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Load.php deleted file mode 100644 index 76324ecaf3f..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Load.php +++ /dev/null @@ -1,46 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Load - extends Mage_Adminhtml_Block_Template -{ - /** - * Retrieve Grid Block HTML - * - * @return string - */ - public function getPackageGridHtml() - { - return $this->getChildHtml('local_package_grid'); - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Local.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Local.php deleted file mode 100644 index c8c67b8744e..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Local.php +++ /dev/null @@ -1,107 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Local - extends Mage_Adminhtml_Block_Abstract - implements Mage_Adminhtml_Block_Widget_Tab_Interface -{ - /** - * Retrieve Tab load URL - * - * @return string - */ - public function getTabUrl() - { - return $this->getUrl('*/*/loadtab', array('_current' => true)); - } - - /** - * Retrieve class for load by ajax - * - * @return string - */ - public function getTabClass() - { - return 'ajax'; - } - - /** - * Retrieve class for load by ajax - * - * @return string - */ - public function getClass() - { - return 'ajax'; - } - - /** - * Get Tab Label - * - * @return string - */ - public function getTabLabel() - { - return Mage::helper('connect')->__('Load Local Package'); - } - - /** - * Get Tab Title - * - * @return string - */ - public function getTabTitle() - { - return Mage::helper('connect')->__('Load Local Package'); - } - - /** - * Is can show tab - * - * @return bool - */ - public function canShowTab() - { - return true; - } - - /** - * Is hidden tab - * - * @return bool - */ - public function isHidden() - { - return false; - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Package.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Package.php deleted file mode 100644 index 80bb10a515a..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Package.php +++ /dev/null @@ -1,148 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Package - extends Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Abstract -{ - /** - * Prepare Package Info Form before rendering HTML - * - * @return $this - */ - protected function _prepareForm() - { - parent::_prepareForm(); - - $form = new Varien_Data_Form(); - $form->setHtmlIdPrefix('_package'); - - $fieldset = $form->addFieldset('package_fieldset', array( - 'legend' => Mage::helper('connect')->__('Package') - )); - - if ($this->getData('name') != $this->getData('file_name')) { - $this->setData('file_name_disabled', $this->getData('file_name')); - $fieldset->addField('file_name_disabled', 'text', array( - 'name' => 'file_name_disabled', - 'label' => Mage::helper('connect')->__('Package File Name'), - 'disabled' => 'disabled', - )); - } - - $fieldset->addField('file_name', 'hidden', array( - 'name' => 'file_name', - )); - - $fieldset->addField('name', 'text', array( - 'name' => 'name', - 'label' => Mage::helper('connect')->__('Name'), - 'required' => true, - )); - - $fieldset->addField('channel', 'text', array( - 'name' => 'channel', - 'label' => Mage::helper('connect')->__('Channel'), - 'required' => true, - )); - - $versionsInfo = array( - array( - 'label' => Mage::helper('connect')->__('1.5.0.0 & later'), - 'value' => Mage_Connect_Package::PACKAGE_VERSION_2X - ), - array( - 'label' => Mage::helper('connect')->__('Pre-1.5.0.0'), - 'value' => Mage_Connect_Package::PACKAGE_VERSION_1X - ) - ); - $fieldset->addField('version_ids','multiselect',array( - 'name' => 'version_ids', - 'required' => true, - 'label' => Mage::helper('connect')->__('Supported releases'), - 'style' => 'height: 45px;', - 'values' => $versionsInfo - )); - - $fieldset->addField('summary', 'textarea', array( - 'name' => 'summary', - 'label' => Mage::helper('connect')->__('Summary'), - 'style' => 'height:50px;', - 'required' => true, - )); - - $fieldset->addField('description', 'textarea', array( - 'name' => 'description', - 'label' => Mage::helper('connect')->__('Description'), - 'style' => 'height:200px;', - 'required' => true, - )); - - $fieldset->addField('license', 'text', array( - 'name' => 'license', - 'label' => Mage::helper('connect')->__('License'), - 'required' => true, - 'value' => 'Open Software License (OSL 3.0)', - )); - - $fieldset->addField('license_uri', 'text', array( - 'name' => 'license_uri', - 'label' => Mage::helper('connect')->__('License URI'), - 'value' => 'http://opensource.org/licenses/osl-3.0.php', - )); - - $form->setValues($this->getData()); - $this->setForm($form); - - return $this; - } - - /** - * Get Tab Label - * - * @return string - */ - public function getTabLabel() - { - return Mage::helper('connect')->__('Package Info'); - } - - /** - * Get Tab Title - * - * @return string - */ - public function getTabTitle() - { - return Mage::helper('connect')->__('Package Info'); - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Release.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Release.php deleted file mode 100644 index a5a0d663df3..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tab/Release.php +++ /dev/null @@ -1,98 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Release - extends Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Abstract -{ - /** - * Prepare Release Info Form before rendering HTML - * - * @return $this - */ - protected function _prepareForm() - { - parent::_prepareForm(); - - $form = new Varien_Data_Form(); - $form->setHtmlIdPrefix('_release'); - - $fieldset = $form->addFieldset('release_fieldset', array( - 'legend' => Mage::helper('adminhtml')->__('Release') - )); - - $stabilityOptions = Mage::getModel('connect/extension')->getStabilityOptions(); - $fieldset->addField('version', 'text', array( - 'name' => 'version', - 'label' => Mage::helper('adminhtml')->__('Release Version'), - 'required' => true, - )); - - $fieldset->addField('stability', 'select', array( - 'name' => 'stability', - 'label' => Mage::helper('adminhtml')->__('Release Stability'), - 'options' => $stabilityOptions, - )); - - $fieldset->addField('notes', 'textarea', array( - 'name' => 'notes', - 'label' => Mage::helper('adminhtml')->__('Notes'), - 'style' => 'height:300px;', - 'required' => true, - )); - - $form->setValues($this->getData()); - $this->setForm($form); - - return $this; - } - - /** - * Get Tab Label - * - * @return string - */ - public function getTabLabel() - { - return Mage::helper('connect')->__('Release Info'); - } - - /** - * Get Tab Title - * - * @return string - */ - public function getTabTitle() - { - return Mage::helper('connect')->__('Release Info'); - } -} diff --git a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tabs.php b/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tabs.php deleted file mode 100644 index a331de91826..00000000000 --- a/app/code/core/Mage/Connect/Block/Adminhtml/Extension/Custom/Edit/Tabs.php +++ /dev/null @@ -1,103 +0,0 @@ - - */ -class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs -{ - /** - * Constructor - */ - public function __construct() - { - parent::__construct(); - $this->setId('connect_extension_edit_tabs'); - $this->setDestElementId('edit_form'); - $this->setTitle(Mage::helper('connect')->__('Create Extension Package')); - } - - /** - * Set tabs - * - * @return $this - */ - protected function _beforeToHtml() - { -// $this->addTab('package', array( -// 'label' => Mage::helper('connect')->__('Package Info'), -// 'content' => $this->_getTabHtml('package'), -// 'active' => true, -// )); -// -// $this->addTab('release', array( -// 'label' => Mage::helper('connect')->__('Release Info'), -// 'content' => $this->_getTabHtml('release'), -// )); -// -// $this->addTab('maintainers', array( -// 'label' => Mage::helper('connect')->__('Authors'), -// 'content' => $this->_getTabHtml('authors'), -// )); -// -// $this->addTab('depends', array( -// 'label' => Mage::helper('connect')->__('Dependencies'), -// 'content' => $this->_getTabHtml('depends'), -// )); -// -// $this->addTab('contents', array( -// 'label' => Mage::helper('connect')->__('Contents'), -// 'content' => $this->_getTabHtml('contents'), -// )); -// -// $this->addTab('load', array( -// 'label' => Mage::helper('connect')->__('Load local Package'), -// 'class' => 'ajax', -// 'url' => $this->getUrl('*/*/loadtab', array('_current' => true)), -// )); - - return parent::_beforeToHtml(); - } - - /** - * Retrieve HTML for tab - * - * @param string $tab - * @return string - */ - protected function _getTabHtml($tab) - { -// return $this->getLayout() -// ->createBlock('connect/adminhtml_extension_custom_edit_tab_'.$tab) -// ->initForm() -// ->toHtml(); - } - -} diff --git a/app/code/core/Mage/Connect/Helper/Data.php b/app/code/core/Mage/Connect/Helper/Data.php deleted file mode 100644 index 83215240ea7..00000000000 --- a/app/code/core/Mage/Connect/Helper/Data.php +++ /dev/null @@ -1,169 +0,0 @@ - - */ -class Mage_Connect_Helper_Data extends Mage_Core_Helper_Data -{ - /** - * Path to directory that contains XML packages definition - * - * @var string - */ - protected $_localPackagesPath; - - public function __construct() - { - $this->_localPackagesPath = Mage::getBaseDir('var') . DS . 'connect' . DS; - } - - /** - * Retrieve file system path for local extension packages - * Return path with last directory separator - * - * @return string - */ - public function getLocalPackagesPath() - { - return $this->_localPackagesPath; - } - - /** - * Set file system path for local extension packages - * - */ - public function setLocalPackagesPath($path) - { - $this->_localPackagesPath = $path; - return $this; - } - - /** - * Retrieve file system path for local extension packages (for version 1 packages only) - * Return path with last directory separator - * - * @return string - */ - public function getLocalPackagesPathV1x() - { - return Mage::getBaseDir('var') . DS . 'pear' . DS; - } - - /** - * Retrieve a map to convert a channel from previous version of Magento Connect Manager - * - * @return array - */ - public function getChannelMapFromV1x() - { - return array( - 'connect.magentocommerce.com/community' => 'community', - 'connect.magentocommerce.com/core' => 'community' - ); - } - - /** - * Retrieve a map to convert a channel to previous version of Magento Connect Manager - * - * @return array - */ - public function getChannelMapToV1x() - { - return array( - 'community' => 'connect.magentocommerce.com/community' - ); - } - - /** - * Convert package channel in order for it to be compatible with current version of Magento Connect Manager - * - * @param string $channel - * - * @return string - */ - public function convertChannelFromV1x($channel) - { - $channelMap = $this->getChannelMapFromV1x(); - if (isset($channelMap[$channel])) { - $channel = $channelMap[$channel]; - } - return $channel; - } - - /** - * Convert package channel in order for it to be compatible with previous version of Magento Connect Manager - * - * @param string $channel - * - * @return string - */ - public function convertChannelToV1x($channel) - { - $channelMap = $this->getChannelMapToV1x(); - if (isset($channelMap[$channel])) { - $channel = $channelMap[$channel]; - } - return $channel; - } - - /** - * Load local package data array - * - * @param string $packageName without extension - * @return array|false - */ - public function loadLocalPackage($packageName) - { - //check LFI protection - $this->checkLfiProtection($packageName); - - $path = $this->getLocalPackagesPath(); - $xmlFile = $path . $packageName . '.xml'; - $serFile = $path . $packageName . '.ser'; - - if (file_exists($xmlFile) && is_readable($xmlFile)) { - $xml = simplexml_load_file($xmlFile); - $data = Mage::helper('core')->xmlToAssoc($xml); - if (!empty($data)) { - return $data; - } - } - - if (file_exists($serFile) && is_readable($xmlFile)) { - $data = unserialize(file_get_contents($serFile)); - if (!empty($data)) { - return $data; - } - } - - return false; - } -} diff --git a/app/code/core/Mage/Connect/Model/Extension.php b/app/code/core/Mage/Connect/Model/Extension.php deleted file mode 100644 index 4171435f146..00000000000 --- a/app/code/core/Mage/Connect/Model/Extension.php +++ /dev/null @@ -1,342 +0,0 @@ - - */ -class Mage_Connect_Model_Extension extends Varien_Object -{ - /** - * Cache for targets - * - * @var array - */ - protected $_targets; - - /** - * Internal cache for package - * - * @var Mage_Connect_Package - */ - protected $_package; - - /** - * Return package object - * - * @return Mage_Connect_Package - */ - protected function getPackage() - { - if (!$this->_package instanceof Mage_Connect_Package) { - $this->_package = new Mage_Connect_Package(); - } - return $this->_package; - } - - /** - * Set package object. - * - * @return $this - */ - public function generatePackageXml() - { - Mage::getSingleton('connect/session') - ->setLocalExtensionPackageFormData($this->getData()); - - $this->_setPackage() - ->_setRelease() - ->_setAuthors() - ->_setDependencies() - ->_setContents(); - if (!$this->getPackage()->validate()) { - $message = $this->getPackage()->getErrors(); - throw Mage::exception('Mage_Core', Mage::helper('connect')->__($message[0])); - } - $this->setPackageXml($this->getPackage()->getPackageXml()); - return $this; - } - - /** - * Set general information. - * - * @return $this - */ - protected function _setPackage() - { - $this->getPackage() - ->setName($this->getData('name')) - ->setChannel($this->getData('channel')) - ->setLicense($this->getData('license'), $this->getData('license_uri')) - ->setSummary($this->getData('summary')) - ->setDescription($this->getData('description')); - return $this; - } - - /** - * Set release information - * - * @return $this - */ - protected function _setRelease() - { - $this->getPackage() - ->setDate(date('Y-m-d')) - ->setTime(date('H:i:s')) - ->setVersion($this->getData('version')?$this->getData('version'):$this->getData('release_version')) - ->setStability($this->getData('stability')) - ->setNotes($this->getData('notes')); - return $this; - } - - /** - * Set authors - * - * @return $this - */ - protected function _setAuthors() - { - $authors = $this->getData('authors'); - foreach ($authors['name'] as $i => $name) { - $user = $authors['user'][$i]; - $email = $authors['email'][$i]; - $this->getPackage()->addAuthor($name, $user, $email); - } - return $this; - } - - - protected function packageFilesToArray($filesString) - { - $packageFiles = array(); - if($filesString) { - $filesArray = preg_split("/[\n\r]+/", $filesString); - foreach($filesArray as $file) { - $file = trim($file, "/"); - $res = explode(DIRECTORY_SEPARATOR, $file, 2); - array_map('trim', $res); - if(2 == count($res)) { - $packageFiles[] = array('target'=>$res[0], 'path'=>$res[1]); - } - } - } - return $packageFiles; - } - - /** - * Set php, php extensions, another packages dependencies - * - * @return $this - */ - protected function _setDependencies() - { - $this->getPackage() - ->clearDependencies() - ->setDependencyPhpVersion($this->getData('depends_php_min'), $this->getData('depends_php_max')); - - foreach ($this->getData('depends') as $deptype=>$deps) { - foreach ($deps['name'] as $i=>$type) { - if (0===$i) { - continue; - } - $name = $deps['name'][$i]; - $min = !empty($deps['min'][$i]) ? $deps['min'][$i] : false; - $max = !empty($deps['max'][$i]) ? $deps['max'][$i] : false; - - $files = !empty($deps['files'][$i]) ? $deps['files'][$i] : false; - $packageFiles = $this->packageFilesToArray($files); - - if ($deptype !== 'extension') { - $channel = !empty($deps['channel'][$i]) - ? $deps['channel'][$i] - : 'connect.magentocommerce.com/core'; - } - switch ($deptype) { - case 'package': - $this->getPackage()->addDependencyPackage($name, $channel, $min, $max, $packageFiles); - break; - - case 'extension': - $this->getPackage()->addDependencyExtension($name, $min, $max); - break; - } - } - } - return $this; - } - - /** - * Set contents. Add file or entire directory. - * - * @return $this - */ - protected function _setContents() - { - $this->getPackage()->clearContents(); - $contents = $this->getData('contents'); - foreach ($contents['target'] as $i=>$target) { - if (0===$i) { - continue; - } - switch ($contents['type'][$i]) { - case 'file': - $this->getPackage()->addContent($contents['path'][$i], $contents['target'][$i]); - break; - - case 'dir': - $target = $contents['target'][$i]; - $path = $contents['path'][$i]; - $include = $contents['include'][$i]; - $ignore = $contents['ignore'][$i]; - $this->getPackage()->addContentDir($target, $path, $ignore, $include); - break; - } - } - return $this; - } - - /** - * Save package file to var/connect. - * - * @return boolean - */ - public function savePackage() - { - if ($this->getData('file_name') != '') { - $fileName = $this->getData('file_name'); - $this->unsetData('file_name'); - } else { - $fileName = $this->getName(); - } - - if (!preg_match('/^[a-z0-9]+[a-z0-9\-\_\.]*([\/\\\\]{1}[a-z0-9]+[a-z0-9\-\_\.]*)*$/i', $fileName)) { - return false; - } - - if (!$this->getPackageXml()) { - $this->generatePackageXml(); - } - if (!$this->getPackageXml()) { - return false; - } - - $path = Mage::helper('connect')->getLocalPackagesPath(); - if (!@file_put_contents($path . 'package.xml', $this->getPackageXml())) { - return false; - } - - $this->unsPackageXml(); - $this->unsTargets(); - $xml = Mage::helper('core')->assocToXml($this->getData()); - $xml = new Varien_Simplexml_Element($xml->asXML()); - - // prepare dir to save - $parts = explode(DS, $fileName); - array_pop($parts); - $newDir = implode(DS, $parts); - if ((!empty($newDir)) && (!is_dir($path . $newDir))) { - if (!@mkdir($path . $newDir, 0777, true)) { - return false; - } - } - - if (!@file_put_contents($path . $fileName . '.xml', $xml->asNiceXml())) { - return false; - } - - return true; - } - - /** - * Create package file - * - * @return boolean - */ - public function createPackage() - { - $path = Mage::helper('connect')->getLocalPackagesPath(); - if (!Mage::getConfig()->createDirIfNotExists($path)) { - return false; - } - if (!$this->getPackageXml()) { - $this->generatePackageXml(); - } - $this->getPackage()->save($path); - return true; - } - - /** - * Create package file compatible with previous version of Magento Connect Manager - * - * @return boolean - */ - public function createPackageV1x() - { - $path = Mage::helper('connect')->getLocalPackagesPathV1x(); - if (!Mage::getConfig()->createDirIfNotExists($path)) { - return false; - } - if (!$this->getPackageXml()) { - $this->generatePackageXml(); - } - $this->getPackage()->saveV1x($path); - return true; - } - - /** - * Retrieve stability value and name for options - * - * @return array - */ - public function getStabilityOptions() - { - return array( - 'devel' => 'Development', - 'alpha' => 'Alpha', - 'beta' => 'Beta', - 'stable' => 'Stable', - ); - } - - /** - * Retrieve targets - * - * @return array - */ - public function getLabelTargets() - { - if (!is_array($this->_targets)) { - $objectTarget = new Mage_Connect_Package_Target(); - $this->_targets = $objectTarget->getLabelTargets(); - } - return $this->_targets; - } - -} diff --git a/app/code/core/Mage/Connect/Model/Extension/Collection.php b/app/code/core/Mage/Connect/Model/Extension/Collection.php deleted file mode 100644 index a9166957c8a..00000000000 --- a/app/code/core/Mage/Connect/Model/Extension/Collection.php +++ /dev/null @@ -1,105 +0,0 @@ - - */ -class Mage_Connect_Model_Extension_Collection extends Varien_Data_Collection_Filesystem -{ - /** - * Files and folders regexsp - * - * @var string - */ - protected $_allowedDirsMask = '/^[a-z0-9\.\-]+$/i'; - protected $_allowedFilesMask = '/^[a-z0-9\.\-\_]+\.(xml|ser)$/i'; - protected $_disallowedFilesMask = '/^package\.xml$/i'; - - /** - * Base dir where packages are located - * - * @var string - */ - protected $_baseDir = ''; - - /** - * Set base dir - */ - public function __construct() - { - $this->_baseDir = Mage::getBaseDir('var') . DS . 'connect'; - $io = new Varien_Io_File(); - $io->setAllowCreateFolders(true)->createDestinationDir($this->_baseDir); - $this->addTargetDir($this->_baseDir); - } - - /** - * Row generator - * - * @param string $filename - * @return array - */ - protected function _generateRow($filename) - { - $row = parent::_generateRow($filename); - $row['package'] = preg_replace('/\.(xml|ser)$/', '', str_replace($this->_baseDir . DS, '', $filename)); - $row['filename_id'] = $row['package']; - $folder = explode(DS, $row['package']); - array_pop($folder); - $row['folder'] = DS; - if (!empty($folder)) { - $row['folder'] = implode(DS, $folder) . DS; - } - return $row; - } - - /** - * Get all folders as options array - * - * @return array - */ - public function collectFolders() - { - $collectFiles = $this->_collectFiles; - $collectDirs = $this->_collectDirs; - $this->setCollectFiles(false)->setCollectDirs(true); - - $this->_collectRecursive($this->_baseDir); - $result = array(DS => DS); - foreach ($this->_collectedDirs as $dir) { - $dir = str_replace($this->_baseDir . DS, '', $dir) . DS; - $result[$dir] = $dir; - } - - $this->setCollectFiles($collectFiles)->setCollectDirs($collectDirs); - return $result; - } - -} diff --git a/app/code/core/Mage/Connect/Model/Session.php b/app/code/core/Mage/Connect/Model/Session.php deleted file mode 100644 index faeace429eb..00000000000 --- a/app/code/core/Mage/Connect/Model/Session.php +++ /dev/null @@ -1,103 +0,0 @@ - - */ -class Mage_Connect_Model_Session extends Mage_Core_Model_Session_Abstract -{ - - /** - * Contructor - */ - public function __construct() - { - $this->init('adminhtml'); - } - - /** - * Retrieve parameters of extension from session. - * Compatible with old version extension info file. - * - * @return array - */ - public function getCustomExtensionPackageFormData() - { - $data = $this->getData('custom_extension_package_form_data'); - /* convert Maintainers to Authors */ - if (!isset($data['authors']) || count($data['authors']) == 0) { - if (isset($data['maintainers'])) { - $data['authors']['name'] = array(); - $data['authors']['user'] = array(); - $data['authors']['email'] = array(); - foreach ($data['maintainers']['name'] as $i => $name) { - if (!$data['maintainers']['name'][$i] && !$data['maintainers']['handle'][$i] && !$data['maintainers']['email'][$i]) { - continue; - } - array_push($data['authors']['name'], $data['maintainers']['name'][$i]); - array_push($data['authors']['user'], $data['maintainers']['handle'][$i]); - array_push($data['authors']['email'], $data['maintainers']['email'][$i]); - } - // Convert channel from previous version for entire package - if (isset($data['channel'])) { - $data['channel'] = Mage::helper('connect')->convertChannelFromV1x($data['channel']); - } - // Convert channel from previous version for each required package - $nRequiredPackages = count($data['depends']['package']['channel']); - for ($i = 0; $i < $nRequiredPackages; $i++) { - $channel = $data['depends']['package']['channel'][$i]; - if ($channel) { - $data['depends']['package']['channel'][$i] = Mage::helper('connect')->convertChannelFromV1x($channel); - } - } - } - } - - /* convert Release version to Version */ - if (!isset($data['version'])) { - if (isset($data['release_version'])) { - $data['version'] = $data['release_version']; - } - } - /* convert Release stability to Stability */ - if (!isset($data['stability'])) { - if (isset($data['release_stability'])) { - $data['stability'] = $data['release_stability']; - } - } - /* convert contents */ - if (!isset($data['contents']['target'])) { - $data['contents']['target'] = $data['contents']['role']; - } - return $data; - } - -} diff --git a/app/code/core/Mage/Connect/controllers/Adminhtml/Extension/CustomController.php b/app/code/core/Mage/Connect/controllers/Adminhtml/Extension/CustomController.php deleted file mode 100644 index 00173ff5d31..00000000000 --- a/app/code/core/Mage/Connect/controllers/Adminhtml/Extension/CustomController.php +++ /dev/null @@ -1,204 +0,0 @@ - - */ -class Mage_Connect_Adminhtml_Extension_CustomController extends Mage_Adminhtml_Controller_Action -{ - /** - * Redirect to edit Extension Package action - * - */ - public function indexAction() - { - $this->_title($this->__('System')) - ->_title($this->__('Magento Connect')) - ->_title($this->__('Package Extensions')); - - $this->_forward('edit'); - } - - /** - * Edit Extension Package Form - * - */ - public function editAction() - { - $this->_title($this->__('System')) - ->_title($this->__('Magento Connect')) - ->_title($this->__('Package Extensions')) - ->_title($this->__('Edit Extension')); - - $this->loadLayout(); - $this->_setActiveMenu('system/extension/custom'); - $this->renderLayout(); - } - - /** - * Reset Extension Package form data - * - */ - public function resetAction() - { - Mage::getSingleton('connect/session')->unsCustomExtensionPackageFormData(); - $this->_redirect('*/*/edit'); - } - - /** - * Load Local Extension Package - * - */ - public function loadAction() - { - $packageName = base64_decode(strtr($this->getRequest()->getParam('id'), '-_,', '+/=')); - if ($packageName) { - $session = Mage::getSingleton('connect/session'); - try { - $data = Mage::helper('connect')->loadLocalPackage($packageName); - if (!$data) { - Mage::throwException(Mage::helper('connect')->__('Failed to load the package data.')); - } - $data = array_merge($data, array('file_name' => $packageName)); - $session->setCustomExtensionPackageFormData($data); - $session->addSuccess( - Mage::helper('connect')->__('The package %s data has been loaded.', $packageName) - ); - } catch (Exception $e) { - $session->addError($e->getMessage()); - } - } - $this->_redirect('*/*/edit'); - } - - /** - * Save Extension Package - * - */ - public function saveAction() - { - $session = Mage::getSingleton('connect/session'); - $p = $this->getRequest()->getPost(); - - if (!empty($p['_create'])) { - $create = true; - unset($p['_create']); - } - - if ($p['file_name'] == '') { - $p['file_name'] = $p['name']; - } - - $session->setCustomExtensionPackageFormData($p); - try { - $ext = Mage::getModel('connect/extension'); - /** @var $ext Mage_Connect_Model_Extension */ - $ext->setData($p); - if ($ext->savePackage()) { - $session->addSuccess(Mage::helper('connect')->__('The package data has been saved.')); - } else { - $session->addError(Mage::helper('connect')->__('There was a problem saving package data')); - $this->_redirect('*/*/edit'); - } - if (empty($create)) { - $this->_redirect('*/*/edit'); - } else { - $this->_forward('create'); - } - } catch (Mage_Core_Exception $e){ - $session->addError($e->getMessage()); - $this->_redirect('*/*'); - } catch (Exception $e){ - $session->addException($e, Mage::helper('connect')->__('Failed to save the package.')); - $this->_redirect('*/*'); - } - } - - /** - * Create new Extension Package - * - */ - public function createAction() - { - $session = Mage::getSingleton('connect/session'); - try { - $p = $this->getRequest()->getPost(); - $session->setCustomExtensionPackageFormData($p); - $ext = Mage::getModel('connect/extension'); - $ext->setData($p); - $packageVersion = $this->getRequest()->getPost('version_ids'); - if (is_array($packageVersion)) { - if (in_array(Mage_Connect_Package::PACKAGE_VERSION_2X, $packageVersion)) { - $ext->createPackage(); - } - if (in_array(Mage_Connect_Package::PACKAGE_VERSION_1X, $packageVersion)) { - $ext->createPackageV1x(); - } - } - $this->_redirect('*/*'); - } catch(Mage_Core_Exception $e){ - $session->addError($e->getMessage()); - $this->_redirect('*/*'); - } catch(Exception $e){ - $session->addException($e, Mage::helper('connect')->__('Failed to create the package.')); - $this->_redirect('*/*'); - } - } - - /** - * Load Grid with Local Packages - * - */ - public function loadtabAction() - { - $this->loadLayout(); - $this->renderLayout(); - } - - /** - * Grid for loading packages - * - */ - public function gridAction() - { - $this->loadLayout(); - $this->renderLayout(); - } - - /** - * Check is allowed access to actions - * - * @return bool - */ - protected function _isAllowed() - { - return Mage::getSingleton('admin/session')->isAllowed('system/extensions/custom'); - } -} diff --git a/app/code/core/Mage/Connect/controllers/Adminhtml/Extension/LocalController.php b/app/code/core/Mage/Connect/controllers/Adminhtml/Extension/LocalController.php deleted file mode 100644 index b01b8ea8da1..00000000000 --- a/app/code/core/Mage/Connect/controllers/Adminhtml/Extension/LocalController.php +++ /dev/null @@ -1,55 +0,0 @@ - - */ -class Mage_Connect_Adminhtml_Extension_LocalController extends Mage_Adminhtml_Controller_Action -{ - /** - * Redirect to Magento Connect - * - */ - public function indexAction() - { - $url = Mage::getBaseUrl('web') . 'downloader/?return=' . urlencode(Mage::getUrl('adminhtml')); - $this->getResponse()->setRedirect($url); - } - - /** - * Check is allowed access to action - * - * @return bool - */ - protected function _isAllowed() - { - return Mage::getSingleton('admin/session')->isAllowed('system/extensions/local'); - } -} diff --git a/app/code/core/Mage/Connect/etc/adminhtml.xml b/app/code/core/Mage/Connect/etc/adminhtml.xml deleted file mode 100644 index bb601ec71e8..00000000000 --- a/app/code/core/Mage/Connect/etc/adminhtml.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - Magento Connect - 80 - - - Magento Connect Manager - adminhtml/extension_local - - - Package Extensions - adminhtml/extension_custom - - - - - - - diff --git a/app/code/core/Mage/Connect/etc/config.xml b/app/code/core/Mage/Connect/etc/config.xml deleted file mode 100644 index d5e902ca625..00000000000 --- a/app/code/core/Mage/Connect/etc/config.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - 1.6.0.0 - - - - - - Mage_Connect_Model - - - - - Mage_Connect_Block - - - - - - - - - Mage_Connect_Adminhtml - - - - - - - - - - connect.xml - - - - - diff --git a/app/code/core/Mage/Install/Block/Download.php b/app/code/core/Mage/Install/Block/Download.php deleted file mode 100644 index 24acbe9ac2d..00000000000 --- a/app/code/core/Mage/Install/Block/Download.php +++ /dev/null @@ -1,66 +0,0 @@ - - */ -class Mage_Install_Block_Download extends Mage_Install_Block_Abstract -{ - public function __construct() - { - parent::__construct(); - $this->setTemplate('install/download.phtml'); - } - - /** - * Retrieve locale data post url - * - * @return string - */ - public function getPostUrl() - { - return $this->getUrl('*/*/downloadPost'); - } - - public function getNextUrl() - { - return Mage::getModel('install/wizard') - ->getStepByName('download') - ->getNextUrl(); - } - - public function hasLocalCopy() - { - $dir = Mage::getConfig()->getModuleDir('etc', 'Mage_Adminhtml'); - if ($dir && file_exists($dir)) { - return true; - } - return false; - } -} - diff --git a/app/code/core/Mage/Install/Block/State.php b/app/code/core/Mage/Install/Block/State.php index 8d484da18a8..406986e91f3 100644 --- a/app/code/core/Mage/Install/Block/State.php +++ b/app/code/core/Mage/Install/Block/State.php @@ -33,39 +33,10 @@ */ class Mage_Install_Block_State extends Mage_Core_Block_Template { - public function __construct() + public function __construct() { $this->setTemplate('install/state.phtml'); $this->assign('steps', Mage::getSingleton('install/wizard')->getSteps()); } - - /** - * Get previous downloader steps - * - * @return array - */ - public function getDownloaderSteps() - { - if ($this->isDownloaderInstall()) { - $steps = array( - Mage::helper('install')->__('Welcome'), - Mage::helper('install')->__('Validation'), - Mage::helper('install')->__('Magento Connect Manager Deployment'), - ); - return $steps; - } else { - return array(); - } - } - /** - * Checks for Magento Connect Manager installation method - * - * @return bool - */ - public function isDownloaderInstall() - { - $session = Mage::app()->getCookie()->get('magento_downloader_session'); - return $session ? true : false; - } } diff --git a/app/code/core/Mage/Install/Model/Installer.php b/app/code/core/Mage/Install/Model/Installer.php index 35ca61bbd01..a7434e39bd2 100644 --- a/app/code/core/Mage/Install/Model/Installer.php +++ b/app/code/core/Mage/Install/Model/Installer.php @@ -83,23 +83,6 @@ public function setDataModel(Varien_Object $model) return $this; } - /** - * Check packages (pear) downloads - * - * @return boolean - */ - public function checkDownloads() - { - try { - $result = Mage::getModel('install/installer_pear')->checkDownloads(); - $result = true; - } catch (Exception $e) { - $result = false; - } - $this->setDownloadCheckStatus($result); - return $result; - } - /** * Check server settings * diff --git a/app/code/core/Mage/Install/Model/Installer/Pear.php b/app/code/core/Mage/Install/Model/Installer/Pear.php deleted file mode 100644 index 4d0ba242275..00000000000 --- a/app/code/core/Mage/Install/Model/Installer/Pear.php +++ /dev/null @@ -1,78 +0,0 @@ - - */ -class Mage_Install_Model_Installer_Pear extends Mage_Install_Model_Installer_Abstract -{ - public function getPackages() - { - $packages = array( - 'pear/PEAR-stable', - 'connect.magentocommerce.com/core/Mage_Pear_Helpers', - 'connect.magentocommerce.com/core/Lib_ZF', - 'connect.magentocommerce.com/core/Lib_Varien', - 'connect.magentocommerce.com/core/Mage_All', - 'connect.magentocommerce.com/core/Interface_Frontend_Default', - 'connect.magentocommerce.com/core/Interface_Adminhtml_Default', - 'connect.magentocommerce.com/core/Interface_Install_Default', - ); - return $packages; - } - - public function checkDownloads() - { - $pear = new Varien_Pear; - $pkg = new PEAR_PackageFile($pear->getConfig(), false); - $result = true; - foreach ($this->getPackages() as $package) { - $obj = $pkg->fromAnyFile($package, PEAR_VALIDATE_NORMAL); - if (PEAR::isError($obj)) { - $uinfo = $obj->getUserInfo(); - if (is_array($uinfo)) { - foreach ($uinfo as $message) { - if (is_array($message)) { - $message = $message['message']; - } - Mage::getSingleton('install/session')->addError($message); - } - } else { - print_r($obj->getUserInfo()); - #Mage::getSingleton('install/session')->addError($message); - } - $result = false; - } - } - return $result; - } -} diff --git a/app/code/core/Mage/Install/controllers/WizardController.php b/app/code/core/Mage/Install/controllers/WizardController.php index 182847f48e1..f57ac390328 100644 --- a/app/code/core/Mage/Install/controllers/WizardController.php +++ b/app/code/core/Mage/Install/controllers/WizardController.php @@ -188,95 +188,6 @@ public function localePostAction() $this->getResponse()->setRedirect($step->getNextUrl()); } - public function downloadAction() - { - $this->_checkIfInstalled(); - $this->setFlag('', self::FLAG_NO_DISPATCH_BLOCK_EVENT, true); - $this->setFlag('', self::FLAG_NO_POST_DISPATCH, true); - - $this->_prepareLayout(); - $this->_initLayoutMessages('install/session'); - $this->getLayout()->getBlock('content')->append( - $this->getLayout()->createBlock('install/download', 'install.download') - ); - - $this->renderLayout(); - } - - public function downloadPostAction() - { - $this->_checkIfInstalled(); - switch ($this->getRequest()->getPost('continue')) { - case 'auto': - $this->_forward('downloadAuto'); - break; - - case 'manual': - $this->_forward('downloadManual'); - break; - - case 'svn': - $step = $this->_getWizard()->getStepByName('download'); - $this->getResponse()->setRedirect($step->getNextUrl()); - break; - - default: - $this->_redirect('*/*/download'); - } - } - - public function downloadAutoAction() - { - $step = $this->_getWizard()->getStepByName('download'); - $this->getResponse()->setRedirect($step->getNextUrl()); - } - - public function installAction() - { - $pear = Varien_Pear::getInstance(); - $params = array('comment'=>Mage::helper('install')->__("Downloading and installing Magento, please wait...") . "\r\n\r\n"); - if ($this->getRequest()->getParam('do')) { - if ($state = $this->getRequest()->getParam('state', 'beta')) { - $result = $pear->runHtmlConsole(array( - 'comment' => Mage::helper('install')->__("Setting preferred state to: %s", $state) . "\r\n\r\n", - 'command' => 'config-set', - 'params' => array('preferred_state', $state) - )); - if ($result instanceof PEAR_Error) { - $this->installFailureCallback(); - exit; - } - } - $params['command'] = 'install'; - $params['options'] = array('onlyreqdeps'=>1); - $params['params'] = Mage::getModel('install/installer_pear')->getPackages(); - $params['success_callback'] = array($this, 'installSuccessCallback'); - $params['failure_callback'] = array($this, 'installFailureCallback'); - } - $pear->runHtmlConsole($params); - Mage::app()->getFrontController()->getResponse()->clearAllHeaders(); - } - - public function installSuccessCallback() - { - echo 'parent.installSuccess()'; - } - - public function installFailureCallback() - { - echo 'parent.installFailure()'; - } - - public function downloadManualAction() - { - $step = $this->_getWizard()->getStepByName('download'); - #if (!$this->_getInstaller()->checkDownloads()) { - # $this->getResponse()->setRedirect($step->getUrl()); - #} else { - $this->getResponse()->setRedirect($step->getNextUrl()); - #} - } - /** * Configuration data installation */ diff --git a/app/design/adminhtml/default/default/layout/connect.xml b/app/design/adminhtml/default/default/layout/connect.xml deleted file mode 100644 index 630d1402d09..00000000000 --- a/app/design/adminhtml/default/default/layout/connect.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - package_infotab_package - release_infotab_release - authorstab_authors - dependenciestab_depends - contentstab_contents - load_local_packagetab_local - - - - - - - - - - - - - - - - - - - diff --git a/app/design/adminhtml/default/default/template/connect/extension/custom/authors.phtml b/app/design/adminhtml/default/default/template/connect/extension/custom/authors.phtml deleted file mode 100644 index 5ac7bec0fd6..00000000000 --- a/app/design/adminhtml/default/default/template/connect/extension/custom/authors.phtml +++ /dev/null @@ -1,91 +0,0 @@ - - - -
- getFormHtml() ?> -
-

__("Authors") ?>

-
-
- __("Authors") ?> - - - - - - - - - - - - - - - - - -
__("Name") ?> *__("User") ?> *__("Email") ?> *__("Remove") ?>
getAddAuthorButtonHtml() ?>
-
-
diff --git a/app/design/adminhtml/default/default/template/connect/extension/custom/contents.phtml b/app/design/adminhtml/default/default/template/connect/extension/custom/contents.phtml deleted file mode 100644 index d055e685f6a..00000000000 --- a/app/design/adminhtml/default/default/template/connect/extension/custom/contents.phtml +++ /dev/null @@ -1,91 +0,0 @@ - - -
- getFormHtml() ?> - -
-

__("Contents") ?>

-
-
- __("Contents") ?> - - - - - - - - - - - - - - - - - - - getData('contents/target')): ?> - getData('contents/target') as $_i=>$_dbField): ?> - - - - - - - - - - - - -
__("Target") ?>__("Path") ?>__("Type") ?>__("Include") ?>__("Ignore") ?>__("Action") ?>
getAddRowButtonHtml('contents_container', 'contents_template', $this->__('Add Contents Path')) ?>
-
-
diff --git a/app/design/adminhtml/default/default/template/connect/extension/custom/depends.phtml b/app/design/adminhtml/default/default/template/connect/extension/custom/depends.phtml deleted file mode 100644 index c2253531c6e..00000000000 --- a/app/design/adminhtml/default/default/template/connect/extension/custom/depends.phtml +++ /dev/null @@ -1,137 +0,0 @@ - -
- getFormHtml() ?> - -
-

__("Packages") ?>

-
-
- __("Packages") ?> - - - - - - - - - - - - - - - - - - - - - getData('depends/package/name')): ?> - getData('depends/package/name') as $_i=>$_dbField): ?> - - - - - - - - - - - - -
__("Package") ?>__("Channel") ?>__("Min") ?>__("Max") ?>__("Files") ?>__("Action") ?>
getAddRowButtonHtml('depends_packages_container', 'depends_packages_template', $this->__('Add Package dependency')) ?>
-
- -
-

__("Extensions") ?>

-
-
- __("Extensions") ?> - - - - - - - - - - - - - - - - - getData('depends/extension/name')): ?> - getData('depends/extension/name') as $_i=>$_dbField): ?> - - - - - - - - - - - - -
__("Extension") ?>__("Min") ?>__("Max") ?>__("Action") ?>
getAddRowButtonHtml('depends_extensions_container', 'depends_extensions_template', $this->__('Add PHP Extension dependency')) ?>
-
- -
diff --git a/app/design/adminhtml/default/default/template/connect/extension/custom/load.phtml b/app/design/adminhtml/default/default/template/connect/extension/custom/load.phtml deleted file mode 100644 index 9f9dd0c9334..00000000000 --- a/app/design/adminhtml/default/default/template/connect/extension/custom/load.phtml +++ /dev/null @@ -1,35 +0,0 @@ - - - -getPackageGridHtml() ?> diff --git a/app/design/adminhtml/default/default/template/connect/extension/custom/package.phtml b/app/design/adminhtml/default/default/template/connect/extension/custom/package.phtml deleted file mode 100644 index 0f8a43ea0e6..00000000000 --- a/app/design/adminhtml/default/default/template/connect/extension/custom/package.phtml +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - -
- - getFormHtml() ?> -
diff --git a/app/design/adminhtml/default/default/template/connect/extension/custom/release.phtml b/app/design/adminhtml/default/default/template/connect/extension/custom/release.phtml deleted file mode 100644 index a8adb7a0261..00000000000 --- a/app/design/adminhtml/default/default/template/connect/extension/custom/release.phtml +++ /dev/null @@ -1,29 +0,0 @@ - -
- getFormHtml() ?> -
diff --git a/app/design/install/default/default/template/install/download.phtml b/app/design/install/default/default/template/install/download.phtml deleted file mode 100644 index a3ba76fdf5f..00000000000 --- a/app/design/install/default/default/template/install/download.phtml +++ /dev/null @@ -1,127 +0,0 @@ - - -
-

__('Download Magento Core Modules and Updates') ?>

-
-getMessagesBlock()->toHtml() ?> - -
- -hasLocalCopy()): ?> -
- __('Full Download / SVN Installation') ?> -

__('Full Download / SVN Installation') ?>

- -

__("If you have downloaded the full package or installed Magento through SVN, you should skip packages installation and validation by clicking the button below.") ?>

- -

-
- - -
- __('Package Management through the Web') ?> -

__('Package Management through the Web') ?>

- -

__("If you wish to manage Magento packages through the web admin interface, you will need to have web writeable permissions applied to all Magento folders and files.") ?>

-

__("If your server is running on MS Windows, most probably you will not need to change anything.") ?>

-

__("If you are running PHP as CGI, your PHP processes may run under the same user as the user you used when uploading Magento files.") ?>

-

__("In other cases you will need to make Magento files writeable for the user that the web server process is running under.") ?>

- -

__("Preferred stability: %s", $this->__("BETA")) ?>

-

__("Currently this is the most stable state available for Magento packages.") ?>
__("Choose this if you would like to test frontend and backend functionality.") ?>

-

-
-

__("Preferred stability: %s", $this->__("ALPHA")) ?>

-

__("If you are a developer and would like to have the latest public updates, choose this option.") ?>
__("Please note that it is much less stable than beta.") ?>

-

-
- -
- -
- __('Manual Downloads and Upgrades') ?> -

__('Manual Downloads and Upgrades') ?>

- -

__("If you are running the install wizard over a previously downloaded and installed Magento installation, proceed with this method.") ?>

-

__("If you do not wish or are not able to have Magento folders writeable for the web process, you could use PEAR executable located in the root of Magento installation.") ?>

-

__("Please note that only UNIX, Linux and Mac OS X shells are currently supported. For Windows use the '%s' option.", $this->__('Package Management through the Web')) ?>

-

__("Run this in your shell from Magento root folder:") ?>

-
-./pear mage-setup
-./pear install mage-core/Mage_Pear_Helpers mage-core/Lib_ZF mage-core/Lib_Varien
-./pear install mage-core/Mage_All mage-core/Interface_Install_Default
-./pear install mage-core/Interface_Frontend_Default mage-core/Interface_Adminhtml_Default
-
-
-

__("After successfull installation please click the button below.") ?>

- -

-
- -
- - diff --git a/app/design/install/default/default/template/install/state.phtml b/app/design/install/default/default/template/install/state.phtml index 69372824cff..aaf19c4b1f8 100644 --- a/app/design/install/default/default/template/install/state.phtml +++ b/app/design/install/default/default/template/install/state.phtml @@ -27,10 +27,6 @@

__('Installation') ?>

    -getDownloaderSteps() as $step): ?> -
  1. - -
  2. __('Download')?>
  3. getActive()): ?>style="color:green; font-weight:bold; ">__($_step->getCode()) ?>
  4. diff --git a/app/etc/modules/Mage_Connect.xml b/app/etc/modules/Mage_Connect.xml deleted file mode 100644 index b95883d3933..00000000000 --- a/app/etc/modules/Mage_Connect.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - true - core - - - - diff --git a/app/locale/en_US/Mage_Adminhtml.csv b/app/locale/en_US/Mage_Adminhtml.csv index a409bd96abb..de1a691c2b5 100644 --- a/app/locale/en_US/Mage_Adminhtml.csv +++ b/app/locale/en_US/Mage_Adminhtml.csv @@ -566,8 +566,6 @@ "MS Excel XML","MS Excel XML" "Magento Admin","Magento Admin" "Magento Commerce - Administrative Panel","Magento Commerce - Administrative Panel" -"Magento Connect","Magento Connect" -"Magento Connect Manager","Magento Connect Manager" "Magento Logo","Magento Logo" "Magento is a trademark of Magento Inc. Copyright © %s Magento Inc.","Magento is a trademark of Magento Inc. Copyright © %s Magento Inc." "Magento root directory","Magento root directory" @@ -711,7 +709,6 @@ "Original Magento attribute names in first row:","Original Magento attribute names in first row:" "Out of stock","Out of stock" "PDT (Payment Data Transfer) Only","PDT (Payment Data Transfer) Only" -"Package Extensions","Package Extensions" "Pages","Pages" "Parent Product Thumbnail","Parent Product Thumbnail" "Parent Transaction ID","Parent Transaction ID" diff --git a/app/locale/en_US/Mage_Connect.csv b/app/locale/en_US/Mage_Connect.csv deleted file mode 100644 index 6470dc9e4cf..00000000000 --- a/app/locale/en_US/Mage_Connect.csv +++ /dev/null @@ -1,58 +0,0 @@ -"1.5.0.0 & later","1.5.0.0 & later" -"Action","Action" -"Add Author","Add Author" -"Add Contents Path","Add Contents Path" -"Add PHP Extension dependency","Add PHP Extension dependency" -"Add Package dependency","Add Package dependency" -"Add files","Add files" -"Authors","Authors" -"Channel","Channel" -"Contents","Contents" -"Create Extension Package","Create Extension Package" -"Dependencies","Dependencies" -"Description","Description" -"Edit Extension","Edit Extension" -"Email","Email" -"Extension","Extension" -"Extensions","Extensions" -"Failed to create the package.","Failed to create the package." -"Failed to load the package data.","Failed to load the package data." -"Failed to save the package.","Failed to save the package." -"Files","Files" -"Folder","Folder" -"Ignore","Ignore" -"Include","Include" -"License","License" -"License URI","License URI" -"Load Local Package","Load Local Package" -"Load local Package","Load local Package" -"Magento Connect","Magento Connect" -"Magento Connect Manager","Magento Connect Manager" -"Max","Max" -"Maximum","Maximum" -"Min","Min" -"Minimum","Minimum" -"Name","Name" -"New Extension","New Extension" -"PHP Version","PHP Version" -"Package","Package" -"Package Extensions","Package Extensions" -"Package File Name","Package File Name" -"Package Info","Package Info" -"Packages","Packages" -"Path","Path" -"Pre-1.5.0.0","Pre-1.5.0.0" -"Release Info","Release Info" -"Remove","Remove" -"Save As...","Save As..." -"Save Data and Create Package","Save Data and Create Package" -"Save package with custom package file name","Save package with custom package file name" -"Summary","Summary" -"Supported releases","Supported releases" -"System","System" -"Target","Target" -"The package %s data has been loaded.","The package %s data has been loaded." -"The package data has been saved.","The package data has been saved." -"There was a problem saving package data","There was a problem saving package data" -"Type","Type" -"User","User" diff --git a/app/locale/en_US/Mage_Install.csv b/app/locale/en_US/Mage_Install.csv index bfb89f466b7..5d076bb1111 100644 --- a/app/locale/en_US/Mage_Install.csv +++ b/app/locale/en_US/Mage_Install.csv @@ -68,7 +68,6 @@ "Localization","Localization" "Login Information","Login Information" "Magento","Magento" -"Magento Connect Manager Deployment","Magento Connect Manager Deployment" "Magento Installation Wizard","Magento Installation Wizard" "Magento is a trademark of Magento Inc. Copyright © %s Magento Inc.","Magento is a trademark of Magento Inc. Copyright © %s Magento Inc." "Magento uses this key to encrypt passwords, credit cards and more. If this field is left empty the system will create an encryption key for you and will display it on the next page.","Magento uses this key to encrypt passwords, credit cards and more. If this field is left empty the system will create an encryption key for you and will display it on the next page." diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Content.php b/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Content.php deleted file mode 100644 index 11952660995..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Content.php +++ /dev/null @@ -1,118 +0,0 @@ -_rootElement->find($this->channelTitle)->getText(); - } - - /** - * Click on the 'Check for Upgrades' button - */ - public function checkForUpgrades() - { - $this->_rootElement->find($this->checkUpgradesButton)->click(); - $this->waitForElementVisible($this->upgradeAvailable); - } - - /** - * Select package for upgrade - * - * @param Connect $connect - */ - public function selectPackages(Connect $connect) - { - $this->fill($connect); - } - - /** - * Start downloading - */ - public function commitChanges() - { - $this->_rootElement->find($this->commitChangesButton)->click(); - $this->waitForElementVisible($this->connectFrame); - $this->waitForElementVisible($this->message); - } -} diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Content.xml b/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Content.xml deleted file mode 100644 index 8dcab95d6fd..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Content.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - actions - - - [name*=Mage_All_Latest] - select - - - diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Login.php b/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Login.php deleted file mode 100644 index 217b68f63e5..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Login.php +++ /dev/null @@ -1,65 +0,0 @@ -_rootElement->find($this->submit, Locator::SELECTOR_CSS)->click(); - } - - /** - * Log in to Connect Manager. - * - * @param User $adminUser - */ - public function loginToConnectManager(User $adminUser) - { - $this->fill($adminUser); - $this->submit(); - } -} diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Login.xml b/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Login.xml deleted file mode 100644 index 3ca54d604d8..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Login.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - [name="username"] - - - [name="password"] - - - diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Navigation.php b/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Navigation.php deleted file mode 100644 index da8e0cd0ba9..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Block/Connect/Navigation.php +++ /dev/null @@ -1,63 +0,0 @@ -_rootElement->find($this->settingsTab)->click(); - } - - /** - * Open 'Extensions' tab - */ - public function openExtensionsTabs() - { - $this->_rootElement->find($this->extensionsTab)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Constraint/AssertChannelTextPresent.php b/dev/tests/functional/tests/app/Mage/Connect/Test/Constraint/AssertChannelTextPresent.php deleted file mode 100644 index 59844b97555..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Constraint/AssertChannelTextPresent.php +++ /dev/null @@ -1,66 +0,0 @@ -getConnectContent()->getChannelTitle(), - 'License agreement text is absent.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Magento has connected to channel successfully"; - } -} diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Constraint/AssertSuccessUpgrade.php b/dev/tests/functional/tests/app/Mage/Connect/Test/Constraint/AssertSuccessUpgrade.php deleted file mode 100644 index 61c4dc6817a..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Constraint/AssertSuccessUpgrade.php +++ /dev/null @@ -1,60 +0,0 @@ -getMessages()->getSuccessMessages() - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Upgrade has been successfully"; - } -} diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Fixture/Connect.xml b/dev/tests/functional/tests/app/Mage/Connect/Test/Fixture/Connect.xml deleted file mode 100644 index 072a766d89e..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Fixture/Connect.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/Page/ConnectManager.xml b/dev/tests/functional/tests/app/Mage/Connect/Test/Page/ConnectManager.xml deleted file mode 100644 index d708e8c1379..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/Page/ConnectManager.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/TestCase/UpgradeTest.php b/dev/tests/functional/tests/app/Mage/Connect/Test/TestCase/UpgradeTest.php deleted file mode 100644 index a4f4cce845b..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/TestCase/UpgradeTest.php +++ /dev/null @@ -1,103 +0,0 @@ -fixtureFactory = $fixtureFactory; - $config = \Magento\Mtf\ObjectManagerFactory::getObjectManager()->get('Magento\Mtf\Config\GlobalConfig'); - $adminCred['username'] = $config->get('application/0/backendLogin/0/value'); - $adminCred['password'] = $config->get('application/0/backendPassword/0/value'); - $newVersion['Mage_All_Latest'] = $config->get('version/0/value'); - $adminFixture = $this->fixtureFactory->createByCode('user', ['data' => $adminCred]); - $connectFixture = $this->fixtureFactory->createByCode('connect', ['data' => $newVersion]); - return ['adminUser' => $adminFixture, 'connect' => $connectFixture]; - } - - /** - * Injection data. - * - * @param ConnectManager $connectManagerPage - */ - public function __inject( - ConnectManager $connectManagerPage - ) { - $this->connectManagerPage = $connectManagerPage; - } - - /** - * Upgrade Magento via Magento Connect Manager. - * - * @param AssertChannelTextPresent $assertChannelTextPresent - * @param User $adminUser - * @param Connect $connect - * @return array - */ - public function test(AssertChannelTextPresent $assertChannelTextPresent, User $adminUser, Connect $connect) - { - $this->connectManagerPage->open(); - $this->connectManagerPage->getConnectLogin()->loginToConnectManager($adminUser); - $assertChannelTextPresent->processAssert($this->connectManagerPage); - $this->connectManagerPage->getConnectContent()->checkForUpgrades(); - $this->connectManagerPage->getConnectContent()->selectPackages($connect); - $this->connectManagerPage->getConnectContent()->commitChanges(); - } -} diff --git a/dev/tests/functional/tests/app/Mage/Connect/Test/TestCase/UpgradeTest.xml b/dev/tests/functional/tests/app/Mage/Connect/Test/TestCase/UpgradeTest.xml deleted file mode 100644 index 7d66894d7cd..00000000000 --- a/dev/tests/functional/tests/app/Mage/Connect/Test/TestCase/UpgradeTest.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - Upgrade - test_type:upgrade - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Block/ContinueDownloadBlock.php b/dev/tests/functional/tests/app/Mage/Install/Test/Block/ContinueDownloadBlock.php deleted file mode 100644 index fe48b9610a9..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Block/ContinueDownloadBlock.php +++ /dev/null @@ -1,122 +0,0 @@ -_rootElement->find($this->continueDeploy)->click(); - } - - /** - * Continue installation. - * - * @return void - */ - public function continueValidation() - { - $this->_rootElement->find($this->continueValidation)->click(); - } - - /** - * Continue installation. - * - * @return void - */ - public function continueDownload() - { - $this->waitForElementVisible($this->continueDownload); - $this->_rootElement->find($this->continueDownload)->click(); - } - - /** - * Continue installation. - * - * @return void - */ - public function startDownload() - { - $this->_rootElement->find($this->startDownload)->click(); - } - - /** - * Continue installation. - * - * @return void - */ - public function continueMagentoInstallation() - { - $this->waitForElementVisible($this->continueMagentoInstallation); - $this->_rootElement->find($this->continueMagentoInstallation)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertDownloadCompleted.php b/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertDownloadCompleted.php deleted file mode 100644 index 5c981898343..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertDownloadCompleted.php +++ /dev/null @@ -1,67 +0,0 @@ -getMessagesBlock()->getSuccessMessages()); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Downloading"; - } -} diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertSuccessDeploy.php b/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertSuccessDeploy.php deleted file mode 100644 index 15e2473287d..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertSuccessDeploy.php +++ /dev/null @@ -1,67 +0,0 @@ -getMainBlock()->getDeployStatus()); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Downloading"; - } -} diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertWelcomeWizardTextPresent.php b/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertWelcomeWizardTextPresent.php deleted file mode 100644 index cf623e08b45..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Constraint/AssertWelcomeWizardTextPresent.php +++ /dev/null @@ -1,66 +0,0 @@ -getWelcomeBlock()->getWizardTitle(), - 'This wrong page' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "License agreement text is present on Terms & Agreement page."; - } -} diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Page/Downloader.xml b/dev/tests/functional/tests/app/Mage/Install/Test/Page/Downloader.xml deleted file mode 100644 index 28f014aee93..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Page/Downloader.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderDeploy.xml b/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderDeploy.xml deleted file mode 100644 index 70dc22504a5..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderDeploy.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderDeployEnd.xml b/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderDeployEnd.xml deleted file mode 100644 index 7c7d651a3d2..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderDeployEnd.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderValidation.xml b/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderValidation.xml deleted file mode 100644 index fd592ef33fe..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderValidation.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderWelcome.xml b/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderWelcome.xml deleted file mode 100644 index c0bf431301f..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/Page/DownloaderWelcome.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderPart2Test.php b/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderPart2Test.php deleted file mode 100644 index 9156d816ceb..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderPart2Test.php +++ /dev/null @@ -1,101 +0,0 @@ -downloaderDownloader = $downloaderDownloader; - } - - /** - * Install Magento via web interface. - * - * @param array $configData - * @return array - */ - public function test($configData) - { - // Steps: - $this->downloaderDownloader->open(); - // Start downloading - $this->downloaderDownloader->getContinueDownloadBlock()->startDownload(); - $i = 1; - while ($i <= 15 and (!(($this->downloaderDownloader->getMessagesBlock()->isVisibleMessage('success')) or - ($this->downloaderDownloader->getMessagesBlock()->isVisibleMessage('error')))) - ) { - sleep(60); - $i++; -// ObjectManager::getInstance()->create(EventManagerInterface::class)->dispatchEvent(array('exception')); - } - - $this->downloaderDownloader->getMessagesBlock()->getSuccessMessages(); - $this->downloaderDownloader->getContinueDownloadBlock()->continueMagentoInstallation(); - } -} diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderPart2Test.xml b/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderPart2Test.xml deleted file mode 100644 index e27bdf08401..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderPart2Test.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - Install with default values - Welcome to Magento Downloader! - test_type:install - - - diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderTest.php b/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderTest.php deleted file mode 100644 index b21ab810a7a..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderTest.php +++ /dev/null @@ -1,149 +0,0 @@ -downloaderWelcome = $downloaderWelcome; - $this->downloaderValidation = $downloaderValidation; - $this->downloaderDeploy = $downloaderDeploy; - $this->downloaderDownloader = $downloaderDownloader; - $this->assertSuccessDeploy = $assertSuccessDeploy; - $this->downloaderDeployEnd = $downloaderDeployEnd; - } - - /** - * Install Magento via web interface. - * - * @param AssertWelcomeWizardTextPresent $assertWelcomeWizardTextPresent - * @param array $configData - * @return array - */ - public function test(AssertWelcomeWizardTextPresent $assertWelcomeWizardTextPresent, $configData) - { - // Steps: - $this->downloaderWelcome->open(); - // Verify license agreement. - $assertWelcomeWizardTextPresent->processAssert($this->downloaderWelcome); - $this->downloaderWelcome->getContinueDownloadBlock()->continueValidation(); - $this->downloaderValidation->getContinueDownloadBlock()->continueDeploy(); - $this->downloaderDeploy->getContinueDownloadBlock()->continueDeploy(); - $this->assertSuccessDeploy->processAssert($this->downloaderDeployEnd); - $this->downloaderDeploy->getContinueDownloadBlock()->continueDownload(); - - } -} diff --git a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderTest.xml b/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderTest.xml deleted file mode 100644 index dd8049ef6e0..00000000000 --- a/dev/tests/functional/tests/app/Mage/Install/Test/TestCase/DownloaderTest.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - Install with default values - Welcome to Magento Downloader! - test_type:install - - - diff --git a/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/ce_download.xml b/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/ce_download.xml deleted file mode 100644 index cdcf2aa783a..00000000000 --- a/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/ce_download.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - diff --git a/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/ce_download2.xml b/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/ce_download2.xml deleted file mode 100644 index 1086c529b63..00000000000 --- a/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/ce_download2.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - diff --git a/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/upgradeconnectce.xml b/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/upgradeconnectce.xml deleted file mode 100644 index 4369452123e..00000000000 --- a/dev/tests/functional/testsuites/Magento/Mtf/TestSuite/InjectableTests/upgradeconnectce.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - diff --git a/downloader/.htaccess b/downloader/.htaccess deleted file mode 100644 index e8420e693bb..00000000000 --- a/downloader/.htaccess +++ /dev/null @@ -1,11 +0,0 @@ - - - RemoveOutputFilter DEFLATE - RemoveOutputFilter GZIP - - - - - order allow,deny - deny from all - \ No newline at end of file diff --git a/downloader/Maged/.htaccess b/downloader/Maged/.htaccess deleted file mode 100644 index 93169e4eb44..00000000000 --- a/downloader/Maged/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -Order deny,allow -Deny from all diff --git a/downloader/Maged/BruteForce/Validator.php b/downloader/Maged/BruteForce/Validator.php deleted file mode 100644 index a7e83aa4c01..00000000000 --- a/downloader/Maged/BruteForce/Validator.php +++ /dev/null @@ -1,148 +0,0 @@ -model = $model; - } - - /** - * @return bool - */ - public function isCanLogin() - { - $badAttempts = $this->getBadAttempts(); - $configAttemptsCount = $this->getConfigAttemptsCount(); - - if ($badAttempts >= $configAttemptsCount and $badAttempts % $configAttemptsCount === 0) { - $lastBadLogin = intval($this->model->get(self::MODEL_KEY_LAST_BAD_TIME)); - if ($lastBadLogin > 0) { - $timeDiff = $this->model->get(self::MODEL_KEY_DIFF_TIME_TO_ATTEMPT, self::DEFAULT_DIFF_TIME_TO_ATTEMPT); - $currentTime = time(); - $checkTime = $lastBadLogin + $timeDiff; - if ($checkTime > $currentTime) { - return false; - } - } - } - return true; - } - - /** - * @return int - */ - protected function getBadAttempts() - { - return (int)$this->model->get(self::MODEL_KEY_BAD_ATTEMPTS_COUNT, self::DEFAULT_BAD_ATTEMPTS_COUNT); - } - - /** - * @return int - */ - protected function getConfigAttemptsCount() - { - return (int)$this->model->get(self::MODEL_KEY_ATTEMPTS_COUNT, self::DEFAULT_ATTEMPTS_COUNT); - } - - /** - * @return int - */ - public function getTimeToAttempt() - { - return (int)$this->model->get(self::MODEL_KEY_DIFF_TIME_TO_ATTEMPT, self::DEFAULT_DIFF_TIME_TO_ATTEMPT); - } - - /** - * @return $this - */ - public function doGoodLogin() - { - $this->reset(); - return $this; - } - - /** - * @return void - */ - public function reset() - { - $this->model - ->set(self::MODEL_KEY_BAD_ATTEMPTS_COUNT, self::DEFAULT_BAD_ATTEMPTS_COUNT) - ->set(self::MODEL_KEY_DIFF_TIME_TO_ATTEMPT, self::DEFAULT_DIFF_TIME_TO_ATTEMPT) - ->delete(self::MODEL_KEY_LAST_BAD_TIME) - ->save(); - } - - /** - * @return $this - */ - public function doBadLogin() - { - $badAttempts = $this->getBadAttempts() + 1; - $configAttemptsCount = $this->getConfigAttemptsCount(); - $timeToNextLogin = $this->getDiffTimeToNextAttempt(); - - if ($badAttempts % $configAttemptsCount == 0 and $badAttempts != $configAttemptsCount) { - $timeToNextLogin += self::DEFAULT_DIFF_TIME_TO_ATTEMPT; - } - - $this->model - ->set(self::MODEL_KEY_BAD_ATTEMPTS_COUNT, $badAttempts) - ->set(self::MODEL_KEY_DIFF_TIME_TO_ATTEMPT, $timeToNextLogin) - ->set(self::MODEL_KEY_ATTEMPTS_COUNT, $configAttemptsCount) - ->set(self::MODEL_KEY_LAST_BAD_TIME, time()) - ->save(); - - return $this; - } - - /** - * @return int - */ - protected function getDiffTimeToNextAttempt() - { - return (int)$this->model->get(self::MODEL_KEY_DIFF_TIME_TO_ATTEMPT, self::DEFAULT_DIFF_TIME_TO_ATTEMPT); - } -} diff --git a/downloader/Maged/Connect.php b/downloader/Maged/Connect.php deleted file mode 100644 index 0beb9a8548a..00000000000 --- a/downloader/Maged/Connect.php +++ /dev/null @@ -1,519 +0,0 @@ -getConfig(); - $this->getSingleConfig(); - $this->getFrontend(); - } - - /** - * Destructor, sends Console footer if Console started - */ - public function __destruct() - { - if ($this->_consoleStarted) { - $this->_consoleFooter(); - } - } - - /** - * Initialize instance - * - * @return Maged_Connect - */ - public static function getInstance() - { - if (!self::$_instance) { - self::$_instance = new self; - } - return self::$_instance; - } - - /** - * Retrieve object of config and set it to Mage_Connect_Command - * - * @return Mage_Connect_Config - */ - public function getConfig() - { - if (!$this->_config) { - $this->_config = new Mage_Connect_Config(); - $ftp=$this->_config->__get('remote_config'); - if(!empty($ftp)){ - $packager = new Mage_Connect_Packager(); - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - $this->_config=$config; - $this->_sconfig=$cache; - } - $this->_config->magento_root = dirname(dirname(__FILE__)).DS.'..'; - Mage_Connect_Command::setConfigObject($this->_config); - } - return $this->_config; - } - - /** - * Retrieve object of single config and set it to Mage_Connect_Command - * - * @param bool $reload - * @return Mage_Connect_Singleconfig - */ - public function getSingleConfig($reload = false) - { - if(!$this->_sconfig || $reload) { - $this->_sconfig = new Mage_Connect_Singleconfig( - $this->getConfig()->magento_root . DIRECTORY_SEPARATOR - . $this->getConfig()->downloader_path . DIRECTORY_SEPARATOR - . Mage_Connect_Singleconfig::DEFAULT_SCONFIG_FILENAME - ); - } - Mage_Connect_Command::setSconfig($this->_sconfig); - return $this->_sconfig; - - } - - /** - * Retrieve object of frontend and set it to Mage_Connect_Command - * - * @return Maged_Connect_Frontend - */ - public function getFrontend() - { - if (!$this->_frontend) { - $this->_frontend = new Maged_Connect_Frontend(); - Mage_Connect_Command::setFrontendObject($this->_frontend); - } - return $this->_frontend; - } - - /** - * Retrieve lof from frontend - * - * @return array - */ - public function getLog() - { - return $this->getFrontend()->getLog(); - } - - /** - * Retrieve output from frontend - * - * @return array - */ - public function getOutput() - { - return $this->getFrontend()->getOutput(); - } - - /** - * Clean registry - * - * @return Maged_Connect - */ - public function cleanSconfig() - { - $this->getSingleConfig()->clear(); - return $this; - } - - /** - * Delete directory recursively - * - * @param string $path - * @return Maged_Connect - */ - public function delTree($path) { - if (@is_dir($path)) { - $entries = @scandir($path); - foreach ($entries as $entry) { - if ($entry != '.' && $entry != '..') { - $this->delTree($path.DS.$entry); - } - } - @rmdir($path); - } else { - @unlink($path); - } - return $this; - } - - /** - * Run commands from Mage_Connect_Command - * - * @param string $command - * @param array $options - * @param array $params - * @return boolean|Mage_Connect_Error - */ - public function run($command, $options=array(), $params=array()) - { - @set_time_limit(0); - @ini_set('memory_limit', '256M'); - - if (empty($this->_cmdCache[$command])) { - Mage_Connect_Command::getCommands(); - /** - * @var $cmd Mage_Connect_Command - */ - $cmd = Mage_Connect_Command::getInstance($command); - if ($cmd instanceof Mage_Connect_Error) { - return $cmd; - } - $this->_cmdCache[$command] = $cmd; - } else { - /** - * @var $cmd Mage_Connect_Command - */ - $cmd = $this->_cmdCache[$command]; - } - $ftp=$this->getConfig()->remote_config; - if(strlen($ftp)>0){ - $options=array_merge($options, array('ftp'=>$ftp)); - } - $cmd->run($command, $options, $params); - if ($cmd->ui()->hasErrors()) { - return false; - } else { - return true; - } - } - - /** - * Set remote Config by URI - * - * @param $uri - * @return Maged_Connect - */ - public function setRemoteConfig($uri) - { - $this->getConfig()->remote_config=$uri; - return $this; - } - - /** - * Show Errors - * - * @param array $errors Error messages - * @return Maged_Connect - */ - public function showConnectErrors($errors) - { - echo ''; - - return $this; - } - - /** - * Run Mage_Connect_Command with html output console style - * - * @throws Maged_Exception - * @param array|string|Maged_Model $runParams command, options, params, comment, success_callback, failure_callback - * @return bool|Mage_Connect_Error - */ - public function runHtmlConsole($runParams) - { - if (function_exists('apache_setenv')) { - apache_setenv('no-gzip', '1'); - } - @ini_set('zlib.output_compression', 0); - @ini_set('implicit_flush', 1); - for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); } - ob_implicit_flush(); - - $fe = $this->getFrontend(); - $oldLogStream = $fe->getLogStream(); - $fe->setLogStream('stdout'); - - if ($runParams instanceof Maged_Model) { - $run = $runParams; - } elseif (is_array($runParams)) { - $run = new Maged_Model_Connect_Request($runParams); - } elseif (is_string($runParams)) { - $run = new Maged_Model_Connect_Request(array('comment'=>$runParams)); - } else { - throw Maged_Exception("Invalid run parameters"); - } - - if (!$run->get('no-header')) { - $this->_consoleHeader(); - } - echo htmlspecialchars($run->get('comment')).'
    '; - - if ($command = $run->get('command')) { - $result = $this->run($command, $run->get('options'), $run->get('params')); - - if ($this->getFrontend()->hasErrors()) { - echo "
    CONNECT ERROR: "; - foreach ($this->getFrontend()->getErrors(false) as $error) { - echo nl2br($error[1]); - echo '
    '; - } - } - echo ''; - } else { - $result = false; - } - if ($this->getFrontend()->getErrors() || !$run->get('no-footer')) { - //$this->_consoleFooter(); - $fe->setLogStream($oldLogStream); - } - return $result; - } - - /** - * Show HTML Console Header - * - * @return void - */ - protected function _consoleHeader() { - if (!$this->_consoleStarted) { - $validateKey = md5(time()); - $sessionModel = new Maged_Model_Session(); - $sessionModel->set('validate_cache_key', $validateKey); ?> - - - - -_consoleStarted = true; - } - } - - /** - * Show HTML Console Footer - * - * @return void - */ - protected function _consoleFooter() { - if ($this->_consoleStarted) { -?> - - -_consoleStarted = false; - } - } -} diff --git a/downloader/Maged/Connect/Frontend.php b/downloader/Maged/Connect/Frontend.php deleted file mode 100644 index 6c230b1aa63..00000000000 --- a/downloader/Maged/Connect/Frontend.php +++ /dev/null @@ -1,152 +0,0 @@ -_logStream = $stream; - return $this; - } - - /** - * Retrieve log stream - * - * @return string - */ - public function getLogStream() - { - return $this->_logStream; - } - - /** - * Echo data from executed command - */ - public function output($data) - { - - $this->_out = $data; - - if ('stdout'===$this->_logStream) { - if (is_string($data)) { - echo $data."
    ".str_repeat(" ", 256); - } elseif (is_array($data)) { - $data = array_pop($data); - if (!empty($data['message']) && is_string($data['message'])) { - echo $data['message']."
    ".str_repeat(" ", 256); - } elseif (!empty($data['data'])) { - if (is_string($data['data'])) { - echo $data['data']."
    ".str_repeat(" ", 256); - } else { - if (isset($data['title'])) { - echo $data['title']."
    ".str_repeat(" ", 256); - } - if (is_array($data['data'])) { - foreach ($data['data'] as $row) { - foreach ($row as $msg) { - echo " ".$msg; - } - echo "
    ".str_repeat(" ", 256); - } - } else { - echo " ".$data['data']; - } - } - } - } else { - print_r($data); - } - } - } - - /** - * Method for ask client about rewrite all files. - * - * @param $string - */ - public function confirm($string) - { - $confirmString = htmlentities($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); - $formId = htmlspecialchars($_POST['form_id'], ENT_COMPAT | ENT_HTML401, 'UTF-8'); - - echo << -SCRIPT; - } - - /** - * Retrieve output cache - * - * @param bool $clearPrevious - * @return array|mixed - */ - public function getOutput($clearPrevious = false) - { - return $this->_out; - } - -} - diff --git a/downloader/Maged/Controller.php b/downloader/Maged/Controller.php deleted file mode 100644 index 35167184d85..00000000000 --- a/downloader/Maged/Controller.php +++ /dev/null @@ -1,1264 +0,0 @@ - 0) { - $post['ftp_path'] = '/' . trim($post['ftp_path'], '\\/') . '/'; - } else { - $post['ftp_path'] = '/'; - } - - $start = stripos($post['ftp_host'],'ftp://'); - if ($start !== false){ - $post['ftp_proto'] = 'ftp://'; - $post['ftp_host'] = substr($post['ftp_host'], $start + 6 - 1); - } - $start = stripos($post['ftp_host'],'ftps://'); - if ($start !== false) { - $post['ftp_proto'] = 'ftps://'; - $post['ftp_host'] = substr($post['ftp_host'], $start + 7 - 1); - } - - $post['ftp_host'] = trim($post['ftp_host'], '\\/'); - - if (!empty($post['ftp_login']) && !empty($post['ftp_password'])){ - $ftp = sprintf("%s%s:%s@%s%s", - $post['ftp_proto'], - $post['ftp_login'], - $post['ftp_password'], - $post['ftp_host'], - $post['ftp_path'] - ); - } elseif (!empty($post['ftp_login'])) { - $ftp = sprintf( - "%s%s@%s%s", - $post['ftp_proto'], - $post['ftp_login'], - $post['ftp_host'], - $post['ftp_path'] - ); - } else { - $ftp = $post['ftp_proto'] . $post['ftp_host'] . $post['ftp_path']; - } - - $_POST['ftp'] = $ftp; - return $ftp; - } - - /** - * NoRoute - */ - public function norouteAction() - { - header("HTTP/1.0 404 Invalid Action"); - echo $this->view()->template('noroute.phtml'); - } - - /** - * Login - */ - public function loginAction() - { - $this->view()->set('username', !empty($_GET['username']) ? $_GET['username'] : ''); - echo $this->view()->template('login.phtml'); - } - - /** - * Logout - */ - public function logoutAction() - { - $this->session()->logout(); - $this->redirect($this->url()); - } - - /** - * Index - */ - public function indexAction() - { - $config = $this->config(); - if (!$this->isInstalled()) { - $this->view()->set('mage_url', dirname(dirname($_SERVER['SCRIPT_NAME']))); - $this->view()->set( - 'use_custom_permissions_mode', - $config->__get('use_custom_permissions_mode') - ? $config->__get('use_custom_permissions_mode') - : '0' - ); - $this->view()->set('mkdir_mode', decoct($config->__get('global_dir_mode'))); - $this->view()->set('chmod_file_mode', decoct($config->__get('global_file_mode'))); - $this->view()->set('protocol', $config->__get('protocol')); - $this->channelConfig()->setInstallView($config,$this->view()); - - echo $this->view()->template('install/download.phtml'); - } elseif (!$config->sync_pear) { - $this->model('connect', true)->connect()->run('sync'); - $this->forward('connectPackages'); - } else { - $this->forward('connectPackages'); - } - } - - /** - * Empty Action - */ - public function emptyAction() - { - $this->model('connect', true) - ->connect() - ->runHtmlConsole('Please wait, preparing for updates...'); - } - - /** - * Install all magento - */ - public function connectInstallAllAction() - { - $p = &$_POST; - $this->getFtpPost($p); - $errors = $this->model('connect', true)->validateConfigPost($p); - /* todo show errors */ - if ($errors) { - $message = "CONNECT ERROR: "; - foreach ($errors as $err) { - $message .= $err . "\n"; - } - $this->model('connect', true)->connect()->runHtmlConsole($message); - $this->model('connect', true)->connect()->showConnectErrors($errors); - return; - } - - if( 1 == $p['inst_protocol']){ - $this->model('connect', true)->connect()->setRemoteConfig($this->getFtpPost($p)); - } - - $this->channelConfig()->setPostData($this->config(),$p); - - $chan = $this->config()->__get('root_channel'); - $this->model('connect', true)->saveConfigPost($_POST); - $this->channelConfig()->setSettingsSession($_POST, $this->session()); - $this->model('connect', true)->installAll(!empty($_GET['force']), $chan); - $p = null; - } - - /** - * Connect packages - */ - public function connectPackagesAction() - { - $connect = $this->model('connect', true); - - if (isset($_GET['loggedin'])) { - $connect->connect()->run('sync'); - } - - $this->view()->set('connect', $connect); - $this->view()->set('channel_config', $this->channelConfig()); - $remoteConfig = $this->config()->remote_config; - if (!$this->isWritable() && empty($remoteConfig)) { - $this->view()->set('writable_warning', true); - } - - echo $this->view()->template('connect/packages.phtml'); - } - - /** - * Connect packages POST - */ - public function connectPackagesPostAction() - { - if (!$this->_validateFormKey()) { - echo "INVALID POST DATA"; - return; - } - $actions = isset($_POST['actions']) ? $_POST['actions'] : array(); - if (isset($_POST['ignore_local_modification'])) { - $ignoreLocalModification = $_POST['ignore_local_modification']; - } else { - $ignoreLocalModification = ''; - } - $this->model('connect', true)->applyPackagesActions($actions, $ignoreLocalModification); - } - - /** - * Prepare package to install, get dependency info. - */ - public function connectPreparePackagePostAction() - { - if (!$this->_validateFormKey()) { - echo "INVALID POST DATA"; - return; - } - if (!$_POST) { - echo "INVALID POST DATA"; - return; - } - $prepareResult = $this->model('connect', true)->prepareToInstall($_POST['install_package_id']); - - $packages = isset($prepareResult['data']) ? $prepareResult['data'] : array(); - $errors = isset($prepareResult['errors']) ? $prepareResult['errors'] : array(); - - $this->view()->set('packages', $packages); - $this->view()->set('errors', $errors); - $this->view()->set('package_id', $_POST['install_package_id']); - - echo $this->view()->template('connect/packages_prepare.phtml'); - } - - /** - * Install package - */ - public function connectInstallPackagePostAction() - { - if (!$this->_validateFormKey()) { - echo "INVALID POST DATA"; - return; - } - if (!$_POST) { - echo "INVALID POST DATA"; - return; - } - $this->model('connect', true)->installPackage($_POST['install_package_id']); - } - - /** - * Install uploaded package - */ - public function connectInstallPackageUploadAction() - { - if (!$this->_validateFormKey()) { - echo "No file was uploaded"; - return; - } - - if (!$_FILES) { - echo "No file was uploaded"; - return; - } - - if(empty($_FILES['file'])) { - echo "No file was uploaded"; - return; - } - - $info =& $_FILES['file']; - - if(0 !== intval($info['error'])) { - echo "File upload problem"; - return; - } - - $target = $this->_mageDir . DS . "var/" . uniqid() . $info['name']; - $res = move_uploaded_file($info['tmp_name'], $target); - if(false === $res) { - echo "Error moving uploaded file"; - return; - } - - $this->model('connect', true)->installUploadedPackage($target); - @unlink($target); - } - - /** - * Clean cache on ajax request - */ - public function cleanCacheAction() - { - $result = $this->cleanCache(true); - echo json_encode($result); - } - - /** - * Settings - */ - public function settingsAction() - { - $config = $this->config(); - $this->view()->set('preferred_state', $config->__get('preferred_state')); - $this->view()->set('protocol', $config->__get('protocol')); - - $this->view()->set('use_custom_permissions_mode', $config->__get('use_custom_permissions_mode')); - $this->view()->set('mkdir_mode', decoct($config->__get('global_dir_mode'))); - $this->view()->set('chmod_file_mode', decoct($config->__get('global_file_mode'))); - - $this->channelConfig()->setSettingsView($this->session(), $this->view()); - - $fs_disabled =! $this->isWritable(); - $ftpParams = $config->__get('remote_config') ? @parse_url($config->__get('remote_config')) : ''; - - $this->view()->set('fs_disabled', $fs_disabled); - $this->view()->set('deployment_type', ($fs_disabled || !empty($ftpParams) ? 'ftp' : 'fs')); - - if (!empty($ftpParams)) { - $this->view()->set('ftp_host', sprintf("%s://%s", $ftpParams['scheme'], $ftpParams['host'])); - $this->view()->set('ftp_login', $ftpParams['user']); - $this->view()->set('ftp_password', $ftpParams['pass']); - $this->view()->set('ftp_path', $ftpParams['path']); - } - echo $this->view()->template('settings.phtml'); - } - - /** - * Settings post - */ - public function settingsPostAction() - { - if (!$this->_validateFormKey()) { - $this->session()->addMessage('error', "Unable to save settings"); - $this->redirect($this->url('settings')); - return; - } - if ($_POST) { - $ftp = $this->getFtpPost($_POST); - - /* clear startup messages */ - $this->config(); - $this->session()->getMessages(); - - $errors = $this->model('connect', true)->validateConfigPost($_POST); - if ($errors) { - foreach ($errors as $err) { - $this->session()->addMessage('error', $err); - } - $this->redirect($this->url('settings')); - return; - } - try { - if ('ftp' == $_POST['deployment_type'] && !empty($_POST['ftp_host'])) { - $this->model('connect', true)->connect()->setRemoteConfig($ftp); - } else { - $this->model('connect', true)->connect()->setRemoteConfig(''); - $_POST['ftp'] = ''; - } - $this->channelConfig()->setPostData($this->config(), $_POST); - $this->model('connect', true)->saveConfigPost($_POST); - $this->channelConfig()->setSettingsSession($_POST, $this->session()); - $this->model('connect', true)->connect()->run('sync'); - } catch (Exception $e) { - $this->session()->addMessage('error', "Unable to save settings: " . $e->getMessage()); - } - } - $this->redirect($this->url('settings')); - } - - //////////////////////////// ABSTRACT - - /** - * Constructor - */ - public function __construct() - { - $this->_rootDir = dirname(dirname(__FILE__)); - $this->_mageDir = dirname($this->_rootDir); - } - - /** - * Run - */ - public static function run() - { - try { - self::singleton()->dispatch(); - } catch (Exception $e) { - echo $e->getMessage(); - } - } - - /** - * Initialize object of class - * - * @return Maged_Controller - */ - public static function singleton() - { - if (!self::$_instance) { - self::$_instance = new self; - - if (self::$_instance->isDownloaded() && self::$_instance->isInstalled()) { - Mage::app('', 'store', array('global_ban_use_cache'=>true)); - Mage::getSingleton('adminhtml/url')->turnOffSecretKey(); - } - } - return self::$_instance; - } - - /** - * Retrieve Downloader root dir - * - * @return string - */ - public function getRootDir() - { - return $this->_rootDir; - } - - /** - * Retrieve Magento root dir - * - * @return string - */ - public function getMageDir() - { - return $this->_mageDir; - } - - /** - * Retrieve Mage Class file path - * - * @return string - */ - public function getMageFilename() - { - $ds = DIRECTORY_SEPARATOR; - return $this->getMageDir() . $ds . 'app' . $ds . 'Mage.php'; - } - - /** - * Retrieve path for Varien_Profiler - * - * @return string - */ - public function getVarFilename() - { - $ds = DIRECTORY_SEPARATOR; - return $this->getMageDir() . $ds . 'lib' . $ds . 'Varien' . $ds . 'Profiler.php'; - } - - /** - * Retrieve downloader file path - * - * @param string $name - * @return string - */ - public function filepath($name = '') - { - $ds = DIRECTORY_SEPARATOR; - return rtrim($this->getRootDir() . $ds . str_replace('/', $ds, $name), $ds); - } - - /** - * Retrieve object of view - * - * @return Maged_View - */ - public function view() - { - if (!$this->_view) { - $this->_view = new Maged_View; - } - return $this->_view; - } - - /** - * Retrieve object of model - * - * @param string $model - * @param boolean $singleton - * @return Maged_Model - */ - public function model($model = null, $singleton = false) - { - if ($singleton && isset($this->_singletons[$model])) { - return $this->_singletons[$model]; - } - - if (is_null($model)) { - $class = 'Maged_Model'; - } else { - $class = 'Maged_Model_' . str_replace(' ', '_', ucwords(str_replace('_', ' ', $model))); - if (!class_exists($class, false)) { - include_once str_replace('_', DIRECTORY_SEPARATOR, $class).'.php'; - } - } - - $object = new $class(); - - if ($singleton) { - $this->_singletons[$model] = $object; - } - - return $object; - } - - /** - * Retrieve object of config - * - * @return Mage_Connect_Config - */ - public function config() - { - if (!$this->_config) { - $this->_config = $this->model('connect', true)->connect()->getConfig(); - if (!$this->_config->isLoaded()) { - $this->session()->addMessage('error', "Settings has not been loaded. Used default settings"); - if ($this->_config->getError()) { - $this->session()->addMessage('error', $this->_config->getError()); - } - } - } - return $this->_config; - } - - /** - * Retrieve object of channel config - * - * @return Maged_Model_Config_Interface - */ - public function channelConfig() - { - if (!$this->_localConfig) { - $this->_localConfig = $this->model('config', true)->getChannelConfig(); - } - return $this->_localConfig; - } - - /** - * Retrieve object of session - * - * @return Maged_Model_Session - */ - public function session() - { - if (!$this->_session) { - $this->_session = $this->model('session')->start(); - } - return $this->_session; - } - - /** - * Set Controller action - * - * @param string $action - * @return Maged_Controller - */ - public function setAction($action=null) - { - if (is_null($action)) { - if (!empty($this->_action)) { - return $this; - } - $action = !empty($_GET[self::ACTION_KEY]) ? $_GET[self::ACTION_KEY] : 'index'; - } - if (empty($action) || !is_string($action) || !method_exists($this, $this->getActionMethod($action))) { - //$action = 'noroute'; - $action = 'index'; - } - $this->_action = $action; - return $this; - } - - /** - * Retrieve Controller action name - * - * @return string - */ - public function getAction() - { - return $this->_action; - } - - /** - * Set Redirect to URL - * - * @param string $url - * @param bool $force - * @return Maged_Controller - */ - public function redirect($url, $force = false) - { - $this->_redirectUrl = $url; - if ($force) { - $this->processRedirect(); - } - return $this; - } - - /** - * Precess redirect - * - * @return Maged_Controller - */ - public function processRedirect() - { - if ($this->_redirectUrl) { - if (headers_sent()) { - echo ''; - exit; - } else { - header("Location: " . $this->_redirectUrl); - exit; - } - } - return $this; - } - - /** - * Forward to action - * - * @param string $action - * @return Maged_Controller - */ - public function forward($action) - { - $this->setAction($action); - $this->_isDispatched = false; - return $this; - } - - /** - * Retrieve action method by action name - * - * @param string $action - * @return string - */ - public function getActionMethod($action = null) - { - $method = (!is_null($action) ? $action : $this->_action) . 'Action'; - return $method; - } - - /** - * Generate URL for action - * - * @param string $action - * @param array $params - */ - public function url($action = '', $params = array()) - { - $args = array(); - foreach ($params as $k => $v) { - $args[] = sprintf('%s=%s', rawurlencode($k), rawurlencode($v)); - } - $args = $args ? join('&', $args) : ''; - - return sprintf('%s?%s=%s%s', $_SERVER['SCRIPT_NAME'], self::ACTION_KEY, rawurlencode($action), $args); - } - - /** - * Add domain policy header according to admin area settings - */ - protected function _addDomainPolicyHeader() - { - if ($this->isInstalled()) { - /** @var Mage_Core_Model_Domainpolicy $domainPolicy */ - $domainPolicy = Mage::getModel('core/domainpolicy'); - if ($domainPolicy) { - $policy = $domainPolicy->getBackendPolicy(); - if ($policy) { - header('X-Frame-Options: ' . $policy); - } - } - } - } - - /** - * Dispatch process - */ - public function dispatch() - { - if (class_exists('Mage')) { - if (Mage::getConfig() == null) { - Mage::init(); - } - $baseUrl = Mage::getBaseUrl( - Mage_Core_Model_Store::URL_TYPE_LINK, Mage::getSingleton('adminhtml/url')->getSecure() - ); - if (strpos($baseUrl, 'https') === 0) { - $request = Mage::app()->getRequest(); - if (!$request->isSecure()) { - Mage::app()->getFrontController()->getResponse() - ->setRedirect(rtrim($baseUrl, '/') . $request->getRequestUri(), 301)->sendResponse(); - exit; - } - } - } - - header('Content-type: text/html; charset=UTF-8'); - - $this->_addDomainPolicyHeader(); - - $this->setAction(); - - if (!$this->isInstalled()) { - if (!in_array($this->getAction(), array('index', 'connectInstallAll', 'empty', 'cleanCache'))) { - $this->setAction('index'); - } - } else { - try { - /** @var Maged_BruteForce_Validator $bruteForce */ - $bruteForce = $this->createBruteForceValidator(); - if ($bruteForce->isCanLogin()) { - $this->session()->authenticate($bruteForce); - } else { - throw new Exception ("Access is locked. Please try again in a few minutes."); - } - } catch (Exception $e) { - $this->session()->addMessage("error", $e->getMessage()); - $this->setAction("login"); - } - } - - while (!$this->_isDispatched) { - $this->_isDispatched = true; - - $method = $this->getActionMethod(); - $this->$method(); - } - - $this->processRedirect(); - } - - /** - * Check root dir is writable - * - * @return bool - */ - public function isWritable() - { - if (is_null($this->_writable)) { - $this->_writable = is_writable($this->getMageDir() . DIRECTORY_SEPARATOR) - && is_writable($this->filepath()) - && (!file_exists($this->filepath('config.ini') || is_writable($this->filepath('config.ini')))); - } - return $this->_writable; - } - - /** - * Check is Magento files downloaded - * - * @return bool - */ - public function isDownloaded() - { - return file_exists($this->getMageFilename()) && file_exists($this->getVarFilename()); - } - - /** - * Check is Magento installed - * - * @return bool - */ - public function isInstalled() - { - if (!$this->isDownloaded()) { - return false; - } - if (!class_exists('Mage', false)) { - if (!file_exists($this->getMageFilename())) { - return false; - } - include_once $this->getMageFilename(); - Mage::setIsDownloader(); - } - return Mage::isInstalled(); - } - - /** - * Retrieve Maintenance flag - * - * @return bool - */ - protected function _getMaintenanceFlag() - { - if (is_null($this->_maintenance)) { - $this->_maintenance = !empty($_REQUEST['maintenance']) && $_REQUEST['maintenance'] == '1' ? true : false; - } - return $this->_maintenance; - } - - /** - * Retrieve Maintenance Flag file path - * - * @return string - */ - protected function _getMaintenanceFilePath() - { - if (is_null($this->_maintenanceFile)) { - $path = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR; - $this->_maintenanceFile = $path . 'maintenance.flag'; - } - return $this->_maintenanceFile; - } - - /** - * Begin install package(s) - */ - public function startInstall() - { - if ($this->_getMaintenanceFlag()) { - $maintenance_filename='maintenance.flag'; - $config = $this->config(); - if (!$this->isWritable() || strlen($config->__get('remote_config')) > 0) { - $ftpObj = new Mage_Connect_Ftp(); - $ftpObj->connect($config->__get('remote_config')); - $tempFile = tempnam(sys_get_temp_dir(),'maintenance'); - @file_put_contents($tempFile, 'maintenance'); - $ftpObj->upload($maintenance_filename, $tempFile); - $ftpObj->close(); - } else { - @file_put_contents($this->_getMaintenanceFilePath(), 'maintenance'); - } - } - - if (!empty($_GET['archive_type'])) { - - $backupName = $_GET['backup_name']; - $connect = $this->model('connect', true)->connect(); - $isSuccess = true; - - if (!preg_match('/^[a-zA-Z0-9\ ]{0,50}$/', $backupName)) { - $connect->runHtmlConsole('Please use only letters (a-z or A-Z), numbers (0-9) or space in ' - . 'Backup Name field. Other characters are not allowed.'); - $isSuccess = false; - } - - if ($isSuccess) { - $isSuccess = $this->_createBackup($_GET['archive_type'], $_GET['backup_name']); - } - - if (!$isSuccess) { - $this->endInstall(); - $this->cleanCache(); - throw new Mage_Exception( - 'The installation process has been canceled because of the backup creation error' - ); - } - } - } - - /** - * End install package(s) - */ - public function endInstall() - { - //$connect - /** @var $connect Maged_Model_Connect */ - $frontend = $this->model('connect', true)->connect()->getFrontend(); - if (!($frontend instanceof Maged_Connect_Frontend)) { - $this->cleanCache(); - } - } - - /** - * Clean cache - * - * @param bool $validate - * @return array - */ - protected function cleanCache($validate = false) - { - $result = true; - $message = ''; - try { - if ($this->isInstalled()) { - if ($validate) { - $result = $this->session()->validateCleanCacheKey(); - } - if ($result) { - if (!empty($_REQUEST['clean_sessions'])) { - Mage::app()->cleanAllSessions(); - $message .= 'Session cleaned successfully. '; - } - Mage::app()->cleanCache(); - - // reinit config and apply all updates - Mage::app()->getConfig()->reinit(); - Mage_Core_Model_Resource_Setup::applyAllUpdates(); - Mage_Core_Model_Resource_Setup::applyAllDataUpdates(); - $message .= 'Cache cleaned successfully'; - } else { - $message .= 'Validation failed'; - } - } - } catch (Exception $e) { - $result = false; - $message = "Exception during cache and session cleaning: ".$e->getMessage(); - $this->session()->addMessage('error', $message); - } - - if ($result && $this->_getMaintenanceFlag()) { - $maintenance_filename='maintenance.flag'; - $config = $this->config(); - if (!$this->isWritable() && strlen($config->__get('remote_config')) > 0) { - $ftpObj = new Mage_Connect_Ftp(); - $ftpObj->connect($config->__get('remote_config')); - $ftpObj->delete($maintenance_filename); - $ftpObj->close(); - } else { - @unlink($this->_getMaintenanceFilePath()); - } - } - return array('result' => $result, 'message' => $message); - } - - /** - * Gets the current Magento Connect Manager (Downloader) version string - * @link http://www.magentocommerce.com/blog/new-community-edition-release-process/ - * - * @return string - */ - public static function getVersion() - { - $i = self::getVersionInfo(); - return trim( - "{$i['major']}.{$i['minor']}.{$i['revision']}" - . ($i['patch'] != '' ? ".{$i['patch']}" : "") - . "-{$i['stability']}{$i['number']}", - '.-' - ); - } - - /** - * Gets the detailed Magento Connect Manager (Downloader) version information - * @link http://www.magentocommerce.com/blog/new-community-edition-release-process/ - * - * @return array - */ - public static function getVersionInfo() - { - return array( - 'major' => '1', - 'minor' => '9', - 'revision' => '4', - 'patch' => '5', - 'stability' => '', - 'number' => '', - ); - } - - /** - * Create Backup - * - * @param string $archiveType - * @param string $archiveName - * @return bool - */ - protected function _createBackup($archiveType, $archiveName){ - /** @var $connect Maged_Connect */ - $connect = $this->model('connect', true)->connect(); - $connect->runHtmlConsole('Creating backup...'); - - $isSuccess = false; - - try { - $type = $this->_getBackupTypeByCode($archiveType); - - $backupManager = Mage_Backup::getBackupInstance($type) - ->setBackupExtension(Mage::helper('backup')->getExtensionByType($type)) - ->setTime(time()) - ->setName($archiveName) - ->setBackupsDir(Mage::helper('backup')->getBackupsDir()); - - Mage::register('backup_manager', $backupManager); - - if ($type != Mage_Backup_Helper_Data::TYPE_DB) { - $backupManager->setRootDir(Mage::getBaseDir()) - ->addIgnorePaths(Mage::helper('backup')->getBackupIgnorePaths()); - } - $backupManager->create(); - $connect->runHtmlConsole( - $this->_getCreateBackupSuccessMessageByType($type) - ); - $isSuccess = true; - } catch (Mage_Backup_Exception_NotEnoughFreeSpace $e) { - $connect->runHtmlConsole('Not enough free space to create backup.'); - Mage::logException($e); - } catch (Mage_Backup_Exception_NotEnoughPermissions $e) { - $connect->runHtmlConsole('Not enough permissions to create backup.'); - Mage::logException($e); - } catch (Exception $e) { - $connect->runHtmlConsole('An error occurred while creating the backup.'); - Mage::logException($e); - } - - return $isSuccess; - } - - /** - * Retrieve Backup Type by Code - * - * @param int $code - * @return string - */ - protected function _getBackupTypeByCode($code) - { - $typeMap = array( - 1 => Mage_Backup_Helper_Data::TYPE_DB, - 2 => Mage_Backup_Helper_Data::TYPE_SYSTEM_SNAPSHOT, - 3 => Mage_Backup_Helper_Data::TYPE_SNAPSHOT_WITHOUT_MEDIA, - 4 => Mage_Backup_Helper_Data::TYPE_MEDIA - ); - - if (!isset($typeMap[$code])) { - Mage::throwException('Unknown backup type'); - } - - return $typeMap[$code]; - } - - /** - * Get backup create success message by backup type - * - * @param string $type - * @return string - */ - protected function _getCreateBackupSuccessMessageByType($type) - { - $messagesMap = array( - Mage_Backup_Helper_Data::TYPE_SYSTEM_SNAPSHOT => 'System backup has been created', - Mage_Backup_Helper_Data::TYPE_SNAPSHOT_WITHOUT_MEDIA => 'System (excluding Media) backup has been created', - Mage_Backup_Helper_Data::TYPE_MEDIA => 'Database and media backup has been created', - Mage_Backup_Helper_Data::TYPE_DB => 'Database backup has been created' - ); - - if (!isset($messagesMap[$type])) { - return ''; - } - - return $messagesMap[$type]; - } - - /** - * Validate Form Key - * - * @return bool - */ - protected function _validateFormKey() - { - return $this->session()->validateFormKey(); - } - - /** - * Retrieve Session Form Key - * - * @return string - */ - public function getFormKey() - { - return $this->session()->getFormKey(); - } - - /** - * @return Maged_BruteForce_Validator - * @throws Exception - */ - protected function createBruteForceValidator() - { - $isRemote = (strlen($this->config()->remote_config) > 0); - $localFileName = ($isRemote) ? "brute-force.tmp.ini" : self::BRUTE_FORCE_CONFIG_NAME; - $localFile = $this->getBruteForceLocalFile($localFileName); - - if (!is_file($localFile)) { - $this->createBruteForceTemporaryFile($localFile, $this->getBruteForceLocalDirectory()); - } - if (!is_writable($localFile)) { - throw new Exception("Unable to write to the configuration file."); - } - if ($isRemote) { - $resource = new Maged_Model_BruteForce_Resource_FTP($this->config()->remote_config, $localFile, self::DOWNLOADER_DIRECTORY . DIRECTORY_SEPARATOR . self::BRUTE_FORCE_CONFIG_NAME); - } else { - $resource = new Maged_Model_BruteForce_Resource_File($localFile, self::DOWNLOADER_DIRECTORY . DIRECTORY_SEPARATOR . self::BRUTE_FORCE_CONFIG_NAME); - } - return new Maged_BruteForce_Validator(new Maged_Model_BruteForce_ConfigIni($resource)); - } - - /** - * @param string $fileName - * @return false |string - */ - protected function getBruteForceLocalFile($fileName) - { - $varFolder = $this->getBruteForceLocalDirectory(); - return rtrim($varFolder . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $fileName), DIRECTORY_SEPARATOR); - } - - /** - * @param string $localBruteForceConfigFile - * @param string $folder - * @throws Exception - */ - protected function createBruteForceTemporaryFile($localBruteForceConfigFile, $folder) - { - $error = false; - if (!is_dir($folder)) { - if (false === mkdir($folder)) { - $error = true; - }; - } - $fp = fopen($localBruteForceConfigFile, "w"); - if ($fp !== false) { - fclose($fp); - } else { - $error = true; - } - - if ($error) { - throw new Exception("Unable to create a temporary file. Please add write permission to the var/ folder."); - } - } - - /** - * @return string - */ - protected function getBruteForceLocalDirectory() - { - return $this->getMageDir() . DIRECTORY_SEPARATOR . "var" . DIRECTORY_SEPARATOR; - } -} diff --git a/downloader/Maged/Exception.php b/downloader/Maged/Exception.php deleted file mode 100644 index effa1063944..00000000000 --- a/downloader/Maged/Exception.php +++ /dev/null @@ -1,37 +0,0 @@ -_data = $args[0]; - - $this->_construct(); - } - - /** - * Constructor for covering - */ - protected function _construct() - { - - } - - /** - * Retrieve controller - * @return Maged_Controller - */ - public function controller() - { - return Maged_Controller::singleton(); - } - - /** - * Set value for key - * - * @param string $key - * @param mixed $value - * @return Maged_Model - */ - public function set($key, $value) - { - $this->_data[$key] = $value; - return $this; - } - - /** - * Get value by key - * - * @param string $key - * @return mixed - */ - public function get($key) - { - return isset($this->_data[$key]) ? $this->_data[$key] : null; - } -} diff --git a/downloader/Maged/Model/BruteForce/ConfigIni.php b/downloader/Maged/Model/BruteForce/ConfigIni.php deleted file mode 100644 index b010cceb975..00000000000 --- a/downloader/Maged/Model/BruteForce/ConfigIni.php +++ /dev/null @@ -1,115 +0,0 @@ -isReadable()) { - $this->resource = $resource; - $this->readConfig(); - } else { - throw new Exception("Unable to read the configuration file."); - } - } - - /** - * @throws Exception - */ - public function readConfig() - { - if (false === $data = parse_ini_string($this->resource->read())) { - throw new Exception("Incorrect configuration file."); - } - $this->data = $data; - } - - /** - * @param string $name - * @param null $defaultValue - * @return mixed|null - */ - public function get($name, $defaultValue = null) - { - return (isset($this->data[$name]) ? $this->data[$name] : $defaultValue); - } - - /** - * @param string $name - * @param mixed $value - * @return $this - * @throws Exception - */ - public function set($name, $value) - { - if (is_array($value) or is_object($value)) { - throw new Exception ("Bad value type."); - } - $this->data[$name] = $value; - return $this; - } - - public function save() - { - if ($this->resource->isWritable()) { - $res = array(); - foreach ($this->data as $key => $value) { - $res[] = "$key = " . (is_numeric($value) ? $value : '"' . $value . '"'); - } - $content = implode("\n", $res); - $this->resource->write($content); - } else { - throw new Exception("Unable to write to the configuration file."); - } - } - - /** - * @param string $name - * @return $this - */ - public function delete($name) - { - if (isset($this->data[$name])) { - unset($this->data[$name]); - } - return $this; - } - -} diff --git a/downloader/Maged/Model/BruteForce/ModelConfigInterface.php b/downloader/Maged/Model/BruteForce/ModelConfigInterface.php deleted file mode 100644 index bfcdedb0faf..00000000000 --- a/downloader/Maged/Model/BruteForce/ModelConfigInterface.php +++ /dev/null @@ -1,55 +0,0 @@ -connectionString = $connectionString; - $this->ftp = new Mage_Connect_Ftp(); - $this->localFilePath = $localFilePath; - $this->remoteFilePath = $remoteFileName; - - $this->ftp->connect($this->connectionString); - } - - /** - * @return string - */ - public function read() - { - if ($this->isReadable()) { - return file_get_contents($this->localFilePath); - } - return false; - } - - /** - * @return boolean - */ - public function isReadable() - { - return ($this->ftp->get($this->localFilePath, $this->remoteFilePath) === true); - } - - public function __destruct() - { - unlink($this->localFilePath); - $this->ftp->close(); - } - - /** - * @param string $content - * @return boolean - */ - public function write($content) - { - if ($this->isWritable()) { - file_put_contents($this->localFilePath, $content); - return $this->ftp->upload( - $this->remoteFilePath, - $this->localFilePath - ); - } - return false; - } - - /** - * @return string - */ - public function isWritable() - { - return ($this->isReadable()); - } - - /** - * @return string - */ - public function getResourcePath() - { - return $this->remoteFilePath; - } -} diff --git a/downloader/Maged/Model/BruteForce/Resource/File.php b/downloader/Maged/Model/BruteForce/Resource/File.php deleted file mode 100644 index 1fc79f7aa83..00000000000 --- a/downloader/Maged/Model/BruteForce/Resource/File.php +++ /dev/null @@ -1,91 +0,0 @@ -filePath = $filePath; - $this->displayFileName = $displayFileName; - } - - /** - * @return string - */ - public function read() - { - if ($this->isReadable()) { - return file_get_contents($this->filePath); - } - return false; - } - - /** - * @return boolean - */ - public function isReadable() - { - return (is_file($this->filePath) and is_readable($this->filePath)); - } - - /** - * @param string $content - * @return boolean - */ - public function write($content) - { - if ($this->isWritable()) { - return (boolean)file_put_contents($this->filePath, $content); - } - return false; - } - - /** - * @return string - */ - public function isWritable() - { - return (is_file($this->filePath) and is_writable($this->filePath)); - } - - /** - * @return string - */ - public function getResourcePath() - { - return $this->displayFileName; - } -} diff --git a/downloader/Maged/Model/BruteForce/Resource/ResourceInterface.php b/downloader/Maged/Model/BruteForce/Resource/ResourceInterface.php deleted file mode 100644 index 01694a02802..00000000000 --- a/downloader/Maged/Model/BruteForce/Resource/ResourceInterface.php +++ /dev/null @@ -1,54 +0,0 @@ -load(); - $channel = trim($this->get('root_channel')); - if (!empty($channel)) { - try { - return $this->controller()->model('config_'.$channel, true); - } catch (Exception $e) { - throw new Exception('Not valid config.ini file.'); - } - } else { - throw new Exception('Not valid config.ini file.'); - } - } - - /** - * Save post data to config - * - * @param array $p - * @return Maged_Model_Config - */ - public function saveConfigPost($p) - { - $configParams = array( - 'protocol', - 'preferred_state', - 'use_custom_permissions_mode', - 'mkdir_mode', - 'chmod_file_mode', - 'magento_root', - 'downloader_path', - 'root_channel_uri', - 'root_channel', - 'ftp', - ); - foreach ($configParams as $paramName){ - if (isset($p[$paramName])) { - $this->set($paramName, $p[$paramName]); - } - } - $this->save(); - return $this; - } -} diff --git a/downloader/Maged/Model/Config/Abstract.php b/downloader/Maged/Model/Config/Abstract.php deleted file mode 100644 index e15036aaadb..00000000000 --- a/downloader/Maged/Model/Config/Abstract.php +++ /dev/null @@ -1,134 +0,0 @@ -controller()->filepath('config.ini'); - } - - /** - * Load file - * - * @return Maged_Model_Config - */ - public function load() - { - if (!file_exists($this->getFilename())) { - return $this; - } - $rows = file($this->getFilename()); - if (!$rows) { - return $this; - } - foreach ($rows as $row) { - $arr = explode('=', $row, 2); - if (count($arr)!==2) { - continue; - } - $key = trim($arr[0]); - $value = trim($arr[1], " \t\"'\n\r"); - if (!$key || $key[0]=='#' || $key[0]==';') { - continue; - } - $this->set($key, $value); - } - return $this; - } - - /** - * Save file - * - * @return Maged_Model_Config - */ - public function save() - { - if ((!is_writable($this->getFilename())&&is_file($this->getFilename()))||(dirname($this->getFilename())!=''&&!is_writable(dirname($this->getFilename())))) { - if(isset($this->_data['ftp'])&&!empty($this->_data['ftp'])&&strlen($this->get('downloader_path'))>0){ - $confFile=$this->get('downloader_path').DIRECTORY_SEPARATOR.basename($this->getFilename()); - $ftpObj = new Mage_Connect_Ftp(); - $ftpObj->connect($this->_data['ftp']); - $tempFile = tempnam(sys_get_temp_dir(),'configini'); - $fp = fopen($tempFile, 'w'); - foreach ($this->_data as $k=>$v) { - fwrite($fp, $k.'='.$v."\n"); - } - fclose($fp); - $ret=$ftpObj->upload($confFile, $tempFile); - $ftpObj->close(); - }else{ - /* @TODO: show Warning message*/ - $this->controller()->session() - ->addMessage('warning', 'Invalid file permissions, could not save configuration.'); - return $this; - } - /**/ - }else{ - $fp = fopen($this->getFilename(), 'w'); - foreach ($this->_data as $k=>$v) { - fwrite($fp, $k.'='.$v."\n"); - } - fclose($fp); - } - return $this; - } - - /** - * Return channel label for channel name - * - * @param string $channel - * @return string - */ - public function getChannelLabel($channel) - { - $channelLabel = ''; - switch($channel) - { - case 'community': - $channelLabel = 'Magento Community Edition'; - break; - default: - $channelLabel = $channel; - break; - } - return $channelLabel; - } -} -?> diff --git a/downloader/Maged/Model/Config/Community.php b/downloader/Maged/Model/Config/Community.php deleted file mode 100644 index 27482dcb3cb..00000000000 --- a/downloader/Maged/Model/Config/Community.php +++ /dev/null @@ -1,112 +0,0 @@ -load(); - } - - /** - * Set data for Settings View - * - * @param Mage_Connect_Config $config - * @param Maged_View $view - * @return null - */ - public function setInstallView($config, $view) - { - $view->set('channel_logo', 'logo'); - } - - /** - * Set data for Settings View - * @param Mage_Connect_Config $config - * @param Maged_View $view - * @return null - */ - public function setSettingsView($config, $view) - { - } - - /** - * Set session data for Settings - * @param array $post post data - * @param mixed $session Session object - * @return null - */ - public function setSettingsSession($post, $session) - { - } - - /** - * Get root channel URI - * - * @return string Root channel URI - */ - public function getRootChannelUri(){ - if (!$this->get('root_channel_uri')) { - $this->set('root_channel_uri', 'connect20.magentocommerce.com/community'); - } - return $this->get('root_channel_uri'); - } - - /** - * Set config data from POST - * - * @param Mage_Connect_Config $config Config object - * @param array $post post data - * @return null - */ - public function setPostData($config, &$post) - { - } - - /** - * Set additional command options - * - * @param mixed $session Session object - * @param array $options - * @return null - */ - public function setCommandOptions($session, &$options) - { - } -} -?> diff --git a/downloader/Maged/Model/Config/Interface.php b/downloader/Maged/Model/Config/Interface.php deleted file mode 100644 index 3f0123ad829..00000000000 --- a/downloader/Maged/Model/Config/Interface.php +++ /dev/null @@ -1,90 +0,0 @@ - diff --git a/downloader/Maged/Model/Connect.php b/downloader/Maged/Model/Connect.php deleted file mode 100644 index 8839430969a..00000000000 --- a/downloader/Maged/Model/Connect.php +++ /dev/null @@ -1,497 +0,0 @@ -true); - if ($force) { - $this->connect()->cleanSconfig(); - $options['force'] = 1; - } - $packages = array( - 'Mage_All_Latest', - ); - $connectConfig = $this->connect()->getConfig(); - $ftp = $connectConfig->remote_config; - if (!empty($ftp)) { - $options['ftp'] = $ftp; - } - $params = array(); - - $uri = $this->controller()->channelConfig()->getRootChannelUri(); - - $this->controller()->channelConfig()->setCommandOptions($this->controller()->session(), $options); - - $connectConfig->root_channel = $chanName; - foreach ($packages as $package) { - $params[] = $uri; - $params[] = $package; - } - $this->connect()->runHtmlConsole(array('command'=>'install', 'options'=>$options, 'params'=>$params)); - } - - /** - * Prepare to install package - * - * @param string $id - * @return array - */ - public function prepareToInstall($id) - { - $match = array(); - if (!$this->checkExtensionKey($id, $match)) { - $errorMessage[] = sprintf('Invalid package identifier provided: %s', $id); - $packages = array( - 'errors' => array('error'=> $errorMessage) - ); - return $packages; - } - - $channel = $match[1]; - $package = $match[2]; - $version = (!empty($match[3]) ? trim($match[3],'/\-') : ''); - - $connect = $this->connect(); - $sconfig = $connect->getSingleConfig(); - - $options = array(); - $params = array($channel, $package, $version, $version); - $this->controller()->channelConfig()->setCommandOptions($this->controller()->session(), $options); - - $connect->run('package-prepare', $options, $params); - $output = $connect->getOutput(); - $errors = $connect->getFrontend()->getErrors(); - $package_error = array(); - foreach ($errors as $error){ - if (isset($error[1])){ - $package_error[] = $error[1]; - } - } - - $packages = array(); - if (is_array($output) && isset($output['package-prepare'])){ - $packages = array_merge($output['package-prepare'], array('errors'=>array('error'=>$package_error))); - } elseif (is_array($output) && !empty($package_error)) { - $packages = array('errors'=>array('error'=>$package_error)); - } - return $packages; - } - - - /** - * Retrieve all installed packages - * - * @return array - */ - public function getAllInstalledPackages() - { - $connect = $this->connect(); - $sconfig = $connect->getSingleConfig(true); - $connect->run('list-installed'); - $output = $connect->getOutput(); - $packages = array(); - if (is_array($output) && isset($output['list-installed']['data'])){ - $packages = $output['list-installed']['data']; - } else { - - } - foreach ($packages as $channel=>$package) { - foreach ($package as $name=>$data) { - $summary = $sconfig->getPackageObject($channel, $name)->getSummary(); - $addition = array('summary'=>$summary, 'upgrade_versions'=>array(), 'upgrade_latest'=>''); - $packages[$channel][$name] = array_merge($data, $addition); - } - } - - if (!empty($_GET['updates'])) { - $options = array(); - $this->controller()->channelConfig()->setCommandOptions($this->controller()->session(), $options); - $result = $connect->run('list-upgrades', $options); - $output = $connect->getOutput(); - if (is_array($output)) { - $channelData = $output; - if (!empty($channelData['list-upgrades']['data']) && is_array($channelData['list-upgrades']['data'])) { - foreach ($channelData['list-upgrades']['data'] as $channel=>$package) { - foreach ($package as $name=>$data) { - if (!isset($packages[$channel][$name])) { - continue; - } - $packages[$channel][$name]['upgrade_latest'] = $data['to'].' ('.$data['from'].')'; - } - } - } - } - } - - $states = array('snapshot'=>0, 'devel'=>1, 'alpha'=>2, 'beta'=>3, 'stable'=>4); - $preferredState = $states[$this->getPreferredState()]; - - foreach ($packages as $channel=>&$package) { - foreach ($package as $name=>&$data) { - $actions = array(); - $systemPkg = $name==='Mage_Downloader'; - if (!empty($data['upgrade_latest'])) { - $status = 'upgrade-available'; - $releases = array(); - $connect->run('info', array(), array($channel, $name)); - $output = $connect->getOutput(); - if (!empty($output['info']['releases'])) { - foreach ($output['info']['releases'] as $release) { - $stability = $packages[$channel][$name]['stability']; - if ($states[$release['s']] < min($preferredState, $states[$stability])) { - continue; - } - if (version_compare($release['v'], $packages[$channel][$name]['version']) < 1) { - continue; - } - $releases[$release['v']] = $release['v'].' ('.$release['s'].')'; - } - } - - if ($releases) { - uksort($releases, 'version_compare'); - foreach ($releases as $version => $release) { - $actions['upgrade|'.$version] = 'Upgrade to '.$release; - } - } else { - $a = explode(' ', $data['upgrade_latest'], 2); - $actions['upgrade|'.$a[0]] = 'Upgrade'; - } - if (!$systemPkg) { - $actions['uninstall'] = 'Uninstall'; - } - } else { - $status = 'installed'; - $actions['reinstall'] = 'Reinstall'; - if (!$systemPkg) { - $actions['uninstall'] = 'Uninstall'; - } - } - $packages[$channel][$name]['actions'] = $actions; - $packages[$channel][$name]['status'] = $status; - } - } - return $packages; - } - - /** - * Run packages action - * - * @param mixed $packages - */ - public function applyPackagesActions($packages, $ignoreLocalModification='') - { - $actions = array(); - foreach ($packages as $package=>$action) { - if ($action) { - $a = explode('|', $package); - $b = explode('|', $action); - $package = $a[1]; - $channel = $a[0]; - $version = ''; - if ($b[0]=='upgrade') { - $version = $b[1]; - } - $actions[$b[0]][] = array($channel, $package, $version, $version); - } - } - if (empty($actions)) { - $this->connect()->runHtmlConsole('No actions selected'); - exit; - } - - $this->controller()->startInstall(); - - $options = array(); - if (!empty($ignoreLocalModification)) { - $options = array('ignorelocalmodification'=>1); - } - if(!$this->controller()->isWritable()||strlen($this->connect()->getConfig()->__get('remote_config'))>0){ - $options['ftp'] = $this->connect()->getConfig()->__get('remote_config'); - } - - $this->controller()->channelConfig()->setCommandOptions($this->controller()->session(), $options); - - foreach ($actions as $action=>$packages) { - foreach ($packages as $package) { - switch ($action) { - case 'install': case 'uninstall': case 'upgrade': - $this->connect()->runHtmlConsole(array( - 'command'=>$action, - 'options'=>$options, - 'params'=>$package - )); - break; - - case 'reinstall': - $package_info = $this->connect()->getSingleConfig()->getPackage($package[0], $package[1]); - if (isset($package_info['version'])) { - $package[2] = $package_info['version']; - $package[3] = $package_info['version']; - } - $this->connect()->runHtmlConsole(array( - 'command'=>'install', - 'options'=>array_merge($options, array('force'=>1, 'nodeps'=>1)), - 'params'=>$package - )); - break; - } - } - } - - $this->controller()->endInstall(); - } - - - public function installUploadedPackage($file) - { - $this->controller()->startInstall(); - - $options = array(); - if(!$this->controller()->isWritable()||strlen($this->connect()->getConfig()->__get('remote_config'))>0){ - $options['ftp'] = $this->connect()->getConfig()->__get('remote_config'); - } - $this->connect()->runHtmlConsole(array( - 'command'=>'install-file', - 'options'=>$options, - 'params'=>array($file), - )); - $this->controller()->endInstall(); - } - - /** - * Install package by id - * - * @param string $id - * @param boolean $force - */ - public function installPackage($id, $force=false) - { - $match = array(); - if (!$this->checkExtensionKey($id, $match)) { - $this->connect()->runHtmlConsole('Invalid package identifier provided: '.$id); - exit; - } - - $channel = $match[1]; - $package = $match[2];//.(!empty($match[3]) ? $match[3] : ''); - $version = (!empty($match[3]) ? trim($match[3],'/\-') : ''); - - $this->controller()->startInstall(); - - $options = array(); - if ($force) { - $options['force'] = 1; - } - if(!$this->controller()->isWritable()||strlen($this->connect()->getConfig()->__get('remote_config'))>0){ - $options['ftp'] = $this->connect()->getConfig()->__get('remote_config'); - } - - $this->controller()->channelConfig()->setCommandOptions($this->controller()->session(), $options); - - $this->connect()->runHtmlConsole(array( - 'command'=>'install', - 'options'=>$options, - 'params'=>array(0=>$channel, 1=>$package, 2=>$version), - )); - - $this->controller()->endInstall(); - } - - /** - * Retrieve stability choosen client - * - * @return string alpha, beta, ... - */ - public function getPreferredState() - { - if (is_null($this->get('preferred_state'))) { - $connectConfig = $this->connect()->getConfig(); - $this->set('preferred_state', $connectConfig->__get('preferred_state')); - } - return $this->get('preferred_state'); - } - - /** - * Retrieve protocol choosen client - * - * @return string http, ftp - */ - public function getProtocol() - { - if (is_null($this->get('protocol'))) { - $connectConfig = $this->connect()->getConfig(); - $this->set('protocol', $connectConfig->__get('protocol')); - } - return $this->get('protocol'); - } - - /** - * Validate settings post data. - * - * @param array $p - */ - public function validateConfigPost($p) - { - $errors = array(); - $configTestFile = 'connect.cfgt'; - $configObj = $this->connect()->getConfig(); - if ('ftp' == $p['deployment_type'] || '1' == $p['inst_protocol']) { - /*check ftp*/ - - $confFile = $configObj->downloader_path.DIRECTORY_SEPARATOR.$configTestFile; - try { - $ftpObj = new Mage_Connect_Ftp(); - $ftpObj->connect($p['ftp']); - $tempFile = tempnam(sys_get_temp_dir(),'config'); - $serial = md5('config test file'); - $f = @fopen($tempFile, "w+"); - @fwrite($f, $serial); - @fclose($f); - $ret=$ftpObj->upload($confFile, $tempFile); - - //read file - if (!$errors && is_file($configTestFile)) { - $size = filesize($configTestFile); - if(!$size) { - $errors[]='Unable to read saved settings. Please check Installation Path of FTP Connection.'; - } - - if (!$errors) { - $f = @fopen($configTestFile, "r"); - @fseek($f, 0, SEEK_SET); - - $contents = @fread($f, strlen($serial)); - if ($serial != $contents) { - $errors[]='Wrong Installation Path of FTP Connection.'; - } - fclose($f); - } - } else { - $errors[] = 'Unable to read saved settings. Please check Installation Path of FTP Connection.'; - } - $ftpObj->delete($confFile); - $ftpObj->close(); - } catch (Exception $e) { - $errors[] = 'Deployment FTP Error. ' . $e->getMessage(); - } - } else { - $p['ftp'] = ''; - } - - if ('1' == $p['use_custom_permissions_mode']) { - /*check permissions*/ - if (octdec(intval($p['mkdir_mode'])) < 73 || octdec(intval($p['mkdir_mode'])) > 511) { - $errors[]='Folders permissions not valid. '; - } - if (octdec(intval($p['chmod_file_mode'])) < 73 || octdec(intval($p['chmod_file_mode'])) > 511) { - $errors[]='Files permissions not valid. '; - } - } - //$this->controller()->session()->addMessage('success', 'Settings has been successfully saved'); - return $errors; - } - /** - * Save settings. - * - * @param array $p - */ - public function saveConfigPost($p) - { - $configObj = $this->connect()->getConfig(); - if ('ftp' == $p['deployment_type'] || '1' == $p['inst_protocol']){ - $this->set('ftp',$p['ftp']); - } else { - $p['ftp'] = ''; - } - $configObj->remote_config = $p['ftp']; - $configObj->preferred_state = $p['preferred_state']; - $configObj->protocol = $p['protocol']; - $configObj->use_custom_permissions_mode = $p['use_custom_permissions_mode']; - if ('1' == $p['use_custom_permissions_mode']) { - $configObj->global_dir_mode = octdec(intval($p['mkdir_mode'])); - $configObj->global_file_mode = octdec(intval($p['chmod_file_mode'])); - } - if ($configObj->save()) { - $this->controller()->session()->addMessage('success', 'Settings has been successfully saved'); - } else { - $this->controller()->session()->addMessage('error', 'Settings cannot be saved'); - } - return $this; - } - - /** - * Check Extension Key - * - * @param string $id - * @param array $match - * @return int - */ - public function checkExtensionKey($id, &$match) - { - if (preg_match('#^(.+)\/(.+)-([\.\d]+)$#', $id, $match)) { - return $match; - } - return preg_match('#^(.+)\/(.+)$#', $id, $match); - } -} diff --git a/downloader/Maged/Model/Connect/Request.php b/downloader/Maged/Model/Connect/Request.php deleted file mode 100644 index fe6b6aaf551..00000000000 --- a/downloader/Maged/Model/Connect/Request.php +++ /dev/null @@ -1,43 +0,0 @@ -set('success_callback', 'clear_cache({success:parent.onSuccess, fail:parent.onFailure})'); - $this->set('failure_callback', 'parent.onFailure()'); - } -} diff --git a/downloader/Maged/Model/Dowloader.php b/downloader/Maged/Model/Dowloader.php deleted file mode 100644 index 95f96fde225..00000000000 --- a/downloader/Maged/Model/Dowloader.php +++ /dev/null @@ -1,30 +0,0 @@ -controller()->isInstalled()) { - // initialize Magento Config - Mage::app(); - $this->_session = Mage::getSingleton('admin/session'); - } else { - session_start(); - } - return $this; - } - - /** - * Get value by key - * - * @param string $key - * @return mixed - */ - public function get($key) - { - return isset($_SESSION[$key]) ? $_SESSION[$key] : null; - } - - /** - * Set value for key - * - * @param string $key - * @param mixed $value - */ - public function set($key, $value) - { - $_SESSION[$key] = $value; - return $this; - } - - /** - * Unset value by key - * - * @param string $key - * @return $this - */ - public function delete($key) - { - if (isset($_SESSION[$key])) { - unset($_SESSION[$key]); - } - return $this; - } - - /** - * Authentication to downloader - * @param Maged_BruteForce_Validator $bruteForceValidator - * @return $this - */ - public function authenticate(Maged_BruteForce_Validator $bruteForceValidator ) - { - if (!$this->_session) { - return $this; - } - - if (!empty($_GET['return'])) { - $this->set('return_url', $_GET['return']); - } - - if ($this->_checkUserAccess()) { - return $this; - } - - if (!$this->controller()->isInstalled()) { - return $this; - } - - try { - if (isset($_POST['username']) && !$this->validateFormKey()) { - $this->controller() - ->redirect( - $this->controller()->url(), - true - ); - } - if ( (isset($_POST['username']) && empty($_POST['username'])) - || (isset($_POST['password']) && empty($_POST['password']))) { - $this->addMessage('error', 'Invalid user name or password'); - } - if (empty($_POST['username']) || empty($_POST['password'])) { - $this->controller()->setAction('login'); - return $this; - } - $user = $this->_session->login($_POST['username'], $_POST['password']); - $this->_session->refreshAcl(); - if ($this->_checkUserAccess($user)) { - $bruteForceValidator->doGoodLogin(); - return $this; - } else { - $bruteForceValidator->doBadLogin(); - } - } catch (Exception $e) { - $this->addMessage('error', $e->getMessage()); - } - - $this->controller() - ->redirect( - $this->controller()->url('loggedin'), - true - ); - } - - /** - * Check is user logged in and permissions - * - * @param Mage_Admin_Model_User|null $user - * @return bool - */ - protected function _checkUserAccess($user = null) - { - if ($user && !$user->getId()) { - $this->addMessage('error', 'Invalid user name or password'); - $this->controller()->setAction('login'); - } elseif ($this->getUserId() || ($user && $user->getId())) { - if ($this->_session->isAllowed('all')) { - return true; - } else { - $this->logout(); - $this->addMessage('error', 'Access Denied', true); - $this->controller()->setAction('login'); - } - } - return false; - } - - /** - * Log Out - * - * @return Maged_Model_Session - */ - public function logout() - { - if (!$this->_session) { - return $this; - } - $this->_session->unsUser(); - return $this; - } - - /** - * Retrieve user - * - * @return mixed - */ - public function getUserId() - { - if (($session = $this->_session) && ($user = $session->getUser())) { - return $user->getId(); - } - return false; - } - - /** - * Add Message - * - * @param string $type - * @param string $msg - * @param string $clear - * @return Maged_Model_Session - */ - public function addMessage($type, $msg, $clear = false) - { - $msgs = $this->getMessages($clear); - $msgs[$type][] = $msg; - $this->set('messages', $msgs); - return $this; - } - - /** - * Retrieve messages from cache - * - * @param boolean $clear - * @return mixed - */ - public function getMessages($clear = true) - { - $msgs = $this->get('messages'); - $msgs = $msgs ? $msgs : array(); - if ($clear) { - unset($_SESSION['messages']); - } - return $msgs; - } - - /** - * Retrieve url to adminhtml - * - * @return string - */ - public function getReturnUrl() - { - if (!$this->_session || !$this->_session->isLoggedIn()) { - return ''; - } - return Mage::getSingleton('adminhtml/url')->getUrl('adminhtml'); - } - - /** - * Retrieve Session Form Key - * - * @return string A 16 bit unique key for forms - */ - public function getFormKey() - { - if (!$this->get('_form_key')) { - $this->set('_form_key', Mage::helper('core')->getRandomString(16)); - } - return $this->get('_form_key'); - } - - /** - * Validate Form Key - * - * @return bool - */ - public function validateFormKey() - { - if (!($formKey = $_REQUEST['form_key']) || $formKey != $this->getFormKey()) { - return false; - } - return true; - } - - /** - * Validate key for cache cleaning - * - * @return bool - */ - public function validateCleanCacheKey() - { - $result = false; - $validateKey = $this->get('validate_cache_key'); - if ($validateKey - && !empty($_REQUEST['validate_cache_key']) - && $validateKey == $_REQUEST['validate_cache_key'] - ) { - $result = true; - } - $this->delete('validate_cache_key'); - - return $result; - } -} diff --git a/downloader/Maged/View.php b/downloader/Maged/View.php deleted file mode 100644 index ddd389d73fb..00000000000 --- a/downloader/Maged/View.php +++ /dev/null @@ -1,197 +0,0 @@ -controller()->url($action, $params); - } - - /** - * Retrieve base url - * - * @return string - */ - public function baseUrl() - { - return str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])); - } - - /** - * Retrieve url of magento - * - * @return string - */ - public function mageUrl() - { - return str_replace('\\', '/', dirname($this->baseUrl())); - } - - /** - * Include template - * - * @param string $name - * @return string - */ - public function template($name) - { - ob_start(); - include $this->controller()->filepath('template/'.$name); - return ob_get_clean(); - } - - /** - * Set value for key - * - * @param string $key - * @param mixed $value - * @return Maged_Controller - */ - public function set($key, $value) - { - $this->_data[$key] = $value; - return $this; - } - - /** - * Get value by key - * - * @param string $key - * @return mixed - */ - public function get($key) - { - return isset($this->_data[$key]) ? $this->_data[$key] : null; - } - - /** - * Translator - * - * @param string $string - * @return string - */ - public function __($string) - { - return $string; - } - - /** - * Retrieve link for header menu - * - * @param mixed $action - */ - public function getNavLinkParams($action) - { - $params = 'href="'.$this->url($action).'"'; - if ($this->controller()->getAction()==$action) { - $params .= ' class="active"'; - } - return $params; - } - - /** - * Retrieve Session Form Key - * - * @return string - */ - public function getFormKey() - { - return $this->controller()->getFormKey(); - } - - /** - * Escape html entities - * - * @param mixed $data - * @param array $allowedTags - * @return mixed - */ - public function escapeHtml($data, $allowedTags = null) - { - if (is_array($data)) { - $result = array(); - foreach ($data as $item) { - $result[] = $this->escapeHtml($item); - } - } else { - // process single item - if (strlen($data)) { - if (is_array($allowedTags) and !empty($allowedTags)) { - $allowed = implode('|', $allowedTags); - $result = preg_replace('/<([\/\s\r\n]*)(' . $allowed . ')([\/\s\r\n]*)>/si', '##$1$2$3##', $data); - $result = htmlspecialchars($result, ENT_COMPAT, 'UTF-8', false); - $result = preg_replace('/##([\/\s\r\n]*)(' . $allowed . ')([\/\s\r\n]*)##/si', '<$1$2$3>', $result); - } else { - $result = htmlspecialchars($data, ENT_COMPAT, 'UTF-8', false); - } - } else { - $result = $data; - } - } - return $result; - } -} diff --git a/downloader/config.ini b/downloader/config.ini deleted file mode 100644 index b2c56fcdc75..00000000000 --- a/downloader/config.ini +++ /dev/null @@ -1 +0,0 @@ -root_channel=community \ No newline at end of file diff --git a/downloader/favicon.ico b/downloader/favicon.ico deleted file mode 100644 index 1cb7c771371..00000000000 Binary files a/downloader/favicon.ico and /dev/null differ diff --git a/downloader/index.php b/downloader/index.php deleted file mode 100644 index 71ac906de53..00000000000 --- a/downloader/index.php +++ /dev/null @@ -1,36 +0,0 @@ -

    Whoops, it looks like you have an invalid PHP version.

    Magento supports PHP 5.2.0 or newer. Find out how to install Magento using PHP-CGI as a work-around.

'; - exit; -} - -require_once("lib/Mage/Autoload/Simple.php"); -Mage_Autoload_Simple::register(); - -umask(0); -Maged_Controller::run(); diff --git a/downloader/js/prototype.js b/downloader/js/prototype.js deleted file mode 100644 index a3f21ac7909..00000000000 --- a/downloader/js/prototype.js +++ /dev/null @@ -1,3277 +0,0 @@ -/* Prototype JavaScript framework, version 1.5.1.1 - * (c) 2005-2007 Sam Stephenson - * - * Prototype is freely distributable under the terms of an MIT-style license. - * For details, see the Prototype web site: http://www.prototypejs.org/ - * -/*--------------------------------------------------------------------------*/ - -var Prototype = { - Version: '1.5.1.1', - - Browser: { - IE: !!(window.attachEvent && !window.opera), - Opera: !!window.opera, - WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1, - Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1 - }, - - BrowserFeatures: { - XPath: !!document.evaluate, - ElementExtensions: !!window.HTMLElement, - SpecificElementExtensions: - (document.createElement('div').__proto__ !== - document.createElement('form').__proto__) - }, - - ScriptFragment: ']*>([\\S\\s]*?)<\/script>', - JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, - - emptyFunction: function() { }, - K: function(x) { return x } -} - -var Class = { - create: function() { - return function() { - this.initialize.apply(this, arguments); - } - } -} - -var Abstract = new Object(); - -Object.extend = function(destination, source) { - for (var property in source) { - destination[property] = source[property]; - } - return destination; -} - -Object.extend(Object, { - inspect: function(object) { - try { - if (object === undefined) return 'undefined'; - if (object === null) return 'null'; - return object.inspect ? object.inspect() : object.toString(); - } catch (e) { - if (e instanceof RangeError) return '...'; - throw e; - } - }, - - toJSON: function(object) { - var type = typeof object; - switch(type) { - case 'undefined': - case 'function': - case 'unknown': return; - case 'boolean': return object.toString(); - } - if (object === null) return 'null'; - if (object.toJSON) return object.toJSON(); - if (object.ownerDocument === document) return; - var results = []; - for (var property in object) { - var value = Object.toJSON(object[property]); - if (value !== undefined) - results.push(property.toJSON() + ': ' + value); - } - return '{' + results.join(', ') + '}'; - }, - - keys: function(object) { - var keys = []; - for (var property in object) - keys.push(property); - return keys; - }, - - values: function(object) { - var values = []; - for (var property in object) - values.push(object[property]); - return values; - }, - - clone: function(object) { - return Object.extend({}, object); - } -}); - -Function.prototype.bind = function() { - var __method = this, args = $A(arguments), object = args.shift(); - return function() { - return __method.apply(object, args.concat($A(arguments))); - } -} - -Function.prototype.bindAsEventListener = function(object) { - var __method = this, args = $A(arguments), object = args.shift(); - return function(event) { - return __method.apply(object, [event || window.event].concat(args)); - } -} - -Object.extend(Number.prototype, { - toColorPart: function() { - return this.toPaddedString(2, 16); - }, - - succ: function() { - return this + 1; - }, - - times: function(iterator) { - $R(0, this, true).each(iterator); - return this; - }, - - toPaddedString: function(length, radix) { - var string = this.toString(radix || 10); - return '0'.times(length - string.length) + string; - }, - - toJSON: function() { - return isFinite(this) ? this.toString() : 'null'; - } -}); - -Date.prototype.toJSON = function() { - return '"' + this.getFullYear() + '-' + - (this.getMonth() + 1).toPaddedString(2) + '-' + - this.getDate().toPaddedString(2) + 'T' + - this.getHours().toPaddedString(2) + ':' + - this.getMinutes().toPaddedString(2) + ':' + - this.getSeconds().toPaddedString(2) + '"'; -}; - -var Try = { - these: function() { - var returnValue; - - for (var i = 0, length = arguments.length; i < length; i++) { - var lambda = arguments[i]; - try { - returnValue = lambda(); - break; - } catch (e) {} - } - - return returnValue; - } -} - -/*--------------------------------------------------------------------------*/ - -var PeriodicalExecuter = Class.create(); -PeriodicalExecuter.prototype = { - initialize: function(callback, frequency) { - this.callback = callback; - this.frequency = frequency; - this.currentlyExecuting = false; - - this.registerCallback(); - }, - - registerCallback: function() { - this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); - }, - - stop: function() { - if (!this.timer) return; - clearInterval(this.timer); - this.timer = null; - }, - - onTimerEvent: function() { - if (!this.currentlyExecuting) { - try { - this.currentlyExecuting = true; - this.callback(this); - } finally { - this.currentlyExecuting = false; - } - } - } -} -Object.extend(String, { - interpret: function(value) { - return value == null ? '' : String(value); - }, - specialChar: { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '\\': '\\\\' - } -}); - -Object.extend(String.prototype, { - gsub: function(pattern, replacement) { - var result = '', source = this, match; - replacement = arguments.callee.prepareReplacement(replacement); - - while (source.length > 0) { - if (match = source.match(pattern)) { - result += source.slice(0, match.index); - result += String.interpret(replacement(match)); - source = source.slice(match.index + match[0].length); - } else { - result += source, source = ''; - } - } - return result; - }, - - sub: function(pattern, replacement, count) { - replacement = this.gsub.prepareReplacement(replacement); - count = count === undefined ? 1 : count; - - return this.gsub(pattern, function(match) { - if (--count < 0) return match[0]; - return replacement(match); - }); - }, - - scan: function(pattern, iterator) { - this.gsub(pattern, iterator); - return this; - }, - - truncate: function(length, truncation) { - length = length || 30; - truncation = truncation === undefined ? '...' : truncation; - return this.length > length ? - this.slice(0, length - truncation.length) + truncation : this; - }, - - strip: function() { - return this.replace(/^\s+/, '').replace(/\s+$/, ''); - }, - - stripTags: function() { - return this.replace(/<\/?[^>]+>/gi, ''); - }, - - stripScripts: function() { - return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); - }, - - extractScripts: function() { - var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); - var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); - return (this.match(matchAll) || []).map(function(scriptTag) { - return (scriptTag.match(matchOne) || ['', ''])[1]; - }); - }, - - evalScripts: function() { - return this.extractScripts().map(function(script) { return eval(script) }); - }, - - escapeHTML: function() { - var self = arguments.callee; - self.text.data = this; - return self.div.innerHTML; - }, - - unescapeHTML: function() { - var div = document.createElement('div'); - div.innerHTML = this.stripTags(); - return div.childNodes[0] ? (div.childNodes.length > 1 ? - $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) : - div.childNodes[0].nodeValue) : ''; - }, - - toQueryParams: function(separator) { - var match = this.strip().match(/([^?#]*)(#.*)?$/); - if (!match) return {}; - - return match[1].split(separator || '&').inject({}, function(hash, pair) { - if ((pair = pair.split('='))[0]) { - var key = decodeURIComponent(pair.shift()); - var value = pair.length > 1 ? pair.join('=') : pair[0]; - if (value != undefined) value = decodeURIComponent(value); - - if (key in hash) { - if (hash[key].constructor != Array) hash[key] = [hash[key]]; - hash[key].push(value); - } - else hash[key] = value; - } - return hash; - }); - }, - - toArray: function() { - return this.split(''); - }, - - succ: function() { - return this.slice(0, this.length - 1) + - String.fromCharCode(this.charCodeAt(this.length - 1) + 1); - }, - - times: function(count) { - var result = ''; - for (var i = 0; i < count; i++) result += this; - return result; - }, - - camelize: function() { - var parts = this.split('-'), len = parts.length; - if (len == 1) return parts[0]; - - var camelized = this.charAt(0) == '-' - ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) - : parts[0]; - - for (var i = 1; i < len; i++) - camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); - - return camelized; - }, - - capitalize: function() { - return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); - }, - - underscore: function() { - return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); - }, - - dasherize: function() { - return this.gsub(/_/,'-'); - }, - - inspect: function(useDoubleQuotes) { - var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) { - var character = String.specialChar[match[0]]; - return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16); - }); - if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; - return "'" + escapedString.replace(/'/g, '\\\'') + "'"; - }, - - toJSON: function() { - return this.inspect(true); - }, - - unfilterJSON: function(filter) { - return this.sub(filter || Prototype.JSONFilter, '#{1}'); - }, - - isJSON: function() { - var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); - return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); - }, - - evalJSON: function(sanitize) { - var json = this.unfilterJSON(); - try { - if (!sanitize || json.isJSON()) return eval('(' + json + ')'); - } catch (e) { } - throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); - }, - - include: function(pattern) { - return this.indexOf(pattern) > -1; - }, - - startsWith: function(pattern) { - return this.indexOf(pattern) === 0; - }, - - endsWith: function(pattern) { - var d = this.length - pattern.length; - return d >= 0 && this.lastIndexOf(pattern) === d; - }, - - empty: function() { - return this == ''; - }, - - blank: function() { - return /^\s*$/.test(this); - } -}); - -if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, { - escapeHTML: function() { - return this.replace(/&/g,'&').replace(//g,'>'); - }, - unescapeHTML: function() { - return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); - } -}); - -String.prototype.gsub.prepareReplacement = function(replacement) { - if (typeof replacement == 'function') return replacement; - var template = new Template(replacement); - return function(match) { return template.evaluate(match) }; -} - -String.prototype.parseQuery = String.prototype.toQueryParams; - -Object.extend(String.prototype.escapeHTML, { - div: document.createElement('div'), - text: document.createTextNode('') -}); - -with (String.prototype.escapeHTML) div.appendChild(text); - -var Template = Class.create(); -Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; -Template.prototype = { - initialize: function(template, pattern) { - this.template = template.toString(); - this.pattern = pattern || Template.Pattern; - }, - - evaluate: function(object) { - return this.template.gsub(this.pattern, function(match) { - var before = match[1]; - if (before == '\\') return match[2]; - return before + String.interpret(object[match[3]]); - }); - } -} - -var $break = {}, $continue = new Error('"throw $continue" is deprecated, use "return" instead'); - -var Enumerable = { - each: function(iterator) { - var index = 0; - try { - this._each(function(value) { - iterator(value, index++); - }); - } catch (e) { - if (e != $break) throw e; - } - return this; - }, - - eachSlice: function(number, iterator) { - var index = -number, slices = [], array = this.toArray(); - while ((index += number) < array.length) - slices.push(array.slice(index, index+number)); - return slices.map(iterator); - }, - - all: function(iterator) { - var result = true; - this.each(function(value, index) { - result = result && !!(iterator || Prototype.K)(value, index); - if (!result) throw $break; - }); - return result; - }, - - any: function(iterator) { - var result = false; - this.each(function(value, index) { - if (result = !!(iterator || Prototype.K)(value, index)) - throw $break; - }); - return result; - }, - - collect: function(iterator) { - var results = []; - this.each(function(value, index) { - results.push((iterator || Prototype.K)(value, index)); - }); - return results; - }, - - detect: function(iterator) { - var result; - this.each(function(value, index) { - if (iterator(value, index)) { - result = value; - throw $break; - } - }); - return result; - }, - - findAll: function(iterator) { - var results = []; - this.each(function(value, index) { - if (iterator(value, index)) - results.push(value); - }); - return results; - }, - - grep: function(pattern, iterator) { - var results = []; - this.each(function(value, index) { - var stringValue = value.toString(); - if (stringValue.match(pattern)) - results.push((iterator || Prototype.K)(value, index)); - }) - return results; - }, - - include: function(object) { - var found = false; - this.each(function(value) { - if (value == object) { - found = true; - throw $break; - } - }); - return found; - }, - - inGroupsOf: function(number, fillWith) { - fillWith = fillWith === undefined ? null : fillWith; - return this.eachSlice(number, function(slice) { - while(slice.length < number) slice.push(fillWith); - return slice; - }); - }, - - inject: function(memo, iterator) { - this.each(function(value, index) { - memo = iterator(memo, value, index); - }); - return memo; - }, - - invoke: function(method) { - var args = $A(arguments).slice(1); - return this.map(function(value) { - return value[method].apply(value, args); - }); - }, - - max: function(iterator) { - var result; - this.each(function(value, index) { - value = (iterator || Prototype.K)(value, index); - if (result == undefined || value >= result) - result = value; - }); - return result; - }, - - min: function(iterator) { - var result; - this.each(function(value, index) { - value = (iterator || Prototype.K)(value, index); - if (result == undefined || value < result) - result = value; - }); - return result; - }, - - partition: function(iterator) { - var trues = [], falses = []; - this.each(function(value, index) { - ((iterator || Prototype.K)(value, index) ? - trues : falses).push(value); - }); - return [trues, falses]; - }, - - pluck: function(property) { - var results = []; - this.each(function(value, index) { - results.push(value[property]); - }); - return results; - }, - - reject: function(iterator) { - var results = []; - this.each(function(value, index) { - if (!iterator(value, index)) - results.push(value); - }); - return results; - }, - - sortBy: function(iterator) { - return this.map(function(value, index) { - return {value: value, criteria: iterator(value, index)}; - }).sort(function(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }).pluck('value'); - }, - - toArray: function() { - return this.map(); - }, - - zip: function() { - var iterator = Prototype.K, args = $A(arguments); - if (typeof args.last() == 'function') - iterator = args.pop(); - - var collections = [this].concat(args).map($A); - return this.map(function(value, index) { - return iterator(collections.pluck(index)); - }); - }, - - size: function() { - return this.toArray().length; - }, - - inspect: function() { - return '#'; - } -} - -Object.extend(Enumerable, { - map: Enumerable.collect, - find: Enumerable.detect, - select: Enumerable.findAll, - member: Enumerable.include, - entries: Enumerable.toArray -}); -var $A = Array.from = function(iterable) { - if (!iterable) return []; - if (iterable.toArray) { - return iterable.toArray(); - } else { - var results = []; - for (var i = 0, length = iterable.length; i < length; i++) - results.push(iterable[i]); - return results; - } -} - -if (Prototype.Browser.WebKit) { - $A = Array.from = function(iterable) { - if (!iterable) return []; - if (!(typeof iterable == 'function' && iterable == '[object NodeList]') && - iterable.toArray) { - return iterable.toArray(); - } else { - var results = []; - for (var i = 0, length = iterable.length; i < length; i++) - results.push(iterable[i]); - return results; - } - } -} - -Object.extend(Array.prototype, Enumerable); - -if (!Array.prototype._reverse) - Array.prototype._reverse = Array.prototype.reverse; - -Object.extend(Array.prototype, { - _each: function(iterator) { - for (var i = 0, length = this.length; i < length; i++) - iterator(this[i]); - }, - - clear: function() { - this.length = 0; - return this; - }, - - first: function() { - return this[0]; - }, - - last: function() { - return this[this.length - 1]; - }, - - compact: function() { - return this.select(function(value) { - return value != null; - }); - }, - - flatten: function() { - return this.inject([], function(array, value) { - return array.concat(value && value.constructor == Array ? - value.flatten() : [value]); - }); - }, - - without: function() { - var values = $A(arguments); - return this.select(function(value) { - return !values.include(value); - }); - }, - - indexOf: function(object) { - for (var i = 0, length = this.length; i < length; i++) - if (this[i] == object) return i; - return -1; - }, - - reverse: function(inline) { - return (inline !== false ? this : this.toArray())._reverse(); - }, - - reduce: function() { - return this.length > 1 ? this : this[0]; - }, - - uniq: function(sorted) { - return this.inject([], function(array, value, index) { - if (0 == index || (sorted ? array.last() != value : !array.include(value))) - array.push(value); - return array; - }); - }, - - clone: function() { - return [].concat(this); - }, - - size: function() { - return this.length; - }, - - inspect: function() { - return '[' + this.map(Object.inspect).join(', ') + ']'; - }, - - toJSON: function() { - var results = []; - this.each(function(object) { - var value = Object.toJSON(object); - if (value !== undefined) results.push(value); - }); - return '[' + results.join(', ') + ']'; - } -}); - -Array.prototype.toArray = Array.prototype.clone; - -function $w(string) { - string = string.strip(); - return string ? string.split(/\s+/) : []; -} - -if (Prototype.Browser.Opera){ - Array.prototype.concat = function() { - var array = []; - for (var i = 0, length = this.length; i < length; i++) array.push(this[i]); - for (var i = 0, length = arguments.length; i < length; i++) { - if (arguments[i].constructor == Array) { - for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) - array.push(arguments[i][j]); - } else { - array.push(arguments[i]); - } - } - return array; - } -} -var Hash = function(object) { - if (object instanceof Hash) this.merge(object); - else Object.extend(this, object || {}); -}; - -Object.extend(Hash, { - toQueryString: function(obj) { - var parts = []; - parts.add = arguments.callee.addPair; - - this.prototype._each.call(obj, function(pair) { - if (!pair.key) return; - var value = pair.value; - - if (value && typeof value == 'object') { - if (value.constructor == Array) value.each(function(value) { - parts.add(pair.key, value); - }); - return; - } - parts.add(pair.key, value); - }); - - return parts.join('&'); - }, - - toJSON: function(object) { - var results = []; - this.prototype._each.call(object, function(pair) { - var value = Object.toJSON(pair.value); - if (value !== undefined) results.push(pair.key.toJSON() + ': ' + value); - }); - return '{' + results.join(', ') + '}'; - } -}); - -Hash.toQueryString.addPair = function(key, value, prefix) { - key = encodeURIComponent(key); - if (value === undefined) this.push(key); - else this.push(key + '=' + (value == null ? '' : encodeURIComponent(value))); -} - -Object.extend(Hash.prototype, Enumerable); -Object.extend(Hash.prototype, { - _each: function(iterator) { - for (var key in this) { - var value = this[key]; - if (value && value == Hash.prototype[key]) continue; - - var pair = [key, value]; - pair.key = key; - pair.value = value; - iterator(pair); - } - }, - - keys: function() { - return this.pluck('key'); - }, - - values: function() { - return this.pluck('value'); - }, - - merge: function(hash) { - return $H(hash).inject(this, function(mergedHash, pair) { - mergedHash[pair.key] = pair.value; - return mergedHash; - }); - }, - - remove: function() { - var result; - for(var i = 0, length = arguments.length; i < length; i++) { - var value = this[arguments[i]]; - if (value !== undefined){ - if (result === undefined) result = value; - else { - if (result.constructor != Array) result = [result]; - result.push(value) - } - } - delete this[arguments[i]]; - } - return result; - }, - - toQueryString: function() { - return Hash.toQueryString(this); - }, - - inspect: function() { - return '#'; - }, - - toJSON: function() { - return Hash.toJSON(this); - } -}); - -function $H(object) { - if (object instanceof Hash) return object; - return new Hash(object); -}; - -// Safari iterates over shadowed properties -if (function() { - var i = 0, Test = function(value) { this.key = value }; - Test.prototype.key = 'foo'; - for (var property in new Test('bar')) i++; - return i > 1; -}()) Hash.prototype._each = function(iterator) { - var cache = []; - for (var key in this) { - var value = this[key]; - if ((value && value == Hash.prototype[key]) || cache.include(key)) continue; - cache.push(key); - var pair = [key, value]; - pair.key = key; - pair.value = value; - iterator(pair); - } -}; -ObjectRange = Class.create(); -Object.extend(ObjectRange.prototype, Enumerable); -Object.extend(ObjectRange.prototype, { - initialize: function(start, end, exclusive) { - this.start = start; - this.end = end; - this.exclusive = exclusive; - }, - - _each: function(iterator) { - var value = this.start; - while (this.include(value)) { - iterator(value); - value = value.succ(); - } - }, - - include: function(value) { - if (value < this.start) - return false; - if (this.exclusive) - return value < this.end; - return value <= this.end; - } -}); - -var $R = function(start, end, exclusive) { - return new ObjectRange(start, end, exclusive); -} - -var Ajax = { - getTransport: function() { - return Try.these( - function() {return new XMLHttpRequest()}, - function() {return new ActiveXObject('Msxml2.XMLHTTP')}, - function() {return new ActiveXObject('Microsoft.XMLHTTP')} - ) || false; - }, - - activeRequestCount: 0 -} - -Ajax.Responders = { - responders: [], - - _each: function(iterator) { - this.responders._each(iterator); - }, - - register: function(responder) { - if (!this.include(responder)) - this.responders.push(responder); - }, - - unregister: function(responder) { - this.responders = this.responders.without(responder); - }, - - dispatch: function(callback, request, transport, json) { - this.each(function(responder) { - if (typeof responder[callback] == 'function') { - try { - responder[callback].apply(responder, [request, transport, json]); - } catch (e) {} - } - }); - } -}; - -Object.extend(Ajax.Responders, Enumerable); - -Ajax.Responders.register({ - onCreate: function() { - Ajax.activeRequestCount++; - }, - onComplete: function() { - Ajax.activeRequestCount--; - } -}); - -Ajax.Base = function() {}; -Ajax.Base.prototype = { - setOptions: function(options) { - this.options = { - method: 'post', - asynchronous: true, - contentType: 'application/x-www-form-urlencoded', - encoding: 'UTF-8', - parameters: '' - } - Object.extend(this.options, options || {}); - - this.options.method = this.options.method.toLowerCase(); - if (typeof this.options.parameters == 'string') - this.options.parameters = this.options.parameters.toQueryParams(); - } -} - -Ajax.Request = Class.create(); -Ajax.Request.Events = - ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; - -Ajax.Request.prototype = Object.extend(new Ajax.Base(), { - _complete: false, - - initialize: function(url, options) { - this.transport = Ajax.getTransport(); - this.setOptions(options); - this.request(url); - }, - - request: function(url) { - this.url = url; - this.method = this.options.method; - var params = Object.clone(this.options.parameters); - - if (!['get', 'post'].include(this.method)) { - // simulate other verbs over post - params['_method'] = this.method; - this.method = 'post'; - } - - this.parameters = params; - - if (params = Hash.toQueryString(params)) { - // when GET, append parameters to URL - if (this.method == 'get') - this.url += (this.url.include('?') ? '&' : '?') + params; - else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) - params += '&_='; - } - - try { - if (this.options.onCreate) this.options.onCreate(this.transport); - Ajax.Responders.dispatch('onCreate', this, this.transport); - - this.transport.open(this.method.toUpperCase(), this.url, - this.options.asynchronous); - - if (this.options.asynchronous) - setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10); - - this.transport.onreadystatechange = this.onStateChange.bind(this); - this.setRequestHeaders(); - - this.body = this.method == 'post' ? (this.options.postBody || params) : null; - this.transport.send(this.body); - - /* Force Firefox to handle ready state 4 for synchronous requests */ - if (!this.options.asynchronous && this.transport.overrideMimeType) - this.onStateChange(); - - } - catch (e) { - this.dispatchException(e); - } - }, - - onStateChange: function() { - var readyState = this.transport.readyState; - if (readyState > 1 && !((readyState == 4) && this._complete)) - this.respondToReadyState(this.transport.readyState); - }, - - setRequestHeaders: function() { - var headers = { - 'X-Requested-With': 'XMLHttpRequest', - 'X-Prototype-Version': Prototype.Version, - 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' - }; - - if (this.method == 'post') { - headers['Content-type'] = this.options.contentType + - (this.options.encoding ? '; charset=' + this.options.encoding : ''); - - /* Force "Connection: close" for older Mozilla browsers to work - * around a bug where XMLHttpRequest sends an incorrect - * Content-length header. See Mozilla Bugzilla #246651. - */ - if (this.transport.overrideMimeType && - (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) - headers['Connection'] = 'close'; - } - - // user-defined headers - if (typeof this.options.requestHeaders == 'object') { - var extras = this.options.requestHeaders; - - if (typeof extras.push == 'function') - for (var i = 0, length = extras.length; i < length; i += 2) - headers[extras[i]] = extras[i+1]; - else - $H(extras).each(function(pair) { headers[pair.key] = pair.value }); - } - - for (var name in headers) - this.transport.setRequestHeader(name, headers[name]); - }, - - success: function() { - return !this.transport.status - || (this.transport.status >= 200 && this.transport.status < 300); - }, - - respondToReadyState: function(readyState) { - var state = Ajax.Request.Events[readyState]; - var transport = this.transport, json = this.evalJSON(); - - if (state == 'Complete') { - try { - this._complete = true; - (this.options['on' + this.transport.status] - || this.options['on' + (this.success() ? 'Success' : 'Failure')] - || Prototype.emptyFunction)(transport, json); - } catch (e) { - this.dispatchException(e); - } - - var contentType = this.getHeader('Content-type'); - if (contentType && contentType.strip(). - match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i)) - this.evalResponse(); - } - - try { - (this.options['on' + state] || Prototype.emptyFunction)(transport, json); - Ajax.Responders.dispatch('on' + state, this, transport, json); - } catch (e) { - this.dispatchException(e); - } - - if (state == 'Complete') { - // avoid memory leak in MSIE: clean up - this.transport.onreadystatechange = Prototype.emptyFunction; - } - }, - - getHeader: function(name) { - try { - return this.transport.getResponseHeader(name); - } catch (e) { return null } - }, - - evalJSON: function() { - try { - var json = this.getHeader('X-JSON'); - return json ? json.evalJSON() : null; - } catch (e) { return null } - }, - - evalResponse: function() { - try { - return eval((this.transport.responseText || '').unfilterJSON()); - } catch (e) { - this.dispatchException(e); - } - }, - - dispatchException: function(exception) { - (this.options.onException || Prototype.emptyFunction)(this, exception); - Ajax.Responders.dispatch('onException', this, exception); - } -}); - -Ajax.Updater = Class.create(); - -Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), { - initialize: function(container, url, options) { - this.container = { - success: (container.success || container), - failure: (container.failure || (container.success ? null : container)) - } - - this.transport = Ajax.getTransport(); - this.setOptions(options); - - var onComplete = this.options.onComplete || Prototype.emptyFunction; - this.options.onComplete = (function(transport, param) { - this.updateContent(); - onComplete(transport, param); - }).bind(this); - - this.request(url); - }, - - updateContent: function() { - var receiver = this.container[this.success() ? 'success' : 'failure']; - var response = this.transport.responseText; - - if (!this.options.evalScripts) response = response.stripScripts(); - - if (receiver = $(receiver)) { - if (this.options.insertion) - new this.options.insertion(receiver, response); - else - receiver.update(response); - } - - if (this.success()) { - if (this.onComplete) - setTimeout(this.onComplete.bind(this), 10); - } - } -}); - -Ajax.PeriodicalUpdater = Class.create(); -Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), { - initialize: function(container, url, options) { - this.setOptions(options); - this.onComplete = this.options.onComplete; - - this.frequency = (this.options.frequency || 2); - this.decay = (this.options.decay || 1); - - this.updater = {}; - this.container = container; - this.url = url; - - this.start(); - }, - - start: function() { - this.options.onComplete = this.updateComplete.bind(this); - this.onTimerEvent(); - }, - - stop: function() { - this.updater.options.onComplete = undefined; - clearTimeout(this.timer); - (this.onComplete || Prototype.emptyFunction).apply(this, arguments); - }, - - updateComplete: function(request) { - if (this.options.decay) { - this.decay = (request.responseText == this.lastText ? - this.decay * this.options.decay : 1); - - this.lastText = request.responseText; - } - this.timer = setTimeout(this.onTimerEvent.bind(this), - this.decay * this.frequency * 1000); - }, - - onTimerEvent: function() { - this.updater = new Ajax.Updater(this.container, this.url, this.options); - } -}); -function $(element) { - if (arguments.length > 1) { - for (var i = 0, elements = [], length = arguments.length; i < length; i++) - elements.push($(arguments[i])); - return elements; - } - if (typeof element == 'string') - element = document.getElementById(element); - return Element.extend(element); -} - -if (Prototype.BrowserFeatures.XPath) { - document._getElementsByXPath = function(expression, parentElement) { - var results = []; - var query = document.evaluate(expression, $(parentElement) || document, - null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); - for (var i = 0, length = query.snapshotLength; i < length; i++) - results.push(query.snapshotItem(i)); - return results; - }; - - document.getElementsByClassName = function(className, parentElement) { - var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]"; - return document._getElementsByXPath(q, parentElement); - } - -} else document.getElementsByClassName = function(className, parentElement) { - var children = ($(parentElement) || document.body).getElementsByTagName('*'); - var elements = [], child, pattern = new RegExp("(^|\\s)" + className + "(\\s|$)"); - for (var i = 0, length = children.length; i < length; i++) { - child = children[i]; - var elementClassName = child.className; - if (elementClassName.length == 0) continue; - if (elementClassName == className || elementClassName.match(pattern)) - elements.push(Element.extend(child)); - } - return elements; -}; - -/*--------------------------------------------------------------------------*/ - -if (!window.Element) var Element = {}; - -Element.extend = function(element) { - var F = Prototype.BrowserFeatures; - if (!element || !element.tagName || element.nodeType == 3 || - element._extended || F.SpecificElementExtensions || element == window) - return element; - - var methods = {}, tagName = element.tagName, cache = Element.extend.cache, - T = Element.Methods.ByTag; - - // extend methods for all tags (Safari doesn't need this) - if (!F.ElementExtensions) { - Object.extend(methods, Element.Methods), - Object.extend(methods, Element.Methods.Simulated); - } - - // extend methods for specific tags - if (T[tagName]) Object.extend(methods, T[tagName]); - - for (var property in methods) { - var value = methods[property]; - if (typeof value == 'function' && !(property in element)) - element[property] = cache.findOrStore(value); - } - - element._extended = Prototype.emptyFunction; - return element; -}; - -Element.extend.cache = { - findOrStore: function(value) { - return this[value] = this[value] || function() { - return value.apply(null, [this].concat($A(arguments))); - } - } -}; - -Element.Methods = { - visible: function(element) { - return $(element).style.display != 'none'; - }, - - toggle: function(element) { - element = $(element); - Element[Element.visible(element) ? 'hide' : 'show'](element); - return element; - }, - - hide: function(element) { - $(element).style.display = 'none'; - return element; - }, - - show: function(element) { - $(element).style.display = ''; - return element; - }, - - remove: function(element) { - element = $(element); - element.parentNode.removeChild(element); - return element; - }, - - update: function(element, html) { - html = typeof html == 'undefined' ? '' : html.toString(); - $(element).innerHTML = html.stripScripts(); - setTimeout(function() {html.evalScripts()}, 10); - return element; - }, - - replace: function(element, html) { - element = $(element); - html = typeof html == 'undefined' ? '' : html.toString(); - if (element.outerHTML) { - element.outerHTML = html.stripScripts(); - } else { - var range = element.ownerDocument.createRange(); - range.selectNodeContents(element); - element.parentNode.replaceChild( - range.createContextualFragment(html.stripScripts()), element); - } - setTimeout(function() {html.evalScripts()}, 10); - return element; - }, - - inspect: function(element) { - element = $(element); - var result = '<' + element.tagName.toLowerCase(); - $H({'id': 'id', 'className': 'class'}).each(function(pair) { - var property = pair.first(), attribute = pair.last(); - var value = (element[property] || '').toString(); - if (value) result += ' ' + attribute + '=' + value.inspect(true); - }); - return result + '>'; - }, - - recursivelyCollect: function(element, property) { - element = $(element); - var elements = []; - while (element = element[property]) - if (element.nodeType == 1) - elements.push(Element.extend(element)); - return elements; - }, - - ancestors: function(element) { - return $(element).recursivelyCollect('parentNode'); - }, - - descendants: function(element) { - return $A($(element).getElementsByTagName('*')).each(Element.extend); - }, - - firstDescendant: function(element) { - element = $(element).firstChild; - while (element && element.nodeType != 1) element = element.nextSibling; - return $(element); - }, - - immediateDescendants: function(element) { - if (!(element = $(element).firstChild)) return []; - while (element && element.nodeType != 1) element = element.nextSibling; - if (element) return [element].concat($(element).nextSiblings()); - return []; - }, - - previousSiblings: function(element) { - return $(element).recursivelyCollect('previousSibling'); - }, - - nextSiblings: function(element) { - return $(element).recursivelyCollect('nextSibling'); - }, - - siblings: function(element) { - element = $(element); - return element.previousSiblings().reverse().concat(element.nextSiblings()); - }, - - match: function(element, selector) { - if (typeof selector == 'string') - selector = new Selector(selector); - return selector.match($(element)); - }, - - up: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return $(element.parentNode); - var ancestors = element.ancestors(); - return expression ? Selector.findElement(ancestors, expression, index) : - ancestors[index || 0]; - }, - - down: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return element.firstDescendant(); - var descendants = element.descendants(); - return expression ? Selector.findElement(descendants, expression, index) : - descendants[index || 0]; - }, - - previous: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); - var previousSiblings = element.previousSiblings(); - return expression ? Selector.findElement(previousSiblings, expression, index) : - previousSiblings[index || 0]; - }, - - next: function(element, expression, index) { - element = $(element); - if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); - var nextSiblings = element.nextSiblings(); - return expression ? Selector.findElement(nextSiblings, expression, index) : - nextSiblings[index || 0]; - }, - - getElementsBySelector: function() { - var args = $A(arguments), element = $(args.shift()); - return Selector.findChildElements(element, args); - }, - - getElementsByClassName: function(element, className) { - return document.getElementsByClassName(className, element); - }, - - readAttribute: function(element, name) { - element = $(element); - if (Prototype.Browser.IE) { - if (!element.attributes) return null; - var t = Element._attributeTranslations; - if (t.values[name]) return t.values[name](element, name); - if (t.names[name]) name = t.names[name]; - var attribute = element.attributes[name]; - return attribute ? attribute.nodeValue : null; - } - return element.getAttribute(name); - }, - - getHeight: function(element) { - return $(element).getDimensions().height; - }, - - getWidth: function(element) { - return $(element).getDimensions().width; - }, - - classNames: function(element) { - return new Element.ClassNames(element); - }, - - hasClassName: function(element, className) { - if (!(element = $(element))) return; - var elementClassName = element.className; - if (elementClassName.length == 0) return false; - if (elementClassName == className || - elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) - return true; - return false; - }, - - addClassName: function(element, className) { - if (!(element = $(element))) return; - Element.classNames(element).add(className); - return element; - }, - - removeClassName: function(element, className) { - if (!(element = $(element))) return; - Element.classNames(element).remove(className); - return element; - }, - - toggleClassName: function(element, className) { - if (!(element = $(element))) return; - Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className); - return element; - }, - - observe: function() { - Event.observe.apply(Event, arguments); - return $A(arguments).first(); - }, - - stopObserving: function() { - Event.stopObserving.apply(Event, arguments); - return $A(arguments).first(); - }, - - // removes whitespace-only text node children - cleanWhitespace: function(element) { - element = $(element); - var node = element.firstChild; - while (node) { - var nextNode = node.nextSibling; - if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) - element.removeChild(node); - node = nextNode; - } - return element; - }, - - empty: function(element) { - return $(element).innerHTML.blank(); - }, - - descendantOf: function(element, ancestor) { - element = $(element), ancestor = $(ancestor); - while (element = element.parentNode) - if (element == ancestor) return true; - return false; - }, - - scrollTo: function(element) { - element = $(element); - var pos = Position.cumulativeOffset(element); - window.scrollTo(pos[0], pos[1]); - return element; - }, - - getStyle: function(element, style) { - element = $(element); - style = style == 'float' ? 'cssFloat' : style.camelize(); - var value = element.style[style]; - if (!value) { - var css = document.defaultView.getComputedStyle(element, null); - value = css ? css[style] : null; - } - if (style == 'opacity') return value ? parseFloat(value) : 1.0; - return value == 'auto' ? null : value; - }, - - getOpacity: function(element) { - return $(element).getStyle('opacity'); - }, - - setStyle: function(element, styles, camelized) { - element = $(element); - var elementStyle = element.style; - - for (var property in styles) - if (property == 'opacity') element.setOpacity(styles[property]) - else - elementStyle[(property == 'float' || property == 'cssFloat') ? - (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') : - (camelized ? property : property.camelize())] = styles[property]; - - return element; - }, - - setOpacity: function(element, value) { - element = $(element); - element.style.opacity = (value == 1 || value === '') ? '' : - (value < 0.00001) ? 0 : value; - return element; - }, - - getDimensions: function(element) { - element = $(element); - var display = $(element).getStyle('display'); - if (display != 'none' && display != null) // Safari bug - return {width: element.offsetWidth, height: element.offsetHeight}; - - // All *Width and *Height properties give 0 on elements with display none, - // so enable the element temporarily - var els = element.style; - var originalVisibility = els.visibility; - var originalPosition = els.position; - var originalDisplay = els.display; - els.visibility = 'hidden'; - els.position = 'absolute'; - els.display = 'block'; - var originalWidth = element.clientWidth; - var originalHeight = element.clientHeight; - els.display = originalDisplay; - els.position = originalPosition; - els.visibility = originalVisibility; - return {width: originalWidth, height: originalHeight}; - }, - - makePositioned: function(element) { - element = $(element); - var pos = Element.getStyle(element, 'position'); - if (pos == 'static' || !pos) { - element._madePositioned = true; - element.style.position = 'relative'; - // Opera returns the offset relative to the positioning context, when an - // element is position relative but top and left have not been defined - if (window.opera) { - element.style.top = 0; - element.style.left = 0; - } - } - return element; - }, - - undoPositioned: function(element) { - element = $(element); - if (element._madePositioned) { - element._madePositioned = undefined; - element.style.position = - element.style.top = - element.style.left = - element.style.bottom = - element.style.right = ''; - } - return element; - }, - - makeClipping: function(element) { - element = $(element); - if (element._overflow) return element; - element._overflow = element.style.overflow || 'auto'; - if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden') - element.style.overflow = 'hidden'; - return element; - }, - - undoClipping: function(element) { - element = $(element); - if (!element._overflow) return element; - element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; - element._overflow = null; - return element; - } -}; - -Object.extend(Element.Methods, { - childOf: Element.Methods.descendantOf, - childElements: Element.Methods.immediateDescendants -}); - -if (Prototype.Browser.Opera) { - Element.Methods._getStyle = Element.Methods.getStyle; - Element.Methods.getStyle = function(element, style) { - switch(style) { - case 'left': - case 'top': - case 'right': - case 'bottom': - if (Element._getStyle(element, 'position') == 'static') return null; - default: return Element._getStyle(element, style); - } - }; -} -else if (Prototype.Browser.IE) { - Element.Methods.getStyle = function(element, style) { - element = $(element); - style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); - var value = element.style[style]; - if (!value && element.currentStyle) value = element.currentStyle[style]; - - if (style == 'opacity') { - if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) - if (value[1]) return parseFloat(value[1]) / 100; - return 1.0; - } - - if (value == 'auto') { - if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none')) - return element['offset'+style.capitalize()] + 'px'; - return null; - } - return value; - }; - - Element.Methods.setOpacity = function(element, value) { - element = $(element); - var filter = element.getStyle('filter'), style = element.style; - if (value == 1 || value === '') { - style.filter = filter.replace(/alpha\([^\)]*\)/gi,''); - return element; - } else if (value < 0.00001) value = 0; - style.filter = filter.replace(/alpha\([^\)]*\)/gi, '') + - 'alpha(opacity=' + (value * 100) + ')'; - return element; - }; - - // IE is missing .innerHTML support for TABLE-related elements - Element.Methods.update = function(element, html) { - element = $(element); - html = typeof html == 'undefined' ? '' : html.toString(); - var tagName = element.tagName.toUpperCase(); - if (['THEAD','TBODY','TR','TD'].include(tagName)) { - var div = document.createElement('div'); - switch (tagName) { - case 'THEAD': - case 'TBODY': - div.innerHTML = '' + html.stripScripts() + '
'; - depth = 2; - break; - case 'TR': - div.innerHTML = '' + html.stripScripts() + '
'; - depth = 3; - break; - case 'TD': - div.innerHTML = '
' + html.stripScripts() + '
'; - depth = 4; - } - $A(element.childNodes).each(function(node) { element.removeChild(node) }); - depth.times(function() { div = div.firstChild }); - $A(div.childNodes).each(function(node) { element.appendChild(node) }); - } else { - element.innerHTML = html.stripScripts(); - } - setTimeout(function() { html.evalScripts() }, 10); - return element; - } -} -else if (Prototype.Browser.Gecko) { - Element.Methods.setOpacity = function(element, value) { - element = $(element); - element.style.opacity = (value == 1) ? 0.999999 : - (value === '') ? '' : (value < 0.00001) ? 0 : value; - return element; - }; -} - -Element._attributeTranslations = { - names: { - colspan: "colSpan", - rowspan: "rowSpan", - valign: "vAlign", - datetime: "dateTime", - accesskey: "accessKey", - tabindex: "tabIndex", - enctype: "encType", - maxlength: "maxLength", - readonly: "readOnly", - longdesc: "longDesc" - }, - values: { - _getAttr: function(element, attribute) { - return element.getAttribute(attribute, 2); - }, - _flag: function(element, attribute) { - return $(element).hasAttribute(attribute) ? attribute : null; - }, - style: function(element) { - return element.style.cssText.toLowerCase(); - }, - title: function(element) { - var node = element.getAttributeNode('title'); - return node.specified ? node.nodeValue : null; - } - } -}; - -(function() { - Object.extend(this, { - href: this._getAttr, - src: this._getAttr, - type: this._getAttr, - disabled: this._flag, - checked: this._flag, - readonly: this._flag, - multiple: this._flag - }); -}).call(Element._attributeTranslations.values); - -Element.Methods.Simulated = { - hasAttribute: function(element, attribute) { - var t = Element._attributeTranslations, node; - attribute = t.names[attribute] || attribute; - node = $(element).getAttributeNode(attribute); - return node && node.specified; - } -}; - -Element.Methods.ByTag = {}; - -Object.extend(Element, Element.Methods); - -if (!Prototype.BrowserFeatures.ElementExtensions && - document.createElement('div').__proto__) { - window.HTMLElement = {}; - window.HTMLElement.prototype = document.createElement('div').__proto__; - Prototype.BrowserFeatures.ElementExtensions = true; -} - -Element.hasAttribute = function(element, attribute) { - if (element.hasAttribute) return element.hasAttribute(attribute); - return Element.Methods.Simulated.hasAttribute(element, attribute); -}; - -Element.addMethods = function(methods) { - var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag; - - if (!methods) { - Object.extend(Form, Form.Methods); - Object.extend(Form.Element, Form.Element.Methods); - Object.extend(Element.Methods.ByTag, { - "FORM": Object.clone(Form.Methods), - "INPUT": Object.clone(Form.Element.Methods), - "SELECT": Object.clone(Form.Element.Methods), - "TEXTAREA": Object.clone(Form.Element.Methods) - }); - } - - if (arguments.length == 2) { - var tagName = methods; - methods = arguments[1]; - } - - if (!tagName) Object.extend(Element.Methods, methods || {}); - else { - if (tagName.constructor == Array) tagName.each(extend); - else extend(tagName); - } - - function extend(tagName) { - tagName = tagName.toUpperCase(); - if (!Element.Methods.ByTag[tagName]) - Element.Methods.ByTag[tagName] = {}; - Object.extend(Element.Methods.ByTag[tagName], methods); - } - - function copy(methods, destination, onlyIfAbsent) { - onlyIfAbsent = onlyIfAbsent || false; - var cache = Element.extend.cache; - for (var property in methods) { - var value = methods[property]; - if (!onlyIfAbsent || !(property in destination)) - destination[property] = cache.findOrStore(value); - } - } - - function findDOMClass(tagName) { - var klass; - var trans = { - "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph", - "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList", - "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading", - "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote", - "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION": - "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD": - "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR": - "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET": - "FrameSet", "IFRAME": "IFrame" - }; - if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; - if (window[klass]) return window[klass]; - klass = 'HTML' + tagName + 'Element'; - if (window[klass]) return window[klass]; - klass = 'HTML' + tagName.capitalize() + 'Element'; - if (window[klass]) return window[klass]; - - window[klass] = {}; - window[klass].prototype = document.createElement(tagName).__proto__; - return window[klass]; - } - - if (F.ElementExtensions) { - copy(Element.Methods, HTMLElement.prototype); - copy(Element.Methods.Simulated, HTMLElement.prototype, true); - } - - if (F.SpecificElementExtensions) { - for (var tag in Element.Methods.ByTag) { - var klass = findDOMClass(tag); - if (typeof klass == "undefined") continue; - copy(T[tag], klass.prototype); - } - } - - Object.extend(Element, Element.Methods); - delete Element.ByTag; -}; - -var Toggle = { display: Element.toggle }; - -/*--------------------------------------------------------------------------*/ - -Abstract.Insertion = function(adjacency) { - this.adjacency = adjacency; -} - -Abstract.Insertion.prototype = { - initialize: function(element, content) { - this.element = $(element); - this.content = content.stripScripts(); - - if (this.adjacency && this.element.insertAdjacentHTML) { - try { - this.element.insertAdjacentHTML(this.adjacency, this.content); - } catch (e) { - var tagName = this.element.tagName.toUpperCase(); - if (['TBODY', 'TR'].include(tagName)) { - this.insertContent(this.contentFromAnonymousTable()); - } else { - throw e; - } - } - } else { - this.range = this.element.ownerDocument.createRange(); - if (this.initializeRange) this.initializeRange(); - this.insertContent([this.range.createContextualFragment(this.content)]); - } - - setTimeout(function() {content.evalScripts()}, 10); - }, - - contentFromAnonymousTable: function() { - var div = document.createElement('div'); - div.innerHTML = '' + this.content + '
'; - return $A(div.childNodes[0].childNodes[0].childNodes); - } -} - -var Insertion = new Object(); - -Insertion.Before = Class.create(); -Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), { - initializeRange: function() { - this.range.setStartBefore(this.element); - }, - - insertContent: function(fragments) { - fragments.each((function(fragment) { - this.element.parentNode.insertBefore(fragment, this.element); - }).bind(this)); - } -}); - -Insertion.Top = Class.create(); -Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), { - initializeRange: function() { - this.range.selectNodeContents(this.element); - this.range.collapse(true); - }, - - insertContent: function(fragments) { - fragments.reverse(false).each((function(fragment) { - this.element.insertBefore(fragment, this.element.firstChild); - }).bind(this)); - } -}); - -Insertion.Bottom = Class.create(); -Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), { - initializeRange: function() { - this.range.selectNodeContents(this.element); - this.range.collapse(this.element); - }, - - insertContent: function(fragments) { - fragments.each((function(fragment) { - this.element.appendChild(fragment); - }).bind(this)); - } -}); - -Insertion.After = Class.create(); -Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), { - initializeRange: function() { - this.range.setStartAfter(this.element); - }, - - insertContent: function(fragments) { - fragments.each((function(fragment) { - this.element.parentNode.insertBefore(fragment, - this.element.nextSibling); - }).bind(this)); - } -}); - -/*--------------------------------------------------------------------------*/ - -Element.ClassNames = Class.create(); -Element.ClassNames.prototype = { - initialize: function(element) { - this.element = $(element); - }, - - _each: function(iterator) { - this.element.className.split(/\s+/).select(function(name) { - return name.length > 0; - })._each(iterator); - }, - - set: function(className) { - this.element.className = className; - }, - - add: function(classNameToAdd) { - if (this.include(classNameToAdd)) return; - this.set($A(this).concat(classNameToAdd).join(' ')); - }, - - remove: function(classNameToRemove) { - if (!this.include(classNameToRemove)) return; - this.set($A(this).without(classNameToRemove).join(' ')); - }, - - toString: function() { - return $A(this).join(' '); - } -}; - -Object.extend(Element.ClassNames.prototype, Enumerable); -/* Portions of the Selector class are derived from Jack Slocum’s DomQuery, - * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style - * license. Please see http://www.yui-ext.com/ for more information. */ - -var Selector = Class.create(); - -Selector.prototype = { - initialize: function(expression) { - this.expression = expression.strip(); - this.compileMatcher(); - }, - - compileMatcher: function() { - // Selectors with namespaced attributes can't use the XPath version - if (Prototype.BrowserFeatures.XPath && !(/\[[\w-]*?:/).test(this.expression)) - return this.compileXPathMatcher(); - - var e = this.expression, ps = Selector.patterns, h = Selector.handlers, - c = Selector.criteria, le, p, m; - - if (Selector._cache[e]) { - this.matcher = Selector._cache[e]; return; - } - this.matcher = ["this.matcher = function(root) {", - "var r = root, h = Selector.handlers, c = false, n;"]; - - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - p = ps[i]; - if (m = e.match(p)) { - this.matcher.push(typeof c[i] == 'function' ? c[i](m) : - new Template(c[i]).evaluate(m)); - e = e.replace(m[0], ''); - break; - } - } - } - - this.matcher.push("return h.unique(n);\n}"); - eval(this.matcher.join('\n')); - Selector._cache[this.expression] = this.matcher; - }, - - compileXPathMatcher: function() { - var e = this.expression, ps = Selector.patterns, - x = Selector.xpath, le, m; - - if (Selector._cache[e]) { - this.xpath = Selector._cache[e]; return; - } - - this.matcher = ['.//*']; - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - if (m = e.match(ps[i])) { - this.matcher.push(typeof x[i] == 'function' ? x[i](m) : - new Template(x[i]).evaluate(m)); - e = e.replace(m[0], ''); - break; - } - } - } - - this.xpath = this.matcher.join(''); - Selector._cache[this.expression] = this.xpath; - }, - - findElements: function(root) { - root = root || document; - if (this.xpath) return document._getElementsByXPath(this.xpath, root); - return this.matcher(root); - }, - - match: function(element) { - return this.findElements(document).include(element); - }, - - toString: function() { - return this.expression; - }, - - inspect: function() { - return "#"; - } -}; - -Object.extend(Selector, { - _cache: {}, - - xpath: { - descendant: "//*", - child: "/*", - adjacent: "/following-sibling::*[1]", - laterSibling: '/following-sibling::*', - tagName: function(m) { - if (m[1] == '*') return ''; - return "[local-name()='" + m[1].toLowerCase() + - "' or local-name()='" + m[1].toUpperCase() + "']"; - }, - className: "[contains(concat(' ', @class, ' '), ' #{1} ')]", - id: "[@id='#{1}']", - attrPresence: "[@#{1}]", - attr: function(m) { - m[3] = m[5] || m[6]; - return new Template(Selector.xpath.operators[m[2]]).evaluate(m); - }, - pseudo: function(m) { - var h = Selector.xpath.pseudos[m[1]]; - if (!h) return ''; - if (typeof h === 'function') return h(m); - return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m); - }, - operators: { - '=': "[@#{1}='#{3}']", - '!=': "[@#{1}!='#{3}']", - '^=': "[starts-with(@#{1}, '#{3}')]", - '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']", - '*=': "[contains(@#{1}, '#{3}')]", - '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]", - '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]" - }, - pseudos: { - 'first-child': '[not(preceding-sibling::*)]', - 'last-child': '[not(following-sibling::*)]', - 'only-child': '[not(preceding-sibling::* or following-sibling::*)]', - 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]", - 'checked': "[@checked]", - 'disabled': "[@disabled]", - 'enabled': "[not(@disabled)]", - 'not': function(m) { - var e = m[6], p = Selector.patterns, - x = Selector.xpath, le, m, v; - - var exclusion = []; - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in p) { - if (m = e.match(p[i])) { - v = typeof x[i] == 'function' ? x[i](m) : new Template(x[i]).evaluate(m); - exclusion.push("(" + v.substring(1, v.length - 1) + ")"); - e = e.replace(m[0], ''); - break; - } - } - } - return "[not(" + exclusion.join(" and ") + ")]"; - }, - 'nth-child': function(m) { - return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m); - }, - 'nth-last-child': function(m) { - return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m); - }, - 'nth-of-type': function(m) { - return Selector.xpath.pseudos.nth("position() ", m); - }, - 'nth-last-of-type': function(m) { - return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m); - }, - 'first-of-type': function(m) { - m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m); - }, - 'last-of-type': function(m) { - m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m); - }, - 'only-of-type': function(m) { - var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m); - }, - nth: function(fragment, m) { - var mm, formula = m[6], predicate; - if (formula == 'even') formula = '2n+0'; - if (formula == 'odd') formula = '2n+1'; - if (mm = formula.match(/^(\d+)$/)) // digit only - return '[' + fragment + "= " + mm[1] + ']'; - if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b - if (mm[1] == "-") mm[1] = -1; - var a = mm[1] ? Number(mm[1]) : 1; - var b = mm[2] ? Number(mm[2]) : 0; - predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " + - "((#{fragment} - #{b}) div #{a} >= 0)]"; - return new Template(predicate).evaluate({ - fragment: fragment, a: a, b: b }); - } - } - } - }, - - criteria: { - tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', - className: 'n = h.className(n, r, "#{1}", c); c = false;', - id: 'n = h.id(n, r, "#{1}", c); c = false;', - attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;', - attr: function(m) { - m[3] = (m[5] || m[6]); - return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m); - }, - pseudo: function(m) { - if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); - return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m); - }, - descendant: 'c = "descendant";', - child: 'c = "child";', - adjacent: 'c = "adjacent";', - laterSibling: 'c = "laterSibling";' - }, - - patterns: { - // combinators must be listed first - // (and descendant needs to be last combinator) - laterSibling: /^\s*~\s*/, - child: /^\s*>\s*/, - adjacent: /^\s*\+\s*/, - descendant: /^\s/, - - // selectors follow - tagName: /^\s*(\*|[\w\-]+)(\b|$)?/, - id: /^#([\w\-\*]+)(\b|$)/, - className: /^\.([\w\-\*]+)(\b|$)/, - pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/, - attrPresence: /^\[([\w]+)\]/, - attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/ - }, - - handlers: { - // UTILITY FUNCTIONS - // joins two collections - concat: function(a, b) { - for (var i = 0, node; node = b[i]; i++) - a.push(node); - return a; - }, - - // marks an array of nodes for counting - mark: function(nodes) { - for (var i = 0, node; node = nodes[i]; i++) - node._counted = true; - return nodes; - }, - - unmark: function(nodes) { - for (var i = 0, node; node = nodes[i]; i++) - node._counted = undefined; - return nodes; - }, - - // mark each child node with its position (for nth calls) - // "ofType" flag indicates whether we're indexing for nth-of-type - // rather than nth-child - index: function(parentNode, reverse, ofType) { - parentNode._counted = true; - if (reverse) { - for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { - node = nodes[i]; - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; - } - } else { - for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) - if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; - } - }, - - // filters out duplicates and extends all nodes - unique: function(nodes) { - if (nodes.length == 0) return nodes; - var results = [], n; - for (var i = 0, l = nodes.length; i < l; i++) - if (!(n = nodes[i])._counted) { - n._counted = true; - results.push(Element.extend(n)); - } - return Selector.handlers.unmark(results); - }, - - // COMBINATOR FUNCTIONS - descendant: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - h.concat(results, node.getElementsByTagName('*')); - return results; - }, - - child: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) { - for (var j = 0, children = [], child; child = node.childNodes[j]; j++) - if (child.nodeType == 1 && child.tagName != '!') results.push(child); - } - return results; - }, - - adjacent: function(nodes) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - var next = this.nextElementSibling(node); - if (next) results.push(next); - } - return results; - }, - - laterSibling: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - h.concat(results, Element.nextSiblings(node)); - return results; - }, - - nextElementSibling: function(node) { - while (node = node.nextSibling) - if (node.nodeType == 1) return node; - return null; - }, - - previousElementSibling: function(node) { - while (node = node.previousSibling) - if (node.nodeType == 1) return node; - return null; - }, - - // TOKEN FUNCTIONS - tagName: function(nodes, root, tagName, combinator) { - tagName = tagName.toUpperCase(); - var results = [], h = Selector.handlers; - if (nodes) { - if (combinator) { - // fastlane for ordinary descendant combinators - if (combinator == "descendant") { - for (var i = 0, node; node = nodes[i]; i++) - h.concat(results, node.getElementsByTagName(tagName)); - return results; - } else nodes = this[combinator](nodes); - if (tagName == "*") return nodes; - } - for (var i = 0, node; node = nodes[i]; i++) - if (node.tagName.toUpperCase() == tagName) results.push(node); - return results; - } else return root.getElementsByTagName(tagName); - }, - - id: function(nodes, root, id, combinator) { - var targetNode = $(id), h = Selector.handlers; - if (!nodes && root == document) return targetNode ? [targetNode] : []; - if (nodes) { - if (combinator) { - if (combinator == 'child') { - for (var i = 0, node; node = nodes[i]; i++) - if (targetNode.parentNode == node) return [targetNode]; - } else if (combinator == 'descendant') { - for (var i = 0, node; node = nodes[i]; i++) - if (Element.descendantOf(targetNode, node)) return [targetNode]; - } else if (combinator == 'adjacent') { - for (var i = 0, node; node = nodes[i]; i++) - if (Selector.handlers.previousElementSibling(targetNode) == node) - return [targetNode]; - } else nodes = h[combinator](nodes); - } - for (var i = 0, node; node = nodes[i]; i++) - if (node == targetNode) return [targetNode]; - return []; - } - return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : []; - }, - - className: function(nodes, root, className, combinator) { - if (nodes && combinator) nodes = this[combinator](nodes); - return Selector.handlers.byClassName(nodes, root, className); - }, - - byClassName: function(nodes, root, className) { - if (!nodes) nodes = Selector.handlers.descendant([root]); - var needle = ' ' + className + ' '; - for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) { - nodeClassName = node.className; - if (nodeClassName.length == 0) continue; - if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle)) - results.push(node); - } - return results; - }, - - attrPresence: function(nodes, root, attr) { - var results = []; - for (var i = 0, node; node = nodes[i]; i++) - if (Element.hasAttribute(node, attr)) results.push(node); - return results; - }, - - attr: function(nodes, root, attr, value, operator) { - if (!nodes) nodes = root.getElementsByTagName("*"); - var handler = Selector.operators[operator], results = []; - for (var i = 0, node; node = nodes[i]; i++) { - var nodeValue = Element.readAttribute(node, attr); - if (nodeValue === null) continue; - if (handler(nodeValue, value)) results.push(node); - } - return results; - }, - - pseudo: function(nodes, name, value, root, combinator) { - if (nodes && combinator) nodes = this[combinator](nodes); - if (!nodes) nodes = root.getElementsByTagName("*"); - return Selector.pseudos[name](nodes, value, root); - } - }, - - pseudos: { - 'first-child': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - if (Selector.handlers.previousElementSibling(node)) continue; - results.push(node); - } - return results; - }, - 'last-child': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - if (Selector.handlers.nextElementSibling(node)) continue; - results.push(node); - } - return results; - }, - 'only-child': function(nodes, value, root) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!h.previousElementSibling(node) && !h.nextElementSibling(node)) - results.push(node); - return results; - }, - 'nth-child': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root); - }, - 'nth-last-child': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, true); - }, - 'nth-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, false, true); - }, - 'nth-last-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, true, true); - }, - 'first-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, "1", root, false, true); - }, - 'last-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, "1", root, true, true); - }, - 'only-of-type': function(nodes, formula, root) { - var p = Selector.pseudos; - return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root); - }, - - // handles the an+b logic - getIndices: function(a, b, total) { - if (a == 0) return b > 0 ? [b] : []; - return $R(1, total).inject([], function(memo, i) { - if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i); - return memo; - }); - }, - - // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type - nth: function(nodes, formula, root, reverse, ofType) { - if (nodes.length == 0) return []; - if (formula == 'even') formula = '2n+0'; - if (formula == 'odd') formula = '2n+1'; - var h = Selector.handlers, results = [], indexed = [], m; - h.mark(nodes); - for (var i = 0, node; node = nodes[i]; i++) { - if (!node.parentNode._counted) { - h.index(node.parentNode, reverse, ofType); - indexed.push(node.parentNode); - } - } - if (formula.match(/^\d+$/)) { // just a number - formula = Number(formula); - for (var i = 0, node; node = nodes[i]; i++) - if (node.nodeIndex == formula) results.push(node); - } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b - if (m[1] == "-") m[1] = -1; - var a = m[1] ? Number(m[1]) : 1; - var b = m[2] ? Number(m[2]) : 0; - var indices = Selector.pseudos.getIndices(a, b, nodes.length); - for (var i = 0, node, l = indices.length; node = nodes[i]; i++) { - for (var j = 0; j < l; j++) - if (node.nodeIndex == indices[j]) results.push(node); - } - } - h.unmark(nodes); - h.unmark(indexed); - return results; - }, - - 'empty': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - // IE treats comments as element nodes - if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue; - results.push(node); - } - return results; - }, - - 'not': function(nodes, selector, root) { - var h = Selector.handlers, selectorType, m; - var exclusions = new Selector(selector).findElements(root); - h.mark(exclusions); - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!node._counted) results.push(node); - h.unmark(exclusions); - return results; - }, - - 'enabled': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!node.disabled) results.push(node); - return results; - }, - - 'disabled': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (node.disabled) results.push(node); - return results; - }, - - 'checked': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (node.checked) results.push(node); - return results; - } - }, - - operators: { - '=': function(nv, v) { return nv == v; }, - '!=': function(nv, v) { return nv != v; }, - '^=': function(nv, v) { return nv.startsWith(v); }, - '$=': function(nv, v) { return nv.endsWith(v); }, - '*=': function(nv, v) { return nv.include(v); }, - '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); }, - '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); } - }, - - matchElements: function(elements, expression) { - var matches = new Selector(expression).findElements(), h = Selector.handlers; - h.mark(matches); - for (var i = 0, results = [], element; element = elements[i]; i++) - if (element._counted) results.push(element); - h.unmark(matches); - return results; - }, - - findElement: function(elements, expression, index) { - if (typeof expression == 'number') { - index = expression; expression = false; - } - return Selector.matchElements(elements, expression || '*')[index || 0]; - }, - - findChildElements: function(element, expressions) { - var exprs = expressions.join(','), expressions = []; - exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { - expressions.push(m[1].strip()); - }); - var results = [], h = Selector.handlers; - for (var i = 0, l = expressions.length, selector; i < l; i++) { - selector = new Selector(expressions[i].strip()); - h.concat(results, selector.findElements(element)); - } - return (l > 1) ? h.unique(results) : results; - } -}); - -function $$() { - return Selector.findChildElements(document, $A(arguments)); -} -var Form = { - reset: function(form) { - $(form).reset(); - return form; - }, - - serializeElements: function(elements, getHash) { - var data = elements.inject({}, function(result, element) { - if (!element.disabled && element.name) { - var key = element.name, value = $(element).getValue(); - if (value != null) { - if (key in result) { - if (result[key].constructor != Array) result[key] = [result[key]]; - result[key].push(value); - } - else result[key] = value; - } - } - return result; - }); - - return getHash ? data : Hash.toQueryString(data); - } -}; - -Form.Methods = { - serialize: function(form, getHash) { - return Form.serializeElements(Form.getElements(form), getHash); - }, - - getElements: function(form) { - return $A($(form).getElementsByTagName('*')).inject([], - function(elements, child) { - if (Form.Element.Serializers[child.tagName.toLowerCase()]) - elements.push(Element.extend(child)); - return elements; - } - ); - }, - - getInputs: function(form, typeName, name) { - form = $(form); - var inputs = form.getElementsByTagName('input'); - - if (!typeName && !name) return $A(inputs).map(Element.extend); - - for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { - var input = inputs[i]; - if ((typeName && input.type != typeName) || (name && input.name != name)) - continue; - matchingInputs.push(Element.extend(input)); - } - - return matchingInputs; - }, - - disable: function(form) { - form = $(form); - Form.getElements(form).invoke('disable'); - return form; - }, - - enable: function(form) { - form = $(form); - Form.getElements(form).invoke('enable'); - return form; - }, - - findFirstElement: function(form) { - return $(form).getElements().find(function(element) { - return element.type != 'hidden' && !element.disabled && - ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); - }); - }, - - focusFirstElement: function(form) { - form = $(form); - form.findFirstElement().activate(); - return form; - }, - - request: function(form, options) { - form = $(form), options = Object.clone(options || {}); - - var params = options.parameters; - options.parameters = form.serialize(true); - - if (params) { - if (typeof params == 'string') params = params.toQueryParams(); - Object.extend(options.parameters, params); - } - - if (form.hasAttribute('method') && !options.method) - options.method = form.method; - - return new Ajax.Request(form.readAttribute('action'), options); - } -} - -/*--------------------------------------------------------------------------*/ - -Form.Element = { - focus: function(element) { - $(element).focus(); - return element; - }, - - select: function(element) { - $(element).select(); - return element; - } -} - -Form.Element.Methods = { - serialize: function(element) { - element = $(element); - if (!element.disabled && element.name) { - var value = element.getValue(); - if (value != undefined) { - var pair = {}; - pair[element.name] = value; - return Hash.toQueryString(pair); - } - } - return ''; - }, - - getValue: function(element) { - element = $(element); - var method = element.tagName.toLowerCase(); - return Form.Element.Serializers[method](element); - }, - - clear: function(element) { - $(element).value = ''; - return element; - }, - - present: function(element) { - return $(element).value != ''; - }, - - activate: function(element) { - element = $(element); - try { - element.focus(); - if (element.select && (element.tagName.toLowerCase() != 'input' || - !['button', 'reset', 'submit'].include(element.type))) - element.select(); - } catch (e) {} - return element; - }, - - disable: function(element) { - element = $(element); - element.blur(); - element.disabled = true; - return element; - }, - - enable: function(element) { - element = $(element); - element.disabled = false; - return element; - } -} - -/*--------------------------------------------------------------------------*/ - -var Field = Form.Element; -var $F = Form.Element.Methods.getValue; - -/*--------------------------------------------------------------------------*/ - -Form.Element.Serializers = { - input: function(element) { - switch (element.type.toLowerCase()) { - case 'checkbox': - case 'radio': - return Form.Element.Serializers.inputSelector(element); - default: - return Form.Element.Serializers.textarea(element); - } - }, - - inputSelector: function(element) { - return element.checked ? element.value : null; - }, - - textarea: function(element) { - return element.value; - }, - - select: function(element) { - return this[element.type == 'select-one' ? - 'selectOne' : 'selectMany'](element); - }, - - selectOne: function(element) { - var index = element.selectedIndex; - return index >= 0 ? this.optionValue(element.options[index]) : null; - }, - - selectMany: function(element) { - var values, length = element.length; - if (!length) return null; - - for (var i = 0, values = []; i < length; i++) { - var opt = element.options[i]; - if (opt.selected) values.push(this.optionValue(opt)); - } - return values; - }, - - optionValue: function(opt) { - // extend element because hasAttribute may not be native - return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; - } -} - -/*--------------------------------------------------------------------------*/ - -Abstract.TimedObserver = function() {} -Abstract.TimedObserver.prototype = { - initialize: function(element, frequency, callback) { - this.frequency = frequency; - this.element = $(element); - this.callback = callback; - - this.lastValue = this.getValue(); - this.registerCallback(); - }, - - registerCallback: function() { - setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); - }, - - onTimerEvent: function() { - var value = this.getValue(); - var changed = ('string' == typeof this.lastValue && 'string' == typeof value - ? this.lastValue != value : String(this.lastValue) != String(value)); - if (changed) { - this.callback(this.element, value); - this.lastValue = value; - } - } -} - -Form.Element.Observer = Class.create(); -Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { - getValue: function() { - return Form.Element.getValue(this.element); - } -}); - -Form.Observer = Class.create(); -Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { - getValue: function() { - return Form.serialize(this.element); - } -}); - -/*--------------------------------------------------------------------------*/ - -Abstract.EventObserver = function() {} -Abstract.EventObserver.prototype = { - initialize: function(element, callback) { - this.element = $(element); - this.callback = callback; - - this.lastValue = this.getValue(); - if (this.element.tagName.toLowerCase() == 'form') - this.registerFormCallbacks(); - else - this.registerCallback(this.element); - }, - - onElementEvent: function() { - var value = this.getValue(); - if (this.lastValue != value) { - this.callback(this.element, value); - this.lastValue = value; - } - }, - - registerFormCallbacks: function() { - Form.getElements(this.element).each(this.registerCallback.bind(this)); - }, - - registerCallback: function(element) { - if (element.type) { - switch (element.type.toLowerCase()) { - case 'checkbox': - case 'radio': - Event.observe(element, 'click', this.onElementEvent.bind(this)); - break; - default: - Event.observe(element, 'change', this.onElementEvent.bind(this)); - break; - } - } - } -} - -Form.Element.EventObserver = Class.create(); -Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { - getValue: function() { - return Form.Element.getValue(this.element); - } -}); - -Form.EventObserver = Class.create(); -Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { - getValue: function() { - return Form.serialize(this.element); - } -}); -if (!window.Event) { - var Event = new Object(); -} - -Object.extend(Event, { - KEY_BACKSPACE: 8, - KEY_TAB: 9, - KEY_RETURN: 13, - KEY_ESC: 27, - KEY_LEFT: 37, - KEY_UP: 38, - KEY_RIGHT: 39, - KEY_DOWN: 40, - KEY_DELETE: 46, - KEY_HOME: 36, - KEY_END: 35, - KEY_PAGEUP: 33, - KEY_PAGEDOWN: 34, - - element: function(event) { - return $(event.target || event.srcElement); - }, - - isLeftClick: function(event) { - return (((event.which) && (event.which == 1)) || - ((event.button) && (event.button == 1))); - }, - - pointerX: function(event) { - return event.pageX || (event.clientX + - (document.documentElement.scrollLeft || document.body.scrollLeft)); - }, - - pointerY: function(event) { - return event.pageY || (event.clientY + - (document.documentElement.scrollTop || document.body.scrollTop)); - }, - - stop: function(event) { - if (event.preventDefault) { - event.preventDefault(); - event.stopPropagation(); - } else { - event.returnValue = false; - event.cancelBubble = true; - } - }, - - // find the first node with the given tagName, starting from the - // node the event was triggered on; traverses the DOM upwards - findElement: function(event, tagName) { - var element = Event.element(event); - while (element.parentNode && (!element.tagName || - (element.tagName.toUpperCase() != tagName.toUpperCase()))) - element = element.parentNode; - return element; - }, - - observers: false, - - _observeAndCache: function(element, name, observer, useCapture) { - if (!this.observers) this.observers = []; - if (element.addEventListener) { - this.observers.push([element, name, observer, useCapture]); - element.addEventListener(name, observer, useCapture); - } else if (element.attachEvent) { - this.observers.push([element, name, observer, useCapture]); - element.attachEvent('on' + name, observer); - } - }, - - unloadCache: function() { - if (!Event.observers) return; - for (var i = 0, length = Event.observers.length; i < length; i++) { - Event.stopObserving.apply(this, Event.observers[i]); - Event.observers[i][0] = null; - } - Event.observers = false; - }, - - observe: function(element, name, observer, useCapture) { - element = $(element); - useCapture = useCapture || false; - - if (name == 'keypress' && - (Prototype.Browser.WebKit || element.attachEvent)) - name = 'keydown'; - - Event._observeAndCache(element, name, observer, useCapture); - }, - - stopObserving: function(element, name, observer, useCapture) { - element = $(element); - useCapture = useCapture || false; - - if (name == 'keypress' && - (Prototype.Browser.WebKit || element.attachEvent)) - name = 'keydown'; - - if (element.removeEventListener) { - element.removeEventListener(name, observer, useCapture); - } else if (element.detachEvent) { - try { - element.detachEvent('on' + name, observer); - } catch (e) {} - } - } -}); - -/* prevent memory leaks in IE */ -if (Prototype.Browser.IE) - Event.observe(window, 'unload', Event.unloadCache, false); -var Position = { - // set to true if needed, warning: firefox performance problems - // NOT neeeded for page scrolling, only if draggable contained in - // scrollable elements - includeScrollOffsets: false, - - // must be called before calling withinIncludingScrolloffset, every time the - // page is scrolled - prepare: function() { - this.deltaX = window.pageXOffset - || document.documentElement.scrollLeft - || document.body.scrollLeft - || 0; - this.deltaY = window.pageYOffset - || document.documentElement.scrollTop - || document.body.scrollTop - || 0; - }, - - realOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.scrollTop || 0; - valueL += element.scrollLeft || 0; - element = element.parentNode; - } while (element); - return [valueL, valueT]; - }, - - cumulativeOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - } while (element); - return [valueL, valueT]; - }, - - positionedOffset: function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - if (element) { - if(element.tagName=='BODY') break; - var p = Element.getStyle(element, 'position'); - if (p == 'relative' || p == 'absolute') break; - } - } while (element); - return [valueL, valueT]; - }, - - offsetParent: function(element) { - if (element.offsetParent) return element.offsetParent; - if (element == document.body) return element; - - while ((element = element.parentNode) && element != document.body) - if (Element.getStyle(element, 'position') != 'static') - return element; - - return document.body; - }, - - // caches x/y coordinate pair to use with overlap - within: function(element, x, y) { - if (this.includeScrollOffsets) - return this.withinIncludingScrolloffsets(element, x, y); - this.xcomp = x; - this.ycomp = y; - this.offset = this.cumulativeOffset(element); - - return (y >= this.offset[1] && - y < this.offset[1] + element.offsetHeight && - x >= this.offset[0] && - x < this.offset[0] + element.offsetWidth); - }, - - withinIncludingScrolloffsets: function(element, x, y) { - var offsetcache = this.realOffset(element); - - this.xcomp = x + offsetcache[0] - this.deltaX; - this.ycomp = y + offsetcache[1] - this.deltaY; - this.offset = this.cumulativeOffset(element); - - return (this.ycomp >= this.offset[1] && - this.ycomp < this.offset[1] + element.offsetHeight && - this.xcomp >= this.offset[0] && - this.xcomp < this.offset[0] + element.offsetWidth); - }, - - // within must be called directly before - overlap: function(mode, element) { - if (!mode) return 0; - if (mode == 'vertical') - return ((this.offset[1] + element.offsetHeight) - this.ycomp) / - element.offsetHeight; - if (mode == 'horizontal') - return ((this.offset[0] + element.offsetWidth) - this.xcomp) / - element.offsetWidth; - }, - - page: function(forElement) { - var valueT = 0, valueL = 0; - - var element = forElement; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - - // Safari fix - if (element.offsetParent == document.body) - if (Element.getStyle(element,'position')=='absolute') break; - - } while (element = element.offsetParent); - - element = forElement; - do { - if (!window.opera || element.tagName=='BODY') { - valueT -= element.scrollTop || 0; - valueL -= element.scrollLeft || 0; - } - } while (element = element.parentNode); - - return [valueL, valueT]; - }, - - clone: function(source, target) { - var options = Object.extend({ - setLeft: true, - setTop: true, - setWidth: true, - setHeight: true, - offsetTop: 0, - offsetLeft: 0 - }, arguments[2] || {}) - - // find page position of source - source = $(source); - var p = Position.page(source); - - // find coordinate system to use - target = $(target); - var delta = [0, 0]; - var parent = null; - // delta [0,0] will do fine with position: fixed elements, - // position:absolute needs offsetParent deltas - if (Element.getStyle(target,'position') == 'absolute') { - parent = Position.offsetParent(target); - delta = Position.page(parent); - } - - // correct by body offsets (fixes Safari) - if (parent == document.body) { - delta[0] -= document.body.offsetLeft; - delta[1] -= document.body.offsetTop; - } - - // set position - if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; - if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; - if(options.setWidth) target.style.width = source.offsetWidth + 'px'; - if(options.setHeight) target.style.height = source.offsetHeight + 'px'; - }, - - absolutize: function(element) { - element = $(element); - if (element.style.position == 'absolute') return; - Position.prepare(); - - var offsets = Position.positionedOffset(element); - var top = offsets[1]; - var left = offsets[0]; - var width = element.clientWidth; - var height = element.clientHeight; - - element._originalLeft = left - parseFloat(element.style.left || 0); - element._originalTop = top - parseFloat(element.style.top || 0); - element._originalWidth = element.style.width; - element._originalHeight = element.style.height; - - element.style.position = 'absolute'; - element.style.top = top + 'px'; - element.style.left = left + 'px'; - element.style.width = width + 'px'; - element.style.height = height + 'px'; - }, - - relativize: function(element) { - element = $(element); - if (element.style.position == 'relative') return; - Position.prepare(); - - element.style.position = 'relative'; - var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); - var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); - - element.style.top = top + 'px'; - element.style.left = left + 'px'; - element.style.height = element._originalHeight; - element.style.width = element._originalWidth; - } -} - -// Safari returns margins on body which is incorrect if the child is absolutely -// positioned. For performance reasons, redefine Position.cumulativeOffset for -// KHTML/WebKit only. -if (Prototype.Browser.WebKit) { - Position.cumulativeOffset = function(element) { - var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - if (element.offsetParent == document.body) - if (Element.getStyle(element, 'position') == 'absolute') break; - - element = element.offsetParent; - } while (element); - - return [valueL, valueT]; - } -} - -Element.addMethods(); \ No newline at end of file diff --git a/downloader/lib/.htaccess b/downloader/lib/.htaccess deleted file mode 100644 index 93169e4eb44..00000000000 --- a/downloader/lib/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -Order deny,allow -Deny from all diff --git a/downloader/lib/Mage/Archive.php b/downloader/lib/Mage/Archive.php deleted file mode 100644 index c0165f2f6dc..00000000000 --- a/downloader/lib/Mage/Archive.php +++ /dev/null @@ -1,222 +0,0 @@ - - */ -class Mage_Archive -{ - - /** - * Archiver is used for compress. - */ - const DEFAULT_ARCHIVER = 'gz'; - - /** - * Default packer for directory. - */ - const TAPE_ARCHIVER = 'tar'; - - /** - * Current archiver is used for compress. - * - * @var Mage_Archiver_Tar|Mage_Archiver_Gz|Mage_Archiver_Bz - */ - protected $_archiver=null; - - /** - * Accessible formats for compress. - * - * @var array - */ - protected $_formats = array( - 'tar' => 'tar', - 'gz' => 'gz', - 'gzip' => 'gz', - 'tgz' => 'tar.gz', - 'tgzip' => 'tar.gz', - 'bz' => 'bz', - 'bzip' => 'bz', - 'bzip2' => 'bz', - 'bz2' => 'bz', - 'tbz' => 'tar.bz', - 'tbzip' => 'tar.bz', - 'tbz2' => 'tar.bz', - 'tbzip2' => 'tar.bz'); - - /** - * Create object of current archiver by $extension. - * - * @param string $extension - * @return Mage_Archiver_Tar|Mage_Archiver_Gz|Mage_Archiver_Bz - */ - protected function _getArchiver($extension) - { - if(array_key_exists(strtolower($extension), $this->_formats)) { - $format = $this->_formats[$extension]; - } else { - $format = self::DEFAULT_ARCHIVER; - } - $class = 'Mage_Archive_' . ucfirst($format); - $this->_archiver = new $class(); - return $this->_archiver; - } - - /** - * Split current format to list of archivers. - * - * @param string $source - * @return array - */ - protected function _getArchivers($source) - { - $ext = pathinfo($source, PATHINFO_EXTENSION); - if(!isset($this->_formats[$ext])) { - return array(); - } - $format = $this->_formats[$ext]; - if ($format) { - $archivers = explode('.', $format); - return $archivers; - } - return array(); - } - - /** - * Pack file or directory to archivers are parsed from extension. - * - * @param string $source - * @param string $destination - * @param boolean $skipRoot skip first level parent - * @return string Path to file - */ - public function pack($source, $destination='packed.tgz', $skipRoot=false) - { - $archivers = $this->_getArchivers($destination); - $interimSource = ''; - for ($i=0; $i_getArchiver($archivers[$i])->pack($source, $packed, $skipRoot); - if ($interimSource && $i < count($archivers)) { - unlink($interimSource); - } - $interimSource = $source; - } - return $source; - } - - /** - * Unpack file from archivers are parsed from extension. - * If $tillTar == true unpack file from archivers till - * meet TAR archiver. - * - * @param string $source - * @param string $destination - * @param boolean $tillTar - * @return string Path to file - */ - public function unpack($source, $destination='.', $tillTar=false, $clearInterm = true) - { - $archivers = $this->_getArchivers($source); - $interimSource = ''; - for ($i=count($archivers)-1; $i>=0; $i--) { - if ($tillTar && $archivers[$i] == self::TAPE_ARCHIVER) { - break; - } - if ($i == 0) { - $packed = rtrim($destination, DS) . DS; - } else { - $packed = rtrim($destination, DS) . DS . '~tmp-'. microtime(true) . $archivers[$i-1] . '.' - . $archivers[$i-1]; - } - $source = $this->_getArchiver($archivers[$i])->unpack($source, $packed); - - //var_dump($packed, $source); - - if ($clearInterm && $interimSource && $i >= 0) { - unlink($interimSource); - } - $interimSource = $source; - } - return $source; - } - - /** - * Extract one file from TAR (Tape Archiver). - * - * @param string $file - * @param string $source - * @param string $destination - * @return string Path to file - */ - public function extract($file, $source, $destination='.') - { - $tarFile = $this->unpack($source, $destination, true); - $resFile = $this->_getArchiver(self::TAPE_ARCHIVER)->extract($file, $tarFile, $destination); - if (!$this->isTar($source)) { - unlink($tarFile); - } - return $resFile; - } - - /** - * Check file is archive. - * - * @param string $file - * @return boolean - */ - public function isArchive($file) - { - $archivers = $this->_getArchivers($file); - if (count($archivers)) { - return true; - } - return false; - } - - /** - * Check file is TAR. - * - * @param mixed $file - * @return boolean - */ - public function isTar($file) - { - $archivers = $this->_getArchivers($file); - if (count($archivers)==1 && $archivers[0] == self::TAPE_ARCHIVER) { - return true; - } - return false; - } -} diff --git a/downloader/lib/Mage/Archive/Abstract.php b/downloader/lib/Mage/Archive/Abstract.php deleted file mode 100644 index 07478a24f40..00000000000 --- a/downloader/lib/Mage/Archive/Abstract.php +++ /dev/null @@ -1,87 +0,0 @@ - - */ -class Mage_Archive_Abstract -{ - /** - * Write data to file. If file can't be opened - throw exception - * - * @param string $destination - * @param string $data - * @return boolean - * @throws Mage_Exception - */ - protected function _writeFile($destination, $data) - { - $destination = trim($destination); - if(false === file_put_contents($destination, $data)) { - throw new Mage_Exception("Can't write to file: " . $destination); - } - return true; - } - - /** - * Read data from file. If file can't be opened, throw to exception. - * - * @param string $source - * @return string - * @throws Mage_Exception - */ - protected function _readFile($source) - { - $data = ''; - if (is_file($source) && is_readable($source)) { - $data = @file_get_contents($source); - if ($data === false) { - throw new Mage_Exception("Can't get contents from: " . $source); - } - } - return $data; - } - - /** - * Get file name from source (URI) without last extension. - * - * @param string $source - * @param bool $withExtension - * @return mixed|string - */ - public function getFilename($source, $withExtension=false) - { - $file = str_replace(dirname($source) . DS, '', $source); - if (!$withExtension) { - $file = substr($file, 0, strrpos($file, '.')); - } - return $file; - } -} diff --git a/downloader/lib/Mage/Archive/Bz.php b/downloader/lib/Mage/Archive/Bz.php deleted file mode 100644 index 50e8486f854..00000000000 --- a/downloader/lib/Mage/Archive/Bz.php +++ /dev/null @@ -1,89 +0,0 @@ - - */ -class Mage_Archive_Bz extends Mage_Archive_Abstract implements Mage_Archive_Interface -{ - - /** - * Pack file by BZIP2 compressor. - * - * @param string $source - * @param string $destination - * @return string - */ - public function pack($source, $destination) - { - $fileReader = new Mage_Archive_Helper_File($source); - $fileReader->open('r'); - - $archiveWriter = new Mage_Archive_Helper_File_Bz($destination); - $archiveWriter->open('w'); - - while (!$fileReader->eof()) { - $archiveWriter->write($fileReader->read()); - } - - $fileReader->close(); - $archiveWriter->close(); - - return $destination; - } - - /** - * Unpack file by BZIP2 compressor. - * - * @param string $source - * @param string $destination - * @return string - */ - public function unpack($source, $destination) - { - if (is_dir($destination)) { - $file = $this->getFilename($source); - $destination = $destination . $file; - } - - $archiveReader = new Mage_Archive_Helper_File_Bz($source); - $archiveReader->open('r'); - - $fileWriter = new Mage_Archive_Helper_File($destination); - $fileWriter->open('w'); - - while (!$archiveReader->eof()) { - $fileWriter->write($archiveReader->read()); - } - - return $destination; - } - -} diff --git a/downloader/lib/Mage/Archive/Gz.php b/downloader/lib/Mage/Archive/Gz.php deleted file mode 100644 index 8286bd5f139..00000000000 --- a/downloader/lib/Mage/Archive/Gz.php +++ /dev/null @@ -1,87 +0,0 @@ - - */ -class Mage_Archive_Gz extends Mage_Archive_Abstract implements Mage_Archive_Interface -{ - /** - * Pack file by GZ compressor. - * - * @param string $source - * @param string $destination - * @return string - */ - public function pack($source, $destination) - { - $fileReader = new Mage_Archive_Helper_File($source); - $fileReader->open('r'); - - $archiveWriter = new Mage_Archive_Helper_File_Gz($destination); - $archiveWriter->open('wb9'); - - while (!$fileReader->eof()) { - $archiveWriter->write($fileReader->read()); - } - - $fileReader->close(); - $archiveWriter->close(); - - return $destination; - } - - /** - * Unpack file by GZ compressor. - * - * @param string $source - * @param string $destination - * @return string - */ - public function unpack($source, $destination) - { - if (is_dir($destination)) { - $file = $this->getFilename($source); - $destination = $destination . $file; - } - - $archiveReader = new Mage_Archive_Helper_File_Gz($source); - $archiveReader->open('r'); - - $fileWriter = new Mage_Archive_Helper_File($destination); - $fileWriter->open('w'); - - while (!$archiveReader->eof()) { - $fileWriter->write($archiveReader->read()); - } - - return $destination; - } -} diff --git a/downloader/lib/Mage/Archive/Helper/File.php b/downloader/lib/Mage/Archive/Helper/File.php deleted file mode 100644 index 92f75526ee1..00000000000 --- a/downloader/lib/Mage/Archive/Helper/File.php +++ /dev/null @@ -1,274 +0,0 @@ - -*/ -class Mage_Archive_Helper_File -{ - /** - * Full path to directory where file located - * - * @var string - */ - protected $_fileLocation; - - /** - * File name - * - * @var string - */ - protected $_fileName; - - /** - * Full path (directory + filename) to file - * - * @var string - */ - protected $_filePath; - - /** - * File permissions that will be set if file opened in write mode - * - * @var int - */ - protected $_chmod; - - /** - * File handler - * - * @var pointer - */ - protected $_fileHandler; - - /** - * Set file path via constructor - * - * @param string $filePath - */ - public function __construct($filePath) - { - $pathInfo = pathinfo($filePath); - - $this->_filePath = $filePath; - $this->_fileLocation = isset($pathInfo['dirname']) ? $pathInfo['dirname'] : ''; - $this->_fileName = isset($pathInfo['basename']) ? $pathInfo['basename'] : ''; - } - - /** - * Close file if it's not closed before object destruction - */ - public function __destruct() - { - if ($this->_fileHandler) { - $this->_close(); - } - } - - /** - * Open file - * - * @param string $mode - * @param int $chmod - * @throws Mage_Exception - */ - public function open($mode = 'w+', $chmod = 0666) - { - if ($this->_isWritableMode($mode)) { - if (!is_writable($this->_fileLocation)) { - throw new Mage_Exception('Permission denied to write to ' . $this->_fileLocation); - } - - if (is_file($this->_filePath) && !is_writable($this->_filePath)) { - throw new Mage_Exception("Can't open file " . $this->_fileName . " for writing. Permission denied."); - } - } - - if ($this->_isReadableMode($mode) && (!is_file($this->_filePath) || !is_readable($this->_filePath))) { - if (!is_file($this->_filePath)) { - throw new Mage_Exception('File ' . $this->_filePath . ' does not exist'); - } - - if (!is_readable($this->_filePath)) { - throw new Mage_Exception('Permission denied to read file ' . $this->_filePath); - } - } - - $this->_open($mode); - - $this->_chmod = $chmod; - } - - /** - * Write data to file - * - * @param string $data - */ - public function write($data) - { - $this->_checkFileOpened(); - $this->_write($data); - } - - /** - * Read data from file - * - * @param int $length - * @return string|boolean - */ - public function read($length = 4096) - { - $data = false; - $this->_checkFileOpened(); - if ($length > 0) { - $data = $this->_read($length); - } - - return $data; - } - - /** - * Check whether end of file reached - * - * @return boolean - */ - public function eof() - { - $this->_checkFileOpened(); - return $this->_eof(); - } - - /** - * Close file - */ - public function close() - { - $this->_checkFileOpened(); - $this->_close(); - $this->_fileHandler = false; - @chmod($this->_filePath, $this->_chmod); - } - - /** - * Implementation of file opening - * - * @param string $mode - * @throws Mage_Exception - */ - protected function _open($mode) - { - $this->_fileHandler = @fopen($this->_filePath, $mode); - - if (false === $this->_fileHandler) { - throw new Mage_Exception('Failed to open file ' . $this->_filePath); - } - } - - /** - * Implementation of writing data to file - * - * @param string $data - * @throws Mage_Exception - */ - protected function _write($data) - { - $result = @fwrite($this->_fileHandler, $data); - - if (false === $result) { - throw new Mage_Exception('Failed to write data to ' . $this->_filePath); - } - } - - /** - * Implementation of file reading - * - * @param int $length - * @throws Mage_Exception - */ - protected function _read($length) - { - $result = fread($this->_fileHandler, $length); - - if (false === $result) { - throw new Mage_Exception('Failed to read data from ' . $this->_filePath); - } - - return $result; - } - - /** - * Implementation of EOF indicator - * - * @return boolean - */ - protected function _eof() - { - return feof($this->_fileHandler); - } - - /** - * Implementation of file closing - */ - protected function _close() - { - fclose($this->_fileHandler); - } - - /** - * Check whether requested mode is writable mode - * - * @param string $mode - */ - protected function _isWritableMode($mode) - { - return preg_match('/(^[waxc])|(\+$)/', $mode); - } - - /** - * Check whether requested mode is readable mode - * - * @param string $mode - */ - protected function _isReadableMode($mode) { - return !$this->_isWritableMode($mode); - } - - /** - * Check whether file is opened - * - * @throws Mage_Exception - */ - protected function _checkFileOpened() - { - if (!$this->_fileHandler) { - throw new Mage_Exception('File not opened'); - } - } -} diff --git a/downloader/lib/Mage/Archive/Helper/File/Bz.php b/downloader/lib/Mage/Archive/Helper/File/Bz.php deleted file mode 100644 index 4dd0f763ac4..00000000000 --- a/downloader/lib/Mage/Archive/Helper/File/Bz.php +++ /dev/null @@ -1,92 +0,0 @@ - -*/ -class Mage_Archive_Helper_File_Bz extends Mage_Archive_Helper_File -{ - /** - * Open bz archive file - * - * @throws Mage_Exception - * @param string $mode - */ - protected function _open($mode) - { - $this->_fileHandler = @bzopen($this->_filePath, $mode); - - if (false === $this->_fileHandler) { - throw new Mage_Exception('Failed to open file ' . $this->_filePath); - } - } - - /** - * Write data to bz archive - * - * @throws Mage_Exception - * @param $data - */ - protected function _write($data) - { - $result = @bzwrite($this->_fileHandler, $data); - - if (false === $result) { - throw new Mage_Exception('Failed to write data to ' . $this->_filePath); - } - } - - /** - * Read data from bz archive - * - * @throws Mage_Exception - * @param int $length - * @return string - */ - protected function _read($length) - { - $data = bzread($this->_fileHandler, $length); - - if (false === $data) { - throw new Mage_Exception('Failed to read data from ' . $this->_filePath); - } - - return $data; - } - - /** - * Close bz archive - */ - protected function _close() - { - bzclose($this->_fileHandler); - } -} - diff --git a/downloader/lib/Mage/Archive/Helper/File/Gz.php b/downloader/lib/Mage/Archive/Helper/File/Gz.php deleted file mode 100644 index 37add5e6bfb..00000000000 --- a/downloader/lib/Mage/Archive/Helper/File/Gz.php +++ /dev/null @@ -1,98 +0,0 @@ - -*/ -class Mage_Archive_Helper_File_Gz extends Mage_Archive_Helper_File -{ - - /** - * Overwritten Mage_Archive_Helper_File constructor with zlib extension check - * @param string $filePath - * @throws Mage_Exception - */ - public function __construct($filePath) - { - if (!function_exists('gzopen')) { - throw new Mage_Exception('PHP Extensions "zlib" must be loaded.'); - } - - parent::__construct($filePath); - } - - /** - * @see Mage_Archive_Helper_File::_open() - */ - protected function _open($mode) - { - $this->_fileHandler = @gzopen($this->_filePath, $mode); - - if (false === $this->_fileHandler) { - throw new Mage_Exception('Failed to open file ' . $this->_filePath); - } - } - - /** - * @see Mage_Archive_Helper_File::_write() - */ - protected function _write($data) - { - $result = @gzwrite($this->_fileHandler, $data); - - if (empty($result) && !empty($data)) { - throw new Mage_Exception('Failed to write data to ' . $this->_filePath); - } - } - - /** - * @see Mage_Archive_Helper_File::_read() - */ - protected function _read($length) - { - return gzread($this->_fileHandler, $length); - } - - /** - * @see Mage_Archive_Helper_File::_eof() - */ - protected function _eof() - { - return gzeof($this->_fileHandler); - } - - /** - * @see Mage_Archive_Helper_File::_close() - */ - protected function _close() - { - gzclose($this->_fileHandler); - } -} diff --git a/downloader/lib/Mage/Archive/Interface.php b/downloader/lib/Mage/Archive/Interface.php deleted file mode 100644 index 05e3e93b32e..00000000000 --- a/downloader/lib/Mage/Archive/Interface.php +++ /dev/null @@ -1,53 +0,0 @@ - - */ -interface Mage_Archive_Interface -{ - /** - * Pack file or directory. - * - * @param string $source - * @param string $destination - * @return string - */ - public function pack($source, $destination); - - /** - * Unpack file or directory. - * - * @param string $source - * @param string $destination - * @return string - */ - public function unpack($source, $destination); -} diff --git a/downloader/lib/Mage/Archive/Tar.php b/downloader/lib/Mage/Archive/Tar.php deleted file mode 100644 index 5a2d350497d..00000000000 --- a/downloader/lib/Mage/Archive/Tar.php +++ /dev/null @@ -1,690 +0,0 @@ - - */ -class Mage_Archive_Tar extends Mage_Archive_Abstract implements Mage_Archive_Interface -{ - /** - * Tar block size - * - * @const int - */ - const TAR_BLOCK_SIZE = 512; - - /** - * Keep file or directory for packing. - * - * @var string - */ - protected $_currentFile; - - /** - * Keep path to file or directory for packing. - * - * @var mixed - */ - protected $_currentPath; - - /** - * Skip first level parent directory. Example: - * use test/fip.php instead test/test/fip.php; - * - * @var mixed - */ - protected $_skipRoot; - - /** - * Tarball data writer - * - * @var Mage_Archive_Helper_File - */ - protected $_writer; - - /** - * Tarball data reader - * - * @var Mage_Archive_Helper_File - */ - protected $_reader; - - /** - * Path to file where tarball should be placed - * - * @var string - */ - protected $_destinationFilePath; - - /** - * Initialize tarball writer - * - * @return Mage_Archive_Tar - */ - protected function _initWriter() - { - $this->_writer = new Mage_Archive_Helper_File($this->_destinationFilePath); - $this->_writer->open('w'); - - return $this; - } - - /** - * Returns string that is used for tar's header parsing - * - * Format codes were changed in 5.5.0 version. See http://php.net/manual/en/function.unpack.php - * - * @return string - */ - protected static final function _getFormatParseHeader() - { - if (version_compare(phpversion(), '5.5.0', '<') === true) { - return 'a100name/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100symlink/a6magic/a2version/' - . 'a32uname/a32gname/a8devmajor/a8devminor/a155prefix/a12closer'; - } - return 'Z100name/Z8mode/Z8uid/Z8gid/Z12size/Z12mtime/Z8checksum/Z1type/Z100symlink/Z6magic/Z2version/' - . 'Z32uname/Z32gname/Z8devmajor/Z8devminor/Z155prefix/Z12closer'; - } - - /** - * Destroy tarball writer - * - * @return Mage_Archive_Tar - */ - protected function _destroyWriter() - { - if ($this->_writer instanceof Mage_Archive_Helper_File) { - $this->_writer->close(); - $this->_writer = null; - } - - return $this; - } - - /** - * Get tarball writer - * - * @return Mage_Archive_Helper_File - */ - protected function _getWriter() - { - if (!$this->_writer) { - $this->_initWriter(); - } - - return $this->_writer; - } - - /** - * Initialize tarball reader - * - * @return Mage_Archive_Tar - */ - protected function _initReader() - { - $this->_reader = new Mage_Archive_Helper_File($this->_getCurrentFile()); - $this->_reader->open('r'); - - return $this; - } - - /** - * Destroy tarball reader - * - * @return Mage_Archive_Tar - */ - protected function _destroyReader() - { - if ($this->_reader instanceof Mage_Archive_Helper_File) { - $this->_reader->close(); - $this->_reader = null; - } - - return $this; - } - - /** - * Get tarball reader - * - * @return Mage_Archive_Helper_File - */ - protected function _getReader() - { - if (!$this->_reader) { - $this->_initReader(); - } - - return $this->_reader; - } - - /** - * Set option that define ability skip first catalog level. - * - * @param mixed $skipRoot - * @return Mage_Archive_Tar - */ - protected function _setSkipRoot($skipRoot) - { - $this->_skipRoot = $skipRoot; - return $this; - } - - /** - * Set file which is packing. - * - * @param string $file - * @return Mage_Archive_Tar - */ - protected function _setCurrentFile($file) - { - $this->_currentFile = $file .((!is_link($file) && is_dir($file) && substr($file, -1) != DS) ? DS : ''); - return $this; - } - - /** - * Set path to file where tarball should be placed - * - * @param string $destinationFilePath - * @return Mage_Archive_Tar - */ - protected function _setDestinationFilePath($destinationFilePath) - { - $this->_destinationFilePath = $destinationFilePath; - return $this; - } - - /** - * Retrieve file which is packing. - * - * @return string - */ - protected function _getCurrentFile() - { - return $this->_currentFile; - } - - /** - * Set path to file which is packing. - * - * @param string $path - * @return Mage_Archive_Tar - */ - protected function _setCurrentPath($path) - { - if ($this->_skipRoot && is_dir($path)) { - $this->_currentPath = $path.(substr($path, -1)!=DS?DS:''); - } else { - $this->_currentPath = dirname($path) . DS; - } - return $this; - } - - /** - * Retrieve path to file which is packing. - * - * @return string - */ - protected function _getCurrentPath() - { - return $this->_currentPath; - } - - /** - * Walk through directory and add to tar file or directory. - * Result is packed string on TAR format. - * - * @deprecated after 1.7.0.0 - * @param boolean $skipRoot - * @return string - */ - protected function _packToTar($skipRoot=false) - { - $file = $this->_getCurrentFile(); - $header = ''; - $data = ''; - if (!$skipRoot) { - $header = $this->_composeHeader(); - $data = $this->_readFile($file); - $data = str_pad($data, floor(((is_dir($file) ? 0 : filesize($file)) + 512 - 1) / 512) * 512, "\0"); - } - $sub = ''; - if (is_dir($file)) { - $treeDir = scandir($file); - if (empty($treeDir)) { - throw new Mage_Exception('Can\'t scan dir: ' . $file); - } - array_shift($treeDir); /* remove './'*/ - array_shift($treeDir); /* remove '../'*/ - foreach ($treeDir as $item) { - $sub .= $this->_setCurrentFile($file.$item)->_packToTar(false); - } - } - $tarData = $header . $data . $sub; - $tarData = str_pad($tarData, floor((strlen($tarData) - 1) / 1536) * 1536, "\0"); - return $tarData; - } - - /** - * Recursively walk through file tree and create tarball - * - * @param boolean $skipRoot - * @param boolean $finalize - * @throws Mage_Exception - */ - protected function _createTar($skipRoot = false, $finalize = false) - { - if (!$skipRoot) { - $this->_packAndWriteCurrentFile(); - } - - $file = $this->_getCurrentFile(); - - if (is_dir($file)) { - $dirFiles = scandir($file); - - if (false === $dirFiles) { - throw new Mage_Exception('Can\'t scan dir: ' . $file); - } - - array_shift($dirFiles); /* remove './'*/ - array_shift($dirFiles); /* remove '../'*/ - - foreach ($dirFiles as $item) { - $this->_setCurrentFile($file . $item)->_createTar(); - } - } - - if ($finalize) { - $this->_getWriter()->write(str_repeat("\0", self::TAR_BLOCK_SIZE * 12)); - } - } - - /** - * Write current file to tarball - */ - protected function _packAndWriteCurrentFile() - { - $archiveWriter = $this->_getWriter(); - $archiveWriter->write($this->_composeHeader()); - - $currentFile = $this->_getCurrentFile(); - - $fileSize = 0; - - if (is_file($currentFile) && !is_link($currentFile)) { - $fileReader = new Mage_Archive_Helper_File($currentFile); - $fileReader->open('r'); - - while (!$fileReader->eof()) { - $archiveWriter->write($fileReader->read()); - } - - $fileReader->close(); - - $fileSize = filesize($currentFile); - } - - $appendZerosCount = (self::TAR_BLOCK_SIZE - $fileSize % self::TAR_BLOCK_SIZE) % self::TAR_BLOCK_SIZE; - $archiveWriter->write(str_repeat("\0", $appendZerosCount)); - } - - /** - * Compose header for current file in TAR format. - * If length of file's name greater 100 characters, - * method breaks header into two pieces. First contains - * header and data with long name. Second contain only header. - * - * @param boolean $long - * @return string - */ - protected function _composeHeader($long = false) - { - $file = $this->_getCurrentFile(); - $path = $this->_getCurrentPath(); - $infoFile = stat($file); - $nameFile = str_replace($path, '', $file); - $nameFile = str_replace('\\', '/', $nameFile); - $packedHeader = ''; - $longHeader = ''; - if (!$long && strlen($nameFile)>100) { - $longHeader = $this->_composeHeader(true); - $longHeader .= str_pad($nameFile, floor((strlen($nameFile) + 512 - 1) / 512) * 512, "\0"); - } - $header = array(); - $header['100-name'] = $long?'././@LongLink':substr($nameFile, 0, 100); - $header['8-mode'] = $long ? ' ' - : str_pad(substr(sprintf("%07o", $infoFile['mode']),-4), 6, '0', STR_PAD_LEFT); - $header['8-uid'] = $long || $infoFile['uid']==0?"\0\0\0\0\0\0\0":sprintf("%07o", $infoFile['uid']); - $header['8-gid'] = $long || $infoFile['gid']==0?"\0\0\0\0\0\0\0":sprintf("%07o", $infoFile['gid']); - $header['12-size'] = $long ? sprintf("%011o", strlen($nameFile)) : sprintf("%011o", is_dir($file) - ? 0 : filesize($file)); - $header['12-mtime'] = $long?'00000000000':sprintf("%011o", $infoFile['mtime']); - $header['8-check'] = sprintf('% 8s', ''); - $header['1-type'] = $long ? 'L' : (is_link($file) ? 2 : (is_dir($file) ? 5 : 0)); - $header['100-symlink'] = is_link($file) ? readlink($file) : ''; - $header['6-magic'] = 'ustar '; - $header['2-version'] = ' '; - $a=function_exists('posix_getpwuid')?posix_getpwuid (fileowner($file)):array('name'=>''); - $header['32-uname'] = $a['name']; - $a=function_exists('posix_getgrgid')?posix_getgrgid (filegroup($file)):array('name'=>''); - $header['32-gname'] = $a['name']; - $header['8-devmajor'] = ''; - $header['8-devminor'] = ''; - $header['155-prefix'] = ''; - $header['12-closer'] = ''; - - $packedHeader = ''; - foreach ($header as $key=>$element) { - $length = explode('-', $key); - $packedHeader .= pack('a' . $length[0], $element); - } - - $checksum = 0; - for ($i = 0; $i < 512; $i++) { - $checksum += ord(substr($packedHeader, $i, 1)); - } - $packedHeader = substr_replace($packedHeader, sprintf("%07o", $checksum)."\0", 148, 8); - - return $longHeader . $packedHeader; - } - - /** - * Read TAR string from file, and unpacked it. - * Create files and directories information about discribed - * in the string. - * - * @param string $destination path to file is unpacked - * @return array list of files - * @throws Mage_Exception - */ - protected function _unpackCurrentTar($destination) - { - $archiveReader = $this->_getReader(); - $list = array(); - - while (!$archiveReader->eof()) { - $header = $this->_extractFileHeader(); - - if (!$header) { - continue; - } - - $currentFile = $destination . $header['name']; - $dirname = dirname($currentFile); - - if (in_array($header['type'], array("0",chr(0), ''))) { - - if(!file_exists($dirname)) { - $mkdirResult = @mkdir($dirname, 0777, true); - - if (false === $mkdirResult) { - throw new Mage_Exception('Failed to create directory ' . $dirname); - } - } - - $this->_extractAndWriteFile($header, $currentFile); - $list[] = $currentFile; - - } elseif ($header['type'] == '5') { - - if(!file_exists($dirname)) { - $mkdirResult = @mkdir($currentFile, $header['mode'], true); - - if (false === $mkdirResult) { - throw new Mage_Exception('Failed to create directory ' . $currentFile); - } - } - $list[] = $currentFile . DS; - } elseif ($header['type'] == '2') { - - //we do not interrupt unpack process if symlink creation failed as symlinks are not so important - @symlink($header['symlink'], $currentFile); - } - } - - return $list; - } - - /** - * Get header from TAR string and unpacked it by format. - * - * @deprecated after 1.7.0.0 - * @param resource $pointer - * @return string - */ - protected function _parseHeader(&$pointer) - { - $firstLine = fread($pointer, 512); - - if (strlen($firstLine)<512){ - return false; - } - - $fmt = self::_getFormatParseHeader(); - $header = unpack ($fmt, $firstLine); - - $header['mode']=$header['mode']+0; - $header['uid']=octdec($header['uid']); - $header['gid']=octdec($header['gid']); - $header['size']=octdec($header['size']); - $header['mtime']=octdec($header['mtime']); - $header['checksum']=octdec($header['checksum']); - - if ($header['type'] == "5") { - $header['size'] = 0; - } - - $checksum = 0; - $firstLine = substr_replace($firstLine, ' ', 148, 8); - for ($i = 0; $i < 512; $i++) { - $checksum += ord(substr($firstLine, $i, 1)); - } - - $isUstar = 'ustar' == strtolower(substr($header['magic'], 0, 5)); - - $checksumOk = $header['checksum'] == $checksum; - if (isset($header['name']) && $checksumOk) { - if ($header['name'] == '././@LongLink' && $header['type'] == 'L') { - $realName = substr(fread($pointer, floor(($header['size'] + 512 - 1) / 512) * 512), 0, $header['size']); - $headerMain = $this->_parseHeader($pointer); - $headerMain['name'] = $realName; - return $headerMain; - } else { - if ($header['size']>0) { - $header['data'] = substr(fread($pointer, floor(($header['size'] + 512 - 1) / 512) * 512), 0, $header['size']); - } else { - $header['data'] = ''; - } - return $header; - } - } - return false; - } - - /** - * Read and decode file header information from tarball - * - * @return array|boolean - */ - protected function _extractFileHeader() - { - $archiveReader = $this->_getReader(); - - $headerBlock = $archiveReader->read(self::TAR_BLOCK_SIZE); - - if (strlen($headerBlock) < self::TAR_BLOCK_SIZE) { - return false; - } - - $header = unpack(self::_getFormatParseHeader(), $headerBlock); - - $header['mode'] = octdec($header['mode']); - $header['uid'] = octdec($header['uid']); - $header['gid'] = octdec($header['gid']); - $header['size'] = octdec($header['size']); - $header['mtime'] = octdec($header['mtime']); - $header['checksum'] = octdec($header['checksum']); - - if ($header['type'] == "5") { - $header['size'] = 0; - } - - $checksum = 0; - $headerBlock = substr_replace($headerBlock, ' ', 148, 8); - - for ($i = 0; $i < 512; $i++) { - $checksum += ord(substr($headerBlock, $i, 1)); - } - - $checksumOk = $header['checksum'] == $checksum; - if (isset($header['name']) && $checksumOk) { - - if (!($header['name'] == '././@LongLink' && $header['type'] == 'L')) { - $header['name'] = trim($header['name']); - return $header; - } - - $realNameBlockSize = floor(($header['size'] + self::TAR_BLOCK_SIZE - 1) / self::TAR_BLOCK_SIZE) - * self::TAR_BLOCK_SIZE; - $realNameBlock = $archiveReader->read($realNameBlockSize); - $realName = substr($realNameBlock, 0, $header['size']); - - $headerMain = $this->_extractFileHeader(); - $headerMain['name'] = trim($realName); - return $headerMain; - } - - return false; - } - - /** - * Extract next file from tarball by its $header information and save it to $destination - * - * @param array $fileHeader - * @param string $destination - */ - protected function _extractAndWriteFile($fileHeader, $destination) - { - $fileWriter = new Mage_Archive_Helper_File($destination); - $fileWriter->open('w', $fileHeader['mode']); - - $archiveReader = $this->_getReader(); - - $filesize = $fileHeader['size']; - $bytesExtracted = 0; - - while ($filesize > $bytesExtracted && !$archiveReader->eof()) { - $block = $archiveReader->read(self::TAR_BLOCK_SIZE); - $nonExtractedBytesCount = $filesize - $bytesExtracted; - - $data = substr($block, 0, $nonExtractedBytesCount); - $fileWriter->write($data); - - $bytesExtracted += strlen($block); - } - } - - /** - * Pack file to TAR (Tape Archiver). - * - * @param string $source - * @param string $destination - * @param boolean $skipRoot - * @return string - */ - public function pack($source, $destination, $skipRoot = false) - { - $this->_setSkipRoot($skipRoot); - $source = realpath($source); - $tarData = $this->_setCurrentPath($source) - ->_setDestinationFilePath($destination) - ->_setCurrentFile($source); - - $this->_initWriter(); - $this->_createTar($skipRoot, true); - $this->_destroyWriter(); - - return $destination; - } - - /** - * Unpack file from TAR (Tape Archiver). - * - * @param string $source - * @param string $destination - * @return string - */ - public function unpack($source, $destination) - { - $this->_setCurrentFile($source) - ->_setCurrentPath($source); - - $this->_initReader(); - $this->_unpackCurrentTar($destination); - $this->_destroyReader(); - - return $destination; - } - - /** - * Extract one file from TAR (Tape Archiver). - * - * @param string $file - * @param string $source - * @param string $destination - * @return string - */ - public function extract($file, $source, $destination) - { - $this->_setCurrentFile($source); - $this->_initReader(); - - $archiveReader = $this->_getReader(); - $extractedFile = ''; - - while (!$archiveReader->eof()) { - $header = $this->_extractFileHeader(); - if ($header['name'] == $file) { - $extractedFile = $destination . basename($header['name']); - $this->_extractAndWriteFile($header, $extractedFile); - break; - } - - if ($header['type'] != 5){ - $skipBytes = floor(($header['size'] + self::TAR_BLOCK_SIZE - 1) / self::TAR_BLOCK_SIZE) - * self::TAR_BLOCK_SIZE; - $archiveReader->read($skipBytes); - } - } - - $this->_destroyReader(); - return $extractedFile; - } -} diff --git a/downloader/lib/Mage/Autoload/Simple.php b/downloader/lib/Mage/Autoload/Simple.php deleted file mode 100644 index 84a0b9d7300..00000000000 --- a/downloader/lib/Mage/Autoload/Simple.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -class Mage_Backup -{ - /** - * List of supported a backup types - * - * @var array - */ - static protected $_allowedBackupTypes = array('db', 'snapshot', 'filesystem', 'media', 'nomedia'); - - /** - * get Backup Instance By File Name - * - * @param string $type - * @return Mage_Backup_Interface - */ - static public function getBackupInstance($type) - { - $class = 'Mage_Backup_' . ucfirst($type); - - if (!in_array($type, self::$_allowedBackupTypes) || !class_exists($class, true)){ - throw new Mage_Exception('Current implementation not supported this type (' . $type . ') of backup.'); - } - - return new $class(); - } -} diff --git a/downloader/lib/Mage/Backup/Abstract.php b/downloader/lib/Mage/Backup/Abstract.php deleted file mode 100644 index c14e73bd9b0..00000000000 --- a/downloader/lib/Mage/Backup/Abstract.php +++ /dev/null @@ -1,318 +0,0 @@ - - */ -abstract class Mage_Backup_Abstract implements Mage_Backup_Interface -{ - /** - * Backup name - * - * @var string - */ - protected $_name; - - /** - * Backup creation date - * - * @var int - */ - protected $_time; - - /** - * Backup file extension - * - * @var string - */ - protected $_backupExtension; - - /** - * Resource model - * - * @var object - */ - protected $_resourceModel; - - /** - * Magento's root directory - * - * @var string - */ - protected $_rootDir; - - /** - * Path to directory where backups stored - * - * @var string - */ - protected $_backupsDir; - - /** - * Is last operation completed successfully - * - * @var bool - */ - protected $_lastOperationSucceed = false; - - /** - * Last failed operation error message - * - * @var string - */ - protected $_lastErrorMessage; - - - /** - * Set Backup Extension - * - * @param string $backupExtension - * @return Mage_Backup_Interface - */ - public function setBackupExtension($backupExtension) - { - $this->_backupExtension = $backupExtension; - return $this; - } - - /** - * Get Backup Extension - * - * @return string - */ - public function getBackupExtension() - { - return $this->_backupExtension; - } - - /** - * Set Resource Model - * - * @param object $resourceModel - * @return Mage_Backup_Interface - */ - public function setResourceModel($resourceModel) - { - $this->_resourceModel = $resourceModel; - return $this; - } - - /** - * Get Resource Model - * - * @return object - */ - public function getResourceModel() - { - return $this->_resourceModel; - } - - /** - * Set Time - * - * @param int $time - * @return Mage_Backup_Interface - */ - public function setTime($time) - { - $this->_time = $time; - return $this; - } - - /** - * Get Time - * - * @return int - */ - public function getTime() - { - return $this->_time; - } - - /** - * Set root directory of Magento installation - * - * @param string $rootDir - * @throws Mage_Exception - * @return Mage_Backup_Interface - */ - public function setRootDir($rootDir) - { - if (!is_dir($rootDir)) { - throw new Mage_Exception('Bad root directory'); - } - - $this->_rootDir = $rootDir; - return $this; - } - - /** - * Get Magento's root directory - * @return string - */ - public function getRootDir() - { - return $this->_rootDir; - } - - /** - * Set path to directory where backups stored - * - * @param string $backupsDir - * @return Mage_Backup_Interface - */ - public function setBackupsDir($backupsDir) - { - $this->_backupsDir = $backupsDir; - return $this; - } - - /** - * Get path to directory where backups stored - * - * @return string - */ - public function getBackupsDir() - { - return $this->_backupsDir; - } - - /** - * Get path to backup - * - * @return string - */ - public function getBackupPath() - { - return $this->getBackupsDir() . DS . $this->getBackupFilename(); - } - - /** - * Get backup file name - * - * @return string - */ - public function getBackupFilename() - { - $filename = $this->getTime() . '_' . $this->getType(); - - $name = $this->getName(); - - if (!empty($name)) { - $filename .= '_' . $name; - } - - $filename .= '.' . $this->getBackupExtension(); - - return $filename; - } - - /** - * Check whether last operation completed successfully - * - * @return bool - */ - public function getIsSuccess() - { - return $this->_lastOperationSucceed; - } - - /** - * Get last error message - * - * @return string - */ - public function getErrorMessage() - { - return $this->_lastErrorMessage; - } - - /** - * Set error message - * - * @param string $errorMessage - * @return string - */ - public function setErrorMessage($errorMessage) - { - $this->_lastErrorMessage = $errorMessage; - } - - /** - * Set backup name - * - * @param string $name - * @param bool $applyFilter - * @return Mage_Backup_Interface - */ - public function setName($name, $applyFilter = true) - { - if ($applyFilter) { - $name = $this->_filterName($name); - } - $this->_name = $name; - return $this; - } - - /** - * Get backup name - * - * @return string - */ - public function getName() - { - return $this->_name; - } - - /** - * Get backup display name - * - * @return string - */ - public function getDisplayName() - { - return str_replace('_', ' ', $this->_name); - } - - /** - * Removes disallowed characters and replaces spaces with underscores - * - * @param string $name - * @return string - */ - protected function _filterName($name) - { - $name = trim(preg_replace('/[^\da-zA-Z ]/', '', $name)); - $name = preg_replace('/\s{2,}/', ' ', $name); - $name = str_replace(' ', '_', $name); - - return $name; - } -} diff --git a/downloader/lib/Mage/Backup/Archive/Tar.php b/downloader/lib/Mage/Backup/Archive/Tar.php deleted file mode 100644 index c1e3a20b4e4..00000000000 --- a/downloader/lib/Mage/Backup/Archive/Tar.php +++ /dev/null @@ -1,82 +0,0 @@ - - */ -class Mage_Backup_Archive_Tar extends Mage_Archive_Tar -{ - /** - * Filenames or filename parts that are used for filtering files - * - * @var array() - */ - protected $_skipFiles = array(); - - /** - * Overridden Mage_Archive_Tar::_createTar method that does the same actions as it's parent but filters - * files using Mage_Backup_Filesystem_Iterator_Filter - * - * @see Mage_Archive_Tar::_createTar() - * @param bool $skipRoot - * @param bool $finalize - */ - protected function _createTar($skipRoot = false, $finalize = false) - { - $path = $this->_getCurrentFile(); - - $filesystemIterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST - ); - - $iterator = new Mage_Backup_Filesystem_Iterator_Filter($filesystemIterator, $this->_skipFiles); - - foreach ($iterator as $item) { - $this->_setCurrentFile($item->getPathname()); - $this->_packAndWriteCurrentFile(); - } - - if ($finalize) { - $this->_getWriter()->write(str_repeat("\0", self::TAR_BLOCK_SIZE * 12)); - } - } - - /** - * Set files that shouldn't be added to tarball - * - * @param array $skipFiles - * @return Mage_Backup_Archive_Tar - */ - public function setSkipFiles(array $skipFiles) - { - $this->_skipFiles = $skipFiles; - return $this; - } -} diff --git a/downloader/lib/Mage/Backup/Db.php b/downloader/lib/Mage/Backup/Db.php deleted file mode 100644 index f6333024885..00000000000 --- a/downloader/lib/Mage/Backup/Db.php +++ /dev/null @@ -1,119 +0,0 @@ - - */ -class Mage_Backup_Db extends Mage_Backup_Abstract -{ - /** - * Implements Rollback functionality for Db - * - * @return bool - */ - public function rollback() - { - set_time_limit(0); - ignore_user_abort(true); - - $this->_lastOperationSucceed = false; - - $archiveManager = new Mage_Archive(); - $source = $archiveManager->unpack($this->getBackupPath(), $this->getBackupsDir()); - - $file = new Mage_Backup_Filesystem_Iterator_File($source); - foreach ($file as $statement) { - $this->getResourceModel()->runCommand($statement); - } - @unlink($source); - - $this->_lastOperationSucceed = true; - - return true; - } - - /** - * Checks whether the line is last in sql command - * - * @param $line - * @return bool - */ - protected function _isLineLastInCommand($line) - { - $cleanLine = trim($line); - $lineLength = strlen($cleanLine); - - $returnResult = false; - if ($lineLength > 0){ - $lastSymbolIndex = $lineLength-1; - if ($cleanLine[$lastSymbolIndex] == ';'){ - $returnResult = true; - } - } - - return $returnResult; - } - - /** - * Implements Create Backup functionality for Db - * - * @return bool - */ - public function create() - { - set_time_limit(0); - ignore_user_abort(true); - - $this->_lastOperationSucceed = false; - - $backup = Mage::getModel('backup/backup') - ->setTime($this->getTime()) - ->setType($this->getType()) - ->setPath($this->getBackupsDir()) - ->setName($this->getName()); - - $backupDb = Mage::getModel('backup/db'); - $backupDb->createBackup($backup); - - $this->_lastOperationSucceed = true; - - return true; - } - - /** - * Get Backup Type - * - * @return string - */ - public function getType() - { - return 'db'; - } -} diff --git a/downloader/lib/Mage/Backup/Exception.php b/downloader/lib/Mage/Backup/Exception.php deleted file mode 100644 index bef1a1d8def..00000000000 --- a/downloader/lib/Mage/Backup/Exception.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class Mage_Backup_Exception extends Mage_Exception -{ -} diff --git a/downloader/lib/Mage/Backup/Exception/CantLoadSnapshot.php b/downloader/lib/Mage/Backup/Exception/CantLoadSnapshot.php deleted file mode 100644 index cd112d098ac..00000000000 --- a/downloader/lib/Mage/Backup/Exception/CantLoadSnapshot.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class Mage_Backup_Exception_CantLoadSnapshot extends Mage_Backup_Exception -{ -} diff --git a/downloader/lib/Mage/Backup/Exception/FtpConnectionFailed.php b/downloader/lib/Mage/Backup/Exception/FtpConnectionFailed.php deleted file mode 100644 index a0fa41ac324..00000000000 --- a/downloader/lib/Mage/Backup/Exception/FtpConnectionFailed.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class Mage_Backup_Exception_FtpConnectionFailed extends Mage_Backup_Exception -{ -} diff --git a/downloader/lib/Mage/Backup/Exception/FtpValidationFailed.php b/downloader/lib/Mage/Backup/Exception/FtpValidationFailed.php deleted file mode 100644 index d1eb04bf43d..00000000000 --- a/downloader/lib/Mage/Backup/Exception/FtpValidationFailed.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class Mage_Backup_Exception_FtpValidationFailed extends Mage_Backup_Exception -{ -} diff --git a/downloader/lib/Mage/Backup/Exception/NotEnoughFreeSpace.php b/downloader/lib/Mage/Backup/Exception/NotEnoughFreeSpace.php deleted file mode 100644 index 37a64e79795..00000000000 --- a/downloader/lib/Mage/Backup/Exception/NotEnoughFreeSpace.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class Mage_Backup_Exception_NotEnoughFreeSpace extends Mage_Backup_Exception -{ -} diff --git a/downloader/lib/Mage/Backup/Exception/NotEnoughPermissions.php b/downloader/lib/Mage/Backup/Exception/NotEnoughPermissions.php deleted file mode 100644 index 6db5b1b4946..00000000000 --- a/downloader/lib/Mage/Backup/Exception/NotEnoughPermissions.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class Mage_Backup_Exception_NotEnoughPermissions extends Mage_Backup_Exception -{ -} diff --git a/downloader/lib/Mage/Backup/Filesystem.php b/downloader/lib/Mage/Backup/Filesystem.php deleted file mode 100644 index aae5222d978..00000000000 --- a/downloader/lib/Mage/Backup/Filesystem.php +++ /dev/null @@ -1,284 +0,0 @@ - - */ -class Mage_Backup_Filesystem extends Mage_Backup_Abstract -{ - /** - * Paths that ignored when creating or rolling back snapshot - * - * @var array - */ - protected $_ignorePaths = array(); - - /** - * Whether use ftp account for rollback procedure - * - * @var bool - */ - protected $_useFtp = false; - - /** - * Ftp host - * - * @var string - */ - protected $_ftpHost; - - /** - * Ftp username - * - * @var string - */ - protected $_ftpUser; - - /** - * Password to ftp account - * - * @var string - */ - protected $_ftpPass; - - /** - * Ftp path to Magento installation - * - * @var string - */ - protected $_ftpPath; - - /** - * Implementation Rollback functionality for Filesystem - * - * @throws Mage_Exception - * @return bool - */ - public function rollback() - { - $this->_lastOperationSucceed = false; - - set_time_limit(0); - ignore_user_abort(true); - - $rollbackWorker = $this->_useFtp ? new Mage_Backup_Filesystem_Rollback_Ftp($this) - : new Mage_Backup_Filesystem_Rollback_Fs($this); - $rollbackWorker->run(); - - $this->_lastOperationSucceed = true; - } - - /** - * Implementation Create Backup functionality for Filesystem - * - * @throws Mage_Exception - * @return boolean - */ - public function create() - { - set_time_limit(0); - ignore_user_abort(true); - - $this->_lastOperationSucceed = false; - - $this->_checkBackupsDir(); - - $fsHelper = new Mage_Backup_Filesystem_Helper(); - - $filesInfo = $fsHelper->getInfo( - $this->getRootDir(), - Mage_Backup_Filesystem_Helper::INFO_READABLE | Mage_Backup_Filesystem_Helper::INFO_SIZE, - $this->getIgnorePaths() - ); - - if (!$filesInfo['readable']) { - throw new Mage_Backup_Exception_NotEnoughPermissions('Not enough permissions to read files for backup'); - } - - $freeSpace = disk_free_space($this->getBackupsDir()); - - if (2 * $filesInfo['size'] > $freeSpace) { - throw new Mage_Backup_Exception_NotEnoughFreeSpace('Not enough free space to create backup'); - } - - $tarTmpPath = $this->_getTarTmpPath(); - - $tarPacker = new Mage_Backup_Archive_Tar(); - $tarPacker->setSkipFiles($this->getIgnorePaths()) - ->pack($this->getRootDir(), $tarTmpPath, true); - - if (!is_file($tarTmpPath) || filesize($tarTmpPath) == 0) { - throw new Mage_Exception('Failed to create backup'); - } - - $backupPath = $this->getBackupPath(); - - $gzPacker = new Mage_Archive_Gz(); - $gzPacker->pack($tarTmpPath, $backupPath); - - if (!is_file($backupPath) || filesize($backupPath) == 0) { - throw new Mage_Exception('Failed to create backup'); - } - - @unlink($tarTmpPath); - - $this->_lastOperationSucceed = true; - } - - /** - * Force class to use ftp for rollback procedure - * - * @param string $host - * @param string $username - * @param string $password - * @param string $path - * @return Mage_Backup_Filesystem - */ - public function setUseFtp($host, $username, $password, $path) - { - $this->_useFtp = true; - $this->_ftpHost = $host; - $this->_ftpUser = $username; - $this->_ftpPass = $password; - $this->_ftpPath = $path; - return $this; - } - - /** - * Get backup type - * - * @see Mage_Backup_Interface::getType() - * @return string - */ - public function getType() - { - return 'filesystem'; - } - - /** - * Add path that should be ignoring when creating or rolling back backup - * - * @param string|array $paths - * @return Mage_Backup_Filesystem - */ - public function addIgnorePaths($paths) - { - if (is_string($paths)) { - if (!in_array($paths, $this->_ignorePaths)) { - $this->_ignorePaths[] = $paths; - } - } - else if (is_array($paths)) { - foreach ($paths as $path) { - $this->addIgnorePaths($path); - } - } - - return $this; - } - - /** - * Get paths that should be ignored while creating or rolling back backup procedure - * - * @return array - */ - public function getIgnorePaths() - { - return $this->_ignorePaths; - } - - /** - * Set directory where backups saved and add it to ignore paths - * - * @see Mage_Backup_Abstract::setBackupsDir() - * @param string $backupsDir - * @return Mage_Backup_Filesystem - */ - public function setBackupsDir($backupsDir) - { - parent::setBackupsDir($backupsDir); - $this->addIgnorePaths($backupsDir); - return $this; - } - - /** - * getter for $_ftpPath variable - * - * @return string - */ - public function getFtpPath() - { - return $this->_ftpPath; - } - - /** - * Get ftp connection string - * - * @return string - */ - public function getFtpConnectString() - { - return 'ftp://' . $this->_ftpUser . ':' . $this->_ftpPass . '@' . $this->_ftpHost . $this->_ftpPath; - } - - /** - * Check backups directory existance and whether it's writeable - * - * @throws Mage_Exception - */ - protected function _checkBackupsDir() - { - $backupsDir = $this->getBackupsDir(); - - if (!is_dir($backupsDir)) { - $backupsDirParentDirectory = basename($backupsDir); - - if (!is_writeable($backupsDirParentDirectory)) { - throw new Mage_Backup_Exception_NotEnoughPermissions('Cant create backups directory'); - } - - mkdir($backupsDir); - chmod($backupsDir, 0777); - } - - if (!is_writable($backupsDir)) { - throw new Mage_Backup_Exception_NotEnoughPermissions('Backups directory is not writeable'); - } - } - - /** - * Generate tmp name for tarball - */ - protected function _getTarTmpPath() - { - $tmpName = '~tmp-'. microtime(true) . '.tar'; - return $this->getBackupsDir() . DS . $tmpName; - } -} diff --git a/downloader/lib/Mage/Backup/Filesystem/Helper.php b/downloader/lib/Mage/Backup/Filesystem/Helper.php deleted file mode 100644 index c637825776d..00000000000 --- a/downloader/lib/Mage/Backup/Filesystem/Helper.php +++ /dev/null @@ -1,137 +0,0 @@ - - */ -class Mage_Backup_Filesystem_Helper -{ - /** - * Constant can be used in getInfo() function as second parameter. - * Check whether directory and all files/sub directories are writable - * - * @const int - */ - const INFO_WRITABLE = 1; - - /** - * Constant can be used in getInfo() function as second parameter. - * Check whether directory and all files/sub directories are readable - * - * @const int - */ - const INFO_READABLE = 2; - - /** - * Constant can be used in getInfo() function as second parameter. - * Get directory size - * - * @const int - */ - const INFO_SIZE = 4; - - /** - * Constant can be used in getInfo() function as second parameter. - * Combination of INFO_WRITABLE, INFO_READABLE, INFO_SIZE - * - * @const int - */ - const INFO_ALL = 7; - - /** - * Recursively delete $path - * - * @param string $path - * @param array $skipPaths - * @param bool $removeRoot - * @throws Mage_Exception - */ - public function rm($path, $skipPaths = array(), $removeRoot = false) - { - $filesystemIterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST - ); - - $iterator = new Mage_Backup_Filesystem_Iterator_Filter($filesystemIterator, $skipPaths); - - foreach ($iterator as $item) { - $item->isDir() ? @rmdir($item->__toString()) : @unlink($item->__toString()); - } - - if ($removeRoot && is_dir($path)) { - @rmdir($path); - } - } - - /** - * Get information (readable, writable, size) about $path - * - * @param string $path - * @param int $infoOptions - * @param array $skipFiles - */ - public function getInfo($path, $infoOptions = self::INFO_ALL, $skipFiles = array()) - { - $info = array(); - if ($infoOptions & self::INFO_READABLE) { - $info['readable'] = true; - } - - if ($infoOptions & self::INFO_WRITABLE) { - $info['writable'] = true; - } - - if ($infoOptions & self::INFO_SIZE) { - $info['size'] = 0; - } - - $filesystemIterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST - ); - - $iterator = new Mage_Backup_Filesystem_Iterator_Filter($filesystemIterator, $skipFiles); - - foreach ($iterator as $item) { - if (($infoOptions & self::INFO_WRITABLE) && !$item->isWritable()) { - $info['writable'] = false; - } - - if (($infoOptions & self::INFO_READABLE) && !$item->isReadable()) { - $info['readable'] = false; - } - - if ($infoOptions & self::INFO_SIZE && !$item->isDir()) { - $info['size'] += $item->getSize(); - } - } - - return $info; - } -} diff --git a/downloader/lib/Mage/Backup/Filesystem/Iterator/File.php b/downloader/lib/Mage/Backup/Filesystem/Iterator/File.php deleted file mode 100644 index bdc8739712f..00000000000 --- a/downloader/lib/Mage/Backup/Filesystem/Iterator/File.php +++ /dev/null @@ -1,112 +0,0 @@ - - */ -class Mage_Backup_Filesystem_Iterator_File extends SplFileObject -{ - /** - * The statement that was last read during iteration - * - * @var string - */ - protected $_currentStatement = ''; - - /** - * Return current sql statement - * - * @return string - */ - public function current() - { - return $this->_currentStatement; - } - - /** - * Iterate to next sql statement in file - */ - public function next() - { - $this->_currentStatement = ''; - while (!$this->eof()) { - $line = $this->fgets(); - if (strlen(trim($line))) { - $this->_currentStatement .= $line; - if ($this->_isLineLastInCommand($line)) { - break; - } - } - } - } - - /** - * Return to first statement - */ - public function rewind() - { - parent::rewind(); - $this->next(); - } - - /** - * Check whether provided string is comment - * - * @param string $line - * @return bool - */ - protected function _isComment($line) - { - return $line[0] == '#' || substr($line, 0, 2) == '--'; - } - - /** - * Check is line a last in sql command - * - * @param string $line - * @return bool - */ - protected function _isLineLastInCommand($line) - { - $cleanLine = trim($line); - $lineLength = strlen($cleanLine); - - $returnResult = false; - if ($lineLength > 0) { - $lastSymbolIndex = $lineLength - 1; - if ($cleanLine[$lastSymbolIndex] == ';') { - $returnResult = true; - } - } - - return $returnResult; - } -} diff --git a/downloader/lib/Mage/Backup/Filesystem/Iterator/Filter.php b/downloader/lib/Mage/Backup/Filesystem/Iterator/Filter.php deleted file mode 100644 index 1de96f7f1db..00000000000 --- a/downloader/lib/Mage/Backup/Filesystem/Iterator/Filter.php +++ /dev/null @@ -1,77 +0,0 @@ - - */ -class Mage_Backup_Filesystem_Iterator_Filter extends FilterIterator -{ - /** - * Array that is used for filtering - * - * @var array - */ - protected $_filters; - - /** - * Constructor - * - * @param Iterator $iterator - * @param array $filters list of files to skip - */ - public function __construct(Iterator $iterator, array $filters) - { - parent::__construct($iterator); - $this->_filters = $filters; - } - - /** - * Check whether the current element of the iterator is acceptable - * - * @return bool - */ - public function accept() - { - $current = $this->current()->__toString(); - $currentFilename = $this->current()->getFilename(); - - if ($currentFilename == '.' || $currentFilename == '..') { - return false; - } - - foreach ($this->_filters as $filter) { - if (false !== strpos($current, $filter)) { - return false; - } - } - - return true; - } -} diff --git a/downloader/lib/Mage/Backup/Filesystem/Rollback/Abstract.php b/downloader/lib/Mage/Backup/Filesystem/Rollback/Abstract.php deleted file mode 100644 index e131284ad7a..00000000000 --- a/downloader/lib/Mage/Backup/Filesystem/Rollback/Abstract.php +++ /dev/null @@ -1,57 +0,0 @@ - - */ -abstract class Mage_Backup_Filesystem_Rollback_Abstract -{ - /** - * Snapshot object - * - * @var Mage_Backup_Filesystem - */ - protected $_snapshot; - - /** - * Default worker constructor - * - * @param Mage_Backup_Filesystem $snapshotObject - */ - public function __construct(Mage_Backup_Filesystem $snapshotObject) - { - $this->_snapshot = $snapshotObject; - } - - /** - * Main worker's function that makes files rollback - */ - abstract public function run(); -} diff --git a/downloader/lib/Mage/Backup/Filesystem/Rollback/Fs.php b/downloader/lib/Mage/Backup/Filesystem/Rollback/Fs.php deleted file mode 100644 index 84d198cfe59..00000000000 --- a/downloader/lib/Mage/Backup/Filesystem/Rollback/Fs.php +++ /dev/null @@ -1,78 +0,0 @@ - - */ -class Mage_Backup_Filesystem_Rollback_Fs extends Mage_Backup_Filesystem_Rollback_Abstract -{ - /** - * Files rollback implementation via local filesystem - * - * @see Mage_Backup_Filesystem_Rollback_Abstract::run() - * @throws Mage_Exception - */ - public function run() - { - $snapshotPath = $this->_snapshot->getBackupPath(); - - if (!is_file($snapshotPath) || !is_readable($snapshotPath)) { - throw new Mage_Backup_Exception_CantLoadSnapshot('Cant load snapshot archive'); - } - - $fsHelper = new Mage_Backup_Filesystem_Helper(); - - $filesInfo = $fsHelper->getInfo( - $this->_snapshot->getRootDir(), - Mage_Backup_Filesystem_Helper::INFO_WRITABLE, - $this->_snapshot->getIgnorePaths() - ); - - if (!$filesInfo['writable']) { - throw new Mage_Backup_Exception_NotEnoughPermissions( - 'Unable to make rollback because not all files are writable' - ); - } - - $archiver = new Mage_Archive(); - - /** - * we need these fake initializations because all magento's files in filesystem will be deleted and autoloader - * wont be able to load classes that we need for unpacking - */ - new Mage_Archive_Tar(); - new Mage_Archive_Gz(); - new Mage_Archive_Helper_File(''); - new Mage_Archive_Helper_File_Gz(''); - - $fsHelper->rm($this->_snapshot->getRootDir(), $this->_snapshot->getIgnorePaths()); - $archiver->unpack($snapshotPath, $this->_snapshot->getRootDir()); - } -} diff --git a/downloader/lib/Mage/Backup/Filesystem/Rollback/Ftp.php b/downloader/lib/Mage/Backup/Filesystem/Rollback/Ftp.php deleted file mode 100644 index cff5824b1ac..00000000000 --- a/downloader/lib/Mage/Backup/Filesystem/Rollback/Ftp.php +++ /dev/null @@ -1,194 +0,0 @@ - - */ -class Mage_Backup_Filesystem_Rollback_Ftp extends Mage_Backup_Filesystem_Rollback_Abstract -{ - /** - * Ftp client - * - * @var Mage_System_Ftp - */ - protected $_ftpClient; - - /** - * Files rollback implementation via ftp - * - * @see Mage_Backup_Filesystem_Rollback_Abstract::run() - * @throws Mage_Exception - */ - public function run() - { - $snapshotPath = $this->_snapshot->getBackupPath(); - - if (!is_file($snapshotPath) || !is_readable($snapshotPath)) { - throw new Mage_Backup_Exception_CantLoadSnapshot('Cant load snapshot archive'); - } - - $this->_initFtpClient(); - $this->_validateFtp(); - - $tmpDir = $this->_createTmpDir(); - $this->_unpackSnapshot($tmpDir); - - $fsHelper = new Mage_Backup_Filesystem_Helper(); - - $this->_cleanupFtp(); - $this->_uploadBackupToFtp($tmpDir); - - $fsHelper->rm($tmpDir, array(), true); - } - - /** - * Initialize ftp client and connect to ftp - * - * @throws Mage_Backup_Exception_FtpConnectionFailed - */ - protected function _initFtpClient() - { - try { - $this->_ftpClient = new Mage_System_Ftp(); - $this->_ftpClient->connect($this->_snapshot->getFtpConnectString()); - } catch (Exception $e) { - throw new Mage_Backup_Exception_FtpConnectionFailed($e->getMessage()); - } - } - - /** - * Perform ftp validation. Check whether ftp account provided points to current magento installation - * - * @throws Mage_Exception - */ - protected function _validateFtp() - { - $validationFilename = '~validation-' . microtime(true) . '.tmp'; - $validationFilePath = $this->_snapshot->getBackupsDir() . DS . $validationFilename; - - $fh = @fopen($validationFilePath, 'w'); - @fclose($fh); - - if (!is_file($validationFilePath)) { - throw new Mage_Exception('Unable to validate ftp account'); - } - - $rootDir = $this->_snapshot->getRootDir(); - $ftpPath = $this->_snapshot->getFtpPath() . DS . str_replace($rootDir, '', $validationFilePath); - - $fileExistsOnFtp = $this->_ftpClient->fileExists($ftpPath); - @unlink($validationFilePath); - - if (!$fileExistsOnFtp) { - throw new Mage_Backup_Exception_FtpValidationFailed('Failed to validate ftp account'); - } - } - - /** - * Unpack snapshot - * - * @param string $tmpDir - */ - protected function _unpackSnapshot($tmpDir) - { - $snapshotPath = $this->_snapshot->getBackupPath(); - - $archiver = new Mage_Archive(); - $archiver->unpack($snapshotPath, $tmpDir); - } - - /** - * @throws Mage_Exception - * @return string - */ - protected function _createTmpDir() - { - $tmpDir = $this->_snapshot->getBackupsDir() . DS . '~tmp-' . microtime(true); - - $result = @mkdir($tmpDir); - - if (false === $result) { - throw new Mage_Backup_Exception_NotEnoughPermissions('Failed to create directory ' . $tmpDir); - } - - return $tmpDir; - } - - /** - * Delete magento and all files from ftp - */ - protected function _cleanupFtp() - { - $rootDir = $this->_snapshot->getRootDir(); - - $filesystemIterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($rootDir), RecursiveIteratorIterator::CHILD_FIRST - ); - - $iterator = new Mage_Backup_Filesystem_Iterator_Filter($filesystemIterator, $this->_snapshot->getIgnorePaths()); - - foreach ($iterator as $item) { - $ftpPath = $this->_snapshot->getFtpPath() . DS . str_replace($rootDir, '', $item->__toString()); - $ftpPath = str_replace(DS, '/', $ftpPath); - - $this->_ftpClient->delete($ftpPath); - } - } - - /** - * Perform files rollback - * - * @param string $tmpDir - * @throws Mage_Exception - */ - protected function _uploadBackupToFtp($tmpDir) - { - $filesystemIterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($tmpDir), RecursiveIteratorIterator::SELF_FIRST - ); - - $iterator = new Mage_Backup_Filesystem_Iterator_Filter($filesystemIterator, $this->_snapshot->getIgnorePaths()); - - foreach ($filesystemIterator as $item) { - $ftpPath = $this->_snapshot->getFtpPath() . DS . str_replace($tmpDir, '', $item->__toString()); - $ftpPath = str_replace(DS, '/', $ftpPath); - - if ($item->isDir()) { - $this->_ftpClient->mkdirRecursive($ftpPath); - } else { - $result = $this->_ftpClient->put($ftpPath, $item->__toString()); - if (false === $result) { - throw new Mage_Backup_Exception_NotEnoughPermissions('Failed to upload file ' - . $item->__toString() . ' to ftp'); - } - } - } - } -} diff --git a/downloader/lib/Mage/Backup/Interface.php b/downloader/lib/Mage/Backup/Interface.php deleted file mode 100644 index 958c7d0023a..00000000000 --- a/downloader/lib/Mage/Backup/Interface.php +++ /dev/null @@ -1,88 +0,0 @@ - - */ -interface Mage_Backup_Interface -{ - /** - * Create Backup - * - * @return boolean - */ - public function create(); - - /** - * Rollback Backup - * - * @return boolean - */ - public function rollback(); - - /** - * Set Backup Extension - * - * @param string $backupExtension - * @return Mage_Backup_Interface - */ - public function setBackupExtension($backupExtension); - - /** - * Set Resource Model - * - * @param object $resourceModel - * @return Mage_Backup_Interface - */ - public function setResourceModel($resourceModel); - - /** - * Set Time - * - * @param int $time - * @return Mage_Backup_Interface - */ - public function setTime($time); - - /** - * Get Backup Type - * - * @return string - */ - public function getType(); - - /** - * Set path to directory where backups stored - * - * @param string $backupsDir - * @return Mage_Backup_Interface - */ - public function setBackupsDir($backupsDir); -} diff --git a/downloader/lib/Mage/Backup/Media.php b/downloader/lib/Mage/Backup/Media.php deleted file mode 100644 index d44633687da..00000000000 --- a/downloader/lib/Mage/Backup/Media.php +++ /dev/null @@ -1,99 +0,0 @@ - - */ -class Mage_Backup_Media extends Mage_Backup_Snapshot -{ - /** - * Implementation Rollback functionality for Snapshot - * - * @throws Mage_Exception - * @return bool - */ - public function rollback() - { - $this->_prepareIgnoreList(); - return parent::rollback(); - } - - /** - * Implementation Create Backup functionality for Snapshot - * - * @throws Mage_Exception - * @return bool - */ - public function create() - { - $this->_prepareIgnoreList(); - return parent::create(); - } - - /** - * Overlap getType - * - * @return string - * @see Mage_Backup_Interface::getType() - */ - public function getType() - { - return 'media'; - } - - /** - * Add all folders and files except media and db backup to ignore list - * - * @return Mage_Backup_Media - */ - protected function _prepareIgnoreList() - { - $iterator = new DirectoryIterator($this->getRootDir()); - - foreach ($iterator as $item) { - $filename = $item->getFilename(); - if (!in_array($filename, array('media', 'var'))) { - $this->addIgnorePaths($item->getPathname()); - } - } - - $iterator = new DirectoryIterator($this->getRootDir() . DS . 'var'); - $dbBackupFilename = $this->_getDbBackupManager()->getBackupFilename(); - - foreach ($iterator as $item) { - $filename = $item->getFilename(); - if ($filename != $dbBackupFilename) { - $this->addIgnorePaths($item->getPathname()); - } - } - - return $this; - } -} diff --git a/downloader/lib/Mage/Backup/Nomedia.php b/downloader/lib/Mage/Backup/Nomedia.php deleted file mode 100644 index a57d561edaf..00000000000 --- a/downloader/lib/Mage/Backup/Nomedia.php +++ /dev/null @@ -1,82 +0,0 @@ - - */ -class Mage_Backup_Nomedia extends Mage_Backup_Snapshot -{ - /** - * Implementation Rollback functionality for Snapshot - * - * @throws Mage_Exception - * @return bool - */ - public function rollback() - { - $this->_prepareIgnoreList(); - return parent::rollback(); - } - - /** - * Implementation Create Backup functionality for Snapshot - * - * @throws Mage_Exception - * @return bool - */ - public function create() - { - $this->_prepareIgnoreList(); - return parent::create(); - } - - /** - * Overlap getType - * - * @return string - * @see Mage_Backup_Interface::getType() - */ - public function getType() - { - return 'nomedia'; - } - - /** - * Add media folder to ignore list - * - * @return Mage_Backup_Media - */ - protected function _prepareIgnoreList() - { - $this->addIgnorePaths($this->getRootDir() . DS . 'media'); - - return $this; - } -} diff --git a/downloader/lib/Mage/Backup/Snapshot.php b/downloader/lib/Mage/Backup/Snapshot.php deleted file mode 100644 index 160a2d5d67b..00000000000 --- a/downloader/lib/Mage/Backup/Snapshot.php +++ /dev/null @@ -1,140 +0,0 @@ - - */ -class Mage_Backup_Snapshot extends Mage_Backup_Filesystem -{ - /** - * Database backup manager - * - * @var Mage_Backup_Db - */ - protected $_dbBackupManager; - - /** - * Implementation Rollback functionality for Snapshot - * - * @throws Mage_Exception - * @return bool - */ - public function rollback() - { - $result = parent::rollback(); - - $this->_lastOperationSucceed = false; - - try { - $this->_getDbBackupManager()->rollback(); - } catch (Exception $e) { - $this->_removeDbBackup(); - throw $e; - } - - $this->_removeDbBackup(); - $this->_lastOperationSucceed = true; - - return $result; - } - - /** - * Implementation Create Backup functionality for Snapshot - * - * @throws Mage_Exception - * @return bool - */ - public function create() - { - $this->_getDbBackupManager()->create(); - - try { - $result = parent::create(); - } catch (Exception $e) { - $this->_removeDbBackup(); - throw $e; - } - - $this->_lastOperationSucceed = false; - $this->_removeDbBackup(); - $this->_lastOperationSucceed = true; - - return $result; - } - - /** - * Overlap getType - * - * @return string - * @see Mage_Backup_Interface::getType() - */ - public function getType() - { - return 'snapshot'; - } - - /** - * Create Db Instance - * - * @return Mage_Backup_Interface - */ - protected function _createDbBackupInstance() - { - return Mage_Backup::getBackupInstance(Mage_Backup_Helper_Data::TYPE_DB) - ->setBackupExtension(Mage::helper('backup')->getExtensionByType(Mage_Backup_Helper_Data::TYPE_DB)) - ->setTime($this->getTime()) - ->setBackupsDir(Mage::getBaseDir("var")) - ->setResourceModel($this->getResourceModel()); - } - - /** - * Get database backup manager - * - * @return Mage_Backup_Db - */ - protected function _getDbBackupManager() - { - if (is_null($this->_dbBackupManager)) { - $this->_dbBackupManager = $this->_createDbBackupInstance(); - } - - return $this->_dbBackupManager; - } - - /** - * Remove Db backup after added it to the snapshot - * - * @return Mage_Backup_Snapshot - */ - protected function _removeDbBackup(){ - @unlink($this->_getDbBackupManager()->getBackupPath()); - return $this; - } -} diff --git a/downloader/lib/Mage/Connect/Backup.php b/downloader/lib/Mage/Connect/Backup.php deleted file mode 100644 index 81cc26a70b2..00000000000 --- a/downloader/lib/Mage/Connect/Backup.php +++ /dev/null @@ -1,169 +0,0 @@ - - */ -class Mage_Connect_Backup -{ - /** - * Prefix for backuped files - * - * @var string - */ - protected $_prefix = '_backup_'; - - /** - * Array of available to overwrite type of files - * - * @var array - */ - protected $_fileTypes = array(); - - /** - * List of files to backup files - * - * @var array - */ - protected $_fileList = array(); - - /** - * Get available file types for backup - * - * @return array - */ - public function getFileTypes() - { - return $this->_fileTypes; - } - - /** - * Set available file types for backup - * - * @param array $types - */ - public function setFileTypes(array $types) - { - foreach ($types as $type) { - $this->_fileTypes[] = $type; - } - } - - /** - * Add file to files list for backup - * - * @param string $file - * @param string $rootPath - * @return void - */ - public function addFile($file, $rootPath) - { - $dest = $rootPath . DS . $file; - $type = $this->getFileType($file); - if (file_exists($dest) && in_array($type, $this->getFileTypes())) { - $this->_fileList[] = $file; - } - } - - /** - * Get count of files - * - * @return int - */ - public function getFilesCount() - { - return count($this->_fileList); - } - - /** - * Clear list of files - * - * @return void - */ - public function unsetAllFiles() - { - $this->_fileList = array(); - } - - /** - * Get list of files - * - * @return array - */ - public function getAllFiles() - { - return $this->_fileList; - } - - /** - * Run backup process - * - * @param boolean $cleanUpQueue - * @return void - */ - public function run($cleanUpQueue = false) - { - if ($this->getFilesCount() > 0) { - $fileList = $this->getAllFiles(); - foreach($fileList as $file) { - $this->_backupFile($file); - } - if ($cleanUpQueue) { - $this->unsetAllFiles(); - } - } - } - - /** - * Get File type - * - * @param string $file - * @return string - */ - public function getFileType($file) - { - return pathinfo($file, PATHINFO_EXTENSION); - } - - /** - * Backup file - * - * @param string $file - * @return void - */ - private function _backupFile($file) - { - $type = $this->getFileType($file); - if ($type && $type != '') { - $newName = $this->_prefix . time() . '.' . $type; - @rename($file, str_replace('.' . $type, $newName, $file)); - } - } -} diff --git a/downloader/lib/Mage/Connect/Channel/Generator.php b/downloader/lib/Mage/Connect/Channel/Generator.php deleted file mode 100644 index 6ba2fca37ad..00000000000 --- a/downloader/lib/Mage/Connect/Channel/Generator.php +++ /dev/null @@ -1,63 +0,0 @@ -_file = $file; - } - return $this; - } - - public function getFile() - { - return $this->_file; - } - - public function getGenerator() - { - if (is_null($this->_generator)) { - $this->_generator = new Mage_Xml_Generator(); - } - return $this->_generator; - } - - /** - * @param array $content - */ - public function save($content) - { - $xmlContent = $this->getGenerator() - ->arrayToXml($content) - ->save($this->getFile()); - return $this; - } -} diff --git a/downloader/lib/Mage/Connect/Channel/Parser.php b/downloader/lib/Mage/Connect/Channel/Parser.php deleted file mode 100644 index e7e108fca24..00000000000 --- a/downloader/lib/Mage/Connect/Channel/Parser.php +++ /dev/null @@ -1,25 +0,0 @@ - '', - 'uri' => '', - 'summary' => '', - ); - - public function rewind() { - reset($this->properties); - } - - public function valid() { - return current($this->properties) !== false; - } - - public function key() { - return key($this->properties); - } - - public function current() { - return current($this->properties); - } - - public function next() { - next($this->properties); - } - - public function __get($var) - { - if (isset($this->properties[$var])) { - return $this->properties[$var]; - } - return null; - } - - public function __set($var, $value) - { - if (is_string($value)) { - $value = trim($value); - } - if (isset($this->properties[$var])) { - if ($value === null) { - $value = ''; - } - $this->properties[$var] = $value; - } - } - - public function toArray() - { - return array('channel' => $this->properties); - } - - public function fromArray(array $arr) - { - foreach($arr as $k=>$v) { - $this->$k = $v; - } - } - - - private function validator() - { - if(is_null($this->_validator)) { - $this->_validator = new Mage_Connect_Validator(); - } - return $this->_validator; - } - - /** - Stub for validation result - */ - public function validate() - { - $v = $this->validator(); - if(!$v->validatePackageName($this->name)) { - return false; - } - return true; - } - -} diff --git a/downloader/lib/Mage/Connect/Command.php b/downloader/lib/Mage/Connect/Command.php deleted file mode 100644 index 0bd75c6bc60..00000000000 --- a/downloader/lib/Mage/Connect/Command.php +++ /dev/null @@ -1,463 +0,0 @@ - - */ -class Mage_Connect_Command -{ - /** - * All commands list - * @var array - */ - protected static $_commandsAll = array(); - - /** - * Commands list hash (key=class) - * @var array - */ - protected static $_commandsByClass = array(); - - /** - * Frontend object - * @var Mage_Connect_Fro - */ - protected static $_frontend = null; - - /** - * Connect Config instance - * @var Mage_Connect_Config - */ - protected static $_config = null; - /** - * Validator instance - * - * @var Mage_Connect_Validator - */ - protected static $_validator = null; - - /** - * Backup instance - * - * @var Mage_Connect_Backup - */ - protected static $_backup = null; - - /** - * Rest instance - * - * @var Mage_Connect_Rest - */ - protected static $_rest = null; - - /** - * Cache config instance - * - * @var Mage_Connect_Singleconfig - */ - protected static $_sconfig = null; - - /** - * Called class name - * - * @var string - */ - protected $_class; - - /** - * Packager instance - * - * @var Mage_Connect_Packager - */ - protected static $_packager = null; - - protected static $_return = array(); - - /** - * Constructor - */ - public function __construct() - { - $class = $this->_class = get_class($this); - if(__CLASS__ == $class) { - throw new Exception("You shouldn't instantiate {$class} directly!"); - } - $this->commandsInfo = self::$_commandsByClass[$class]; - } - - /** - * Get command info (static) - * - * @param string $name command name - * @return array|boolean - */ - public static function commandInfo($name) - { - $name = strtolower($name); - if(!isset(self::$_commandsAll[$name])) { - return false; - } - return self::$_commandsAll[$name]; - } - - /** - * Get command info for current command object - * - * @param string $name - * @return array|boolean - */ - public function getCommandInfo($name) - { - if(!isset(self::$_commandsByClass[$this->_class][$name])) { - return false; - } - return self::$_commandsByClass[$this->_class][$name]; - } - - /** - * Run command - * - * @param string $command - * @param string $options - * @param string $params - * @throws Exception if there's no needed method - * @return mixed - */ - public function run($command, $options, $params) - { - $data = $this->getCommandInfo($command); - $method = $data['function']; - if(! method_exists($this, $method)) { - throw new Exception("$method does't exist in class ".$this->_class); - } - return $this->$method($command, $options, $params); - } - - /** - * Static functions - */ - - /** - * Static - * @param $commandName - * @return unknown_type - */ - public static function getInstance($commandName) - { - if(!isset(self::$_commandsAll[$commandName])) { - throw new UnexpectedValueException("Cannot find command $commandName"); - } - $currentCommand = self::$_commandsAll[$commandName]; - return new $currentCommand['class'](); - } - - /** - * Cache config setter - * - * @static - * @param Mage_Connect_Singleconfig $obj - * @return null - */ - public static function setSconfig($obj) - { - self::$_sconfig = $obj; - } - - /** - * Cache config getter - * - * @return Mage_Connect_Singleconfig - */ - public function getSconfig() - { - return self::$_sconfig; - } - - /** - * Sets frontend object for all commands - * - * @param Mage_Connect_Frontend $obj - * @return null - */ - public static function setFrontendObject($obj) - { - self::$_frontend = $obj; - } - - /** - * Set config object for all commands - * - * @param Mage_Connect_Config $obj - * @return null - */ - public static function setConfigObject($obj) - { - self::$_config = $obj; - } - - /** - * Non-static getter for config - * - * @return Mage_Connect_Config - */ - public function config() - { - return self::$_config; - } - - /** - * Non-static getter for UI - * - * @return Mage_Connect_Frontend - */ - public function ui() - { - return self::$_frontend; - } - - /** - * Get validator object - * - * @return Mage_Connect_Validator - */ - public function validator() - { - if(is_null(self::$_validator)) { - self::$_validator = new Mage_Connect_Validator(); - } - return self::$_validator; - } - - /** - * Get backup object - * - * @return Mage_Connect_Backup - */ - public function backup() - { - if(is_null(self::$_backup)) { - self::$_backup = new Mage_Connect_Backup(); - } - return self::$_backup; - } - - /** - * Get rest object - * - * @return Mage_Connect_Rest - */ - public function rest() - { - if(is_null(self::$_rest)) { - self::$_rest = Mage_Connect_Rest_Builder::getAdapter(self::config()->protocol); - } - return self::$_rest; - } - - /** - * Get commands list sorted - * - * @return array - */ - public static function getCommands() - { - if(!count(self::$_commandsAll)) { - self::registerCommands(); - } - ksort(self::$_commandsAll); - return self::$_commandsAll; - } - - /** - * Get Getopt args from command definitions - * and parse them - * - * @param $command - * @return array - */ - public static function getGetoptArgs($command) - { - $commandInfo = self::commandInfo($command); - $short_args = ''; - $long_args = array(); - if (empty($commandInfo) || empty($commandInfo['options'])) { - return; - } - reset($commandInfo['options']); - while (list($option, $info) = each($commandInfo['options'])) { - $larg = $sarg = ''; - if (isset($info['arg'])) { - if ($info['arg'][0] == '(') { - $larg = '=='; - $sarg = '::'; - } else { - $larg = '='; - $sarg = ':'; - } - } - if (isset($info['shortopt'])) { - $short_args .= $info['shortopt'] . $sarg; - } - $long_args[] = $option . $larg; - } - return array($short_args, $long_args); - } - - /** - * Try to register commands automatically - * - * @return null - */ - public static function registerCommands() - { - $pathCommands = dirname(__FILE__).DIRECTORY_SEPARATOR.basename(__FILE__, ".php"); - $f = new DirectoryIterator($pathCommands); - foreach($f as $file) { - /** @var $file DirectoryIterator */ - if (! $file->isFile()) { - continue; - } - $pattern = preg_match("/(.*)_Header\.php/imsu", $file->getFilename(), $matches); - if(! $pattern) { - continue; - } - include($file->getPathname()); - if(! isset($commands)) { - continue; - } - $class = __CLASS__."_".$matches[1]; - foreach ($commands as $k=>$v) { - $commands[$k]['class'] = $class; - self::$_commandsAll[$k] = $commands[$k]; - } - self::$_commandsByClass[$class] = $commands; - } - } - - /** - * Add Error message - * - * @param string $command - * @param string $message - * @return null - */ - public function doError($command, $message) - { - return $this->ui()->doError($command, $message); - } - - /** - * Set command return - * - * @param string $key - * @param mixed $val - * @return null - */ - public static function setReturn($key, $val) - { - self::$_return[$key] = $val; - } - - /** - * Get command return - * - * @param $key - * @param $clear - * @return mixed - */ - public static function getReturn($key, $clear = true) - { - if(isset(self::$_return[$key])) { - $out = self::$_return[$key]; - if($clear) { - unset(self::$_return[$key]); - } - return $out; - } - return null; - } - - /** - * Cleanup command params from empty strings - * - * @param array $params by reference - */ - public function cleanupParams(array & $params) - { - $newParams = array(); - if(!count($params)) { - return; - } - foreach($params as $v) { - if(is_string($v)) { - $v = trim($v); - if(!strlen($v)) { - continue; - } - } - $newParams[] = $v; - } - $params = $newParams; - } - - /** - * Splits first command argument: channel/package - * to two arguments if found in top of array - * - * @param array $params - */ - public function splitPackageArgs(array & $params) - { - if(!count($params) || !isset($params[0])) { - return; - } - if($this->validator()->validateUrl($params[0])) { - return; - } - if(preg_match("@([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)@ims", $params[0], $subs)) { - $params[0] = $subs[2]; - array_unshift($params, $subs[1]); - } - } - - - /** - * Get packager instance - * - * @return Mage_Connect_Packager - */ - public function getPackager() - { - if(!self::$_packager) { - self::$_packager = new Mage_Connect_Packager(); - } - return self::$_packager; - } -} diff --git a/downloader/lib/Mage/Connect/Command/Channels.php b/downloader/lib/Mage/Connect/Command/Channels.php deleted file mode 100644 index 22f9e050f21..00000000000 --- a/downloader/lib/Mage/Connect/Command/Channels.php +++ /dev/null @@ -1,189 +0,0 @@ -getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - $data = $cache->getData(); - @unlink($config->getFilename()); - @unlink($cache->getFilename()); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - $data = $cache->getData(); - } - $out = array($command => array('data'=>$data, 'title'=>$title, 'title_aliases'=>$aliasT)); - $this->ui()->output($out); - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - /** - * channel-delete callback method - * @param string $command - * @param array $options - * @param array $params - */ - public function doDelete($command, $options, $params) - { - $this->cleanupParams($params); - try { - if(count($params) != 1) { - throw new Exception("Parameters count should be equal to 1"); - } - $packager = $this->getPackager(); - - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - $cache->deleteChannel($params[0]); - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } else { - $config = $this->config(); - $cache = $this->getSconfig(); - $cache->deleteChannel($params[0]); - } - $this->ui()->output("Successfully deleted"); - - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - /** - * Channel-add callback - * @param string $command - * @param array $options - * @param array $params - */ - public function doAdd($command, $options, $params) - { - $this->cleanupParams($params); - try { - if(count($params) != 1) { - throw new Exception("Parameters count should be equal to 1"); - } - $url = $params[0]; - $rest = $this->rest(); - $rest->setChannel($url); - $data = $rest->getChannelInfo(); - $data->url = $url; - - $packager = $this->getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - $cache->addChannel($data->name, $url); - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - $cache->addChannel($data->name, $url); - } - - $this->ui()->output("Successfully added: ".$url); - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - /** - * Get information about given channel callback - * @param string $command - * @param array $options - * @param array $params - */ - public function doInfo($command, $options, $params) - { - - } - - /** - * channel-alias - * @param $command - * @param $options - * @param $params - * @return unknown_type - */ - public function doAlias($command, $options, $params) - { - $this->cleanupParams($params); - try { - if(count($params) != 2) { - throw new Exception("Parameters count should be equal to 2"); - } - - $packager = $this->getPackager(); - $chanUrl = $params[0]; - $alias = $params[1]; - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - $cache->addChannelAlias($chanUrl, $alias); - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - $cache->addChannelAlias($chanUrl, $alias); - } - $this->ui()->output("Successfully added: ".$alias); - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - public function doLogin($command, $options, $params) - { - - } - - public function doLogout($command, $options, $params) - { - - } - -} diff --git a/downloader/lib/Mage/Connect/Command/Channels_Header.php b/downloader/lib/Mage/Connect/Command/Channels_Header.php deleted file mode 100644 index c257acaf560..00000000000 --- a/downloader/lib/Mage/Connect/Command/Channels_Header.php +++ /dev/null @@ -1,104 +0,0 @@ - array( - 'summary' => 'List Available Channels', - 'function' => 'doList', - 'shortcut' => 'lc', - 'options' => array(), - 'doc' => ' -List all available channels for installation. -', - ), - 'channel-delete' => array( - 'summary' => 'Remove a Channel From the List', - 'function' => 'doDelete', - 'shortcut' => 'cde', - 'options' => array(), - 'doc' => ' -Delete a channel from the registry. You may not -remove any channel that has installed packages. -' - ), - 'channel-add' => array( - 'summary' => 'Add a Channel', - 'function' => 'doAdd', - 'shortcut' => 'ca', - 'options' => array(), - 'doc' => ' -Add a private channel to the channel list. Note that all -public channels should be synced using "update-channels". -Parameter may be either a local file or remote URL to a -channel.xml. -' - ), - 'channel-info' => array( - 'summary' => 'Retrieve Information on a Channel', - 'function' => 'doInfo', - 'shortcut' => 'ci', - 'options' => array(), - 'doc' => ' -List the files in an installed package. -' - ), - 'channel-alias' => array( - 'summary' => 'Specify an alias to a channel name', - 'function' => 'doAlias', - 'shortcut' => 'cha', - 'options' => array(), - 'doc' => ' -Specify a specific alias to use for a channel name. -The alias may not be an existing channel name or -alias. -' - ), - 'channel-login' => array( - 'summary' => 'Connects and authenticates to remote channel server', - 'shortcut' => 'cli', - 'function' => 'doLogin', - 'options' => array(), - 'doc' => ' -Log in to a remote channel server. If is not supplied, -the default channel is used. To use remote functions in the installer -that require any kind of privileges, you need to log in first. The -username and password you enter here will be stored in your per-user -PEAR configuration (~/.pearrc on Unix-like systems). After logging -in, your username and password will be sent along in subsequent -operations on the remote server.', - ), - 'channel-logout' => array( - 'summary' => 'Logs out from the remote channel server', - 'shortcut' => 'clo', - 'function' => 'doLogout', - 'options' => array(), - 'doc' => ' -Logs out from a remote channel server. If is not supplied, -the default channel is used. This command does not actually connect to the -remote server, it only deletes the stored username and password from your user -configuration.', - ), - ); diff --git a/downloader/lib/Mage/Connect/Command/Config.php b/downloader/lib/Mage/Connect/Command/Config.php deleted file mode 100644 index 1e24cf67578..00000000000 --- a/downloader/lib/Mage/Connect/Command/Config.php +++ /dev/null @@ -1,216 +0,0 @@ - - */ -class Mage_Connect_Command_Config extends Mage_Connect_Command -{ - /** - * Parameters constants - */ - const PARAM_KEY = 0; - const PARAM_VAL = 1; - - /** - * Show config variable - * @param string $command - * @param array $options - * @param array $params - * @return void - */ - public function doConfigShow($command, $options, $params) - { - $this->cleanupParams($params); - - try { - $values = array(); - - $packager = $this->getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($config, $ftpObj) = $packager->getRemoteConfig($ftp); - } else { - $config = $this->config(); - } - foreach( $config as $k=>$v ) { - $values[$k] = $v; - } - if($ftp) { - @unlink($config->getFilename()); - } - $data = array($command => array('data'=>$values)); - $this->ui()->output($data); - } catch (Exception $e) { - if($ftp) { - @unlink($config->getFilename()); - } - return $this->doError($command, $e->getMessage()); - } - } - - /** - * Set config variable - * @param string $command - * @param array $options - * @param array $params - * @return void - */ - public function doConfigSet($command, $options, $params) - { - $this->cleanupParams($params); - - try { - if(count($params) < 2) { - throw new Exception("Parameters count should be >= 2"); - } - $key = strtolower($params[self::PARAM_KEY]); - $val = strval($params[self::PARAM_VAL]); - $packager = $this->getPackager(); - - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if(!$ftp) { - $config = $this->config(); - $ftp=$config->remote_config; - } - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } - - if(!$config->hasKey($key)) { - throw new Exception ("No such config variable: {$key}!"); - } - if(!$config->validate($key, $val)) { - $possible = $this->config()->possible($key); - $type = $this->config()->type($key); - $errString = "Invalid value specified for $key!"; - throw new Exception($errString); - } - if($ftp) { - $packager->writeToRemoteConfig($config, $ftpObj); - } - $this->config()->$key = $val; - $this->ui()->output('Success'); - } catch (Exception $e) { - if($ftp) { - @unlink($config->getFilename()); - } - return $this->doError($command, $e->getMessage()); - } - } - - /** - * Get config var - * @param string $command - * @param array $options - * @param array $params - * @return void - */ - public function doConfigGet($command, $options, $params) - { - $this->cleanupParams($params); - - try { - if(count($params) < 1) { - throw new Exception("Parameters count should be >= 1"); - } - $packager = $this->getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($config, $ftpObj) = $packager->getRemoteConfig($ftp); - } else { - $config = $this->config(); - } - $key = strtolower($params[self::PARAM_KEY]); - if(!$config->hasKey($key)) { - throw new Exception("No such config variable '{$key}'!"); - } - if($ftp) { - @unlink($config->getFilename()); - } - $this->ui()->output($config->$key); - } catch (Exception $e) { - if($ftp) { - @unlink($config->getFilename()); - } - return $this->doError($command, $e->getMessage()); - } - } - - /** - * Config help - * @param string $command - * @param array $options - * @param array $params - * @return void - */ - public function doConfigHelp($command, $options, $params) - { - try { - $this->cleanupParams($params); - if(count($params) < 1) { - throw new Exception( "Parameters count should be >= 1"); - } - $packager = $this->getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($config, $ftpObj) = $packager->getRemoteConfig($ftp); - } else { - $config = $this->config(); - } - - $key = strtolower($params[self::PARAM_KEY]); - if(!$this->config()->hasKey($key)) { - throw new Exception("No such config variable '{$key}'!"); - } - - $possible = $config->possible($key); - $type = $config->type($key); - $doc = $config->doc($key); - if($ftp) { - @unlink($config->getFilename()); - } - $data = array(); - $data[$command]['data'] = array( - 'name' => array('Variable name', $key), - 'type' => array('Value type', $type), - 'possible' => array('Possible values', $possible), - 'doc' => $doc, - ); - $this->ui()->output($data); - } catch (Exception $e) { - if($ftp) { - @unlink($config->getFilename()); - } - return $this->doError($command, $e->getMessage()); - } - } -} diff --git a/downloader/lib/Mage/Connect/Command/Config_Header.php b/downloader/lib/Mage/Connect/Command/Config_Header.php deleted file mode 100644 index 2f1f5ee29d9..00000000000 --- a/downloader/lib/Mage/Connect/Command/Config_Header.php +++ /dev/null @@ -1,100 +0,0 @@ - array( - 'summary' => 'Show All Settings', - 'function' => 'doConfigShow', - 'shortcut' => 'csh', - 'options' => array( - 'channel' => array( - 'shortopt' => 'c', - 'doc' => 'show configuration variables for another channel', - 'arg' => 'CHAN', -), -), - 'doc' => '[layer] -Displays all configuration values. An optional argument -may be used to tell which configuration layer to display. Valid -configuration layers are "user", "system" and "default". To display -configurations for different channels, set the default_channel -configuration variable and run config-show again. -', -), - 'config-get' => array( - 'summary' => 'Show One Setting', - 'function' => 'doConfigGet', - 'shortcut' => 'cg', - 'options' => array( - 'channel' => array( - 'shortopt' => 'c', - 'doc' => 'show configuration variables for another channel', - 'arg' => 'CHAN', -), -), - 'doc' => ' [layer] -Displays the value of one configuration parameter. The -first argument is the name of the parameter, an optional second argument -may be used to tell which configuration layer to look in. Valid configuration -layers are "user", "system" and "default". If no layer is specified, a value -will be picked from the first layer that defines the parameter, in the order -just specified. The configuration value will be retrieved for the channel -specified by the default_channel configuration variable. -', -), - 'config-set' => array( - 'summary' => 'Change Setting', - 'function' => 'doConfigSet', - 'shortcut' => 'cs', - 'options' => array( - 'channel' => array( - 'shortopt' => 'c', - 'doc' => 'show configuration variables for another channel', - 'arg' => 'CHAN', -), -), - 'doc' => ' [layer] -Sets the value of one configuration parameter. The first argument is -the name of the parameter, the second argument is the new value. Some -parameters are subject to validation, and the command will fail with -an error message if the new value does not make sense. An optional -third argument may be used to specify in which layer to set the -configuration parameter. The default layer is "user". The -configuration value will be set for the current channel, which -is controlled by the default_channel configuration variable. -', -), - 'config-help' => array( - 'summary' => 'Show Information About Setting', - 'function' => 'doConfigHelp', - 'shortcut' => 'ch', - 'options' => array(), - 'doc' => '[parameter] -Displays help for a configuration parameter. Without arguments it -displays help for all configuration parameters. -', -), -); diff --git a/downloader/lib/Mage/Connect/Command/Install.php b/downloader/lib/Mage/Connect/Command/Install.php deleted file mode 100644 index 65c804828ba..00000000000 --- a/downloader/lib/Mage/Connect/Command/Install.php +++ /dev/null @@ -1,568 +0,0 @@ -cleanupParams($params); - - $installFileMode = $command === 'install-file'; - - /** @var $ftpObj Mage_Connect_Ftp */ - $ftpObj=null; - $ftp = empty($options['ftp']) ? false : $options['ftp']; - /** @var $packager Mage_Connect_Packager */ - $packager = $this->getPackager(); - /** @var $cache Mage_Connect_Singleconfig */ - /** @var $config Mage_Connect_Config */ - if ($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - } - - try { - $forceMode = isset($options['force']); - $upgradeAllMode = $command == 'upgrade-all'; - $upgradeMode = $command == 'upgrade' || $command == 'upgrade-all'; - $noFilesInstall = isset($options['nofiles']); - $withDepsMode = !isset($options['nodeps']); - $ignoreModifiedMode = true || !isset($options['ignorelocalmodification']); - $clearInstallMode = $command == 'install' && !$forceMode; - $installAll = isset($options['install_all']); - $channelAuth = isset($options['auth'])?$options['auth']:array(); - - $rest = $this->rest(); - if (empty($config->magento_root)) { - $config->magento_root=dirname(dirname($_SERVER['SCRIPT_FILENAME'])); - } - chdir($config->magento_root); - $dirCache = DIRECTORY_SEPARATOR . $config->downloader_path . DIRECTORY_SEPARATOR - . Mage_Connect_Config::DEFAULT_CACHE_PATH; - $dirTmp = DIRECTORY_SEPARATOR . Mage_Connect_Package_Reader::PATH_TO_TEMPORARY_DIRECTORY; - $dirMedia = DIRECTORY_SEPARATOR . 'media'; - $isWritable = true; - if ($ftp) { - $cwd=$ftpObj->getcwd(); - $ftpObj->mkdirRecursive($cwd . $dirCache,0777); - $ftpObj->chdir($cwd); - $ftpObj->mkdirRecursive($cwd . $dirTmp,0777); - $ftpObj->chdir($cwd); - $ftpObj->mkdirRecursive($cwd . $dirMedia,0777); - $ftpObj->chdir($cwd); - $err = "Please check for sufficient ftp write file permissions."; - } else { - @mkdir($config->magento_root . $dirCache,0777,true); - @mkdir($config->magento_root . $dirTmp,0777,true); - @mkdir($config->magento_root . $dirMedia,0777,true); - $isWritable = is_writable($config->magento_root) - && is_writable($config->magento_root . DIRECTORY_SEPARATOR . $config->downloader_path) - && is_writable($config->magento_root . $dirCache) - && is_writable($config->magento_root . $dirTmp) - && is_writable($config->magento_root . $dirMedia); - $err = "Please check for sufficient write file permissions."; - } - $isWritable = $isWritable && is_writable($config->magento_root . $dirMedia) - && is_writable($config->magento_root . $dirCache) - && is_writable($config->magento_root . $dirTmp); - if (!$isWritable) { - $this->doError($command, $err); - throw new Exception( - 'Your Magento folder does not have sufficient write permissions, which downloader requires.' - ); - } - if (!empty($channelAuth)) { - $rest->getLoader()->setCredentials($channelAuth['username'], $channelAuth['password']); - } - - if ($installFileMode) { - if (count($params) < 1) { - throw new Exception("Argument should be: filename"); - } - $filename = $params[0]; - if (!@file_exists($filename)) { - throw new Exception("File '{$filename}' not found"); - } - if (!@is_readable($filename)) { - throw new Exception("File '{$filename}' is not readable"); - } - - $package = new Mage_Connect_Package($filename); - $package->setConfig($config); - $package->validate(); - $errors = $package->getErrors(); - if (count($errors)) { - throw new Exception("Package file is invalid\n" . implode("\n", $errors)); - } - - $pChan = $package->getChannel(); - $pName = $package->getName(); - $pVer = $package->getVersion(); - - if (!($cache->isChannelName($pChan) || $cache->isChannelAlias($pChan))) { - throw new Exception("The '{$pChan}' channel is not installed. Please use the MAGE shell " - . "script to install the '{$pChan}' channel."); - } - - $conflicts = $cache->hasConflicts($pChan, $pName, $pVer); - - if (false !== $conflicts) { - $conflicts = implode(", ",$conflicts); - if ($forceMode) { - $this->doError($command, "Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts); - } else { - throw new Exception("Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts); - } - } - - $conflicts = $package->checkPhpDependencies(); - if (true !== $conflicts) { - $conflicts = implode(",",$conflicts); - $err = "Package {$pChan}/{$pName} {$pVer} depends on PHP extensions: " . $conflicts; - if ($forceMode) { - $this->doError($command, $err); - } else { - throw new Exception($err); - } - } - - $conflicts = $package->checkPhpVersion(); - if (true !== $conflicts) { - $err = "Package {$pChan}/{$pName} {$pVer}: " . $conflicts; - if ($forceMode) { - $this->doError($command, $err); - } else { - throw new Exception($err); - } - } - - if (!$noFilesInstall) { - if ($ftp) { - $packager->processInstallPackageFtp($package, $filename, $config, $ftpObj); - } else { - $packager->processInstallPackage($package, $filename, $config); - } - } - $cache->addPackage($package); - $installedDeps = array(); - $installedDepsAssoc = array(); - $installedDepsAssoc[] = array('channel'=>$pChan, 'name'=>$pName, 'version'=>$pVer); - $installedDeps[] = array($pChan, $pName, $pVer); - - $title = isset($options['title']) ? $options['title'] : "Package installed: "; - $out = array($command => array('data'=>$installedDeps, 'assoc'=>$installedDepsAssoc, 'title'=>$title)); - - if ($ftp) { - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } - - $this->ui()->output($out); - return $out[$command]['data']; - } - - if (!$upgradeAllMode) { - if (count($params) < 2) { - throw new Exception("Argument should be: channelName packageName"); - } - $channel = $params[0]; - $package = $params[1]; - $argVersionMax = isset($params[2]) ? $params[2]: false; - $argVersionMin = isset($params[3]) ? $params[3]: false; - - $cache->checkChannel($channel, $config, $rest); - $channelName = $cache->chanName($channel); - $this->ui()->output("Checking dependencies of packages"); - $packagesToInstall = $packager->getDependenciesList($channelName, $package, $cache, $config, - $argVersionMax, $argVersionMin, $withDepsMode, false, $rest - ); - /* - * process 'failed' results - */ - if (count($packagesToInstall['failed'])) { - $showError=!count($packagesToInstall['result']); - foreach ($packagesToInstall['failed'] as $failed) { - $msg="Package {$failed['channel']}/{$failed['name']} failed: " . $failed['reason']; - if ($showError) { - $this->doError($command, $msg); - } else { - $this->ui()->output($msg); - } - } - } - $packagesToInstall = $packagesToInstall['result']; - } else { - if (empty($params[0])) { - $channels = $cache->getChannelNames(); - } else { - $channel = $params[0]; - if (!$cache->isChannel($channel)) { - throw new Exception("'{$channel}' is not existant channel name / valid uri"); - } - $channels = $cache->chanName($channel); - } - $packagesToInstall = array(); - $neededToUpgrade = $packager->getUpgradesList($channels, $cache, $config, $rest); - foreach ($neededToUpgrade as $chan=>$packages) { - foreach ($packages as $name=>$data) { - $versionTo = $data['to']; - $tmp = $packager->getDependenciesList($chan, $name, $cache, $config, $versionTo, $versionTo, - $withDepsMode, false, $rest - ); - if (count($tmp['result'])) { - $packagesToInstall = array_merge($packagesToInstall, $tmp['result']); - } - } - } - } - - /** - * Make installation - */ - $installedDeps = array(); - $installedDepsAssoc = array(); - - foreach ($packagesToInstall as $package) { - try { - $pName = $package['name']; - $pChan = $package['channel']; - $pVer = $package['downloaded_version']; - $pInstallState = $package['install_state']; - $rest->setChannel($cache->chanUrl($pChan)); - - /** - * Skip existing packages - */ - if ($upgradeMode && $cache->hasPackage($pChan, $pName, $pVer, $pVer) - || ('already_installed' == $pInstallState && !$forceMode) - ) { - $this->ui()->output("Already installed: {$pChan}/{$pName} {$pVer}, skipping"); - continue; - } - - if ('incompartible' == $pInstallState) { - $this->ui()->output( - "Package incompartible with installed Magento: {$pChan}/{$pName} {$pVer}, skipping" - ); - continue; - } - - $conflicts = $cache->hasConflicts($pChan, $pName, $pVer); - - if (false !== $conflicts) { - $conflicts = implode(", ",$conflicts); - if ($forceMode) { - $this->doError($command, "Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts); - } else { - throw new Exception("Package {$pChan}/{$pName} {$pVer} conflicts with: " . $conflicts); - } - } - - /** - * Modifications - */ - if (($upgradeMode || ($pInstallState == 'upgrade')) && !$ignoreModifiedMode) { - if ($ftp) { - $modifications = $packager->getRemoteModifiedFiles($pChan, $pName, $cache, $config, $ftp); - } else { - $modifications = $packager->getLocalModifiedFiles($pChan, $pName, $cache, $config); - } - if (count($modifications) > 0) { - $this->ui()->output('Changed locally: '); - foreach ($modifications as $row) { - if (!$ftp) { - $this->ui()->output($config->magento_root . DS . $row); - } else { - $this->ui()->output($row); - } - } - } - } - - if ($ftp) { - $cwd=$ftpObj->getcwd(); - $dir=$cwd . DIRECTORY_SEPARATOR .$config->downloader_path . DIRECTORY_SEPARATOR - . Mage_Connect_Config::DEFAULT_CACHE_PATH . DIRECTORY_SEPARATOR . trim( $pChan, "\\/"); - $ftpObj->mkdirRecursive($dir,0777); - $ftpObj->chdir($cwd); - } else { - $dir = $config->getChannelCacheDir($pChan); - @mkdir($dir, 0777, true); - } - $dir = $config->getChannelCacheDir($pChan); - $packageFileName = $pName . "-" . $pVer . ".tgz"; - $file = $dir . DIRECTORY_SEPARATOR . $packageFileName; - if (!@file_exists($file)) { - $this->ui()->output("Starting to download $packageFileName ..."); - $rest->downloadPackageFileOfRelease($pName, $pVer, $file); - $this->ui()->output(sprintf("...done: %s bytes", number_format(filesize($file)))); - } - - /** - * Remove old version package before install new - */ - if ($cache->hasPackage($pChan, $pName)) { - if ($ftp) { - $packager->processUninstallPackageFtp($pChan, $pName, $cache, $ftpObj); - } else { - $packager->processUninstallPackage($pChan, $pName, $cache, $config); - } - $cache->deletePackage($pChan, $pName); - } - - $package = new Mage_Connect_Package($file); - if ($clearInstallMode && $pInstallState != 'upgrade' && !$installAll) { - $contents = $package->getContents(); - $this->backup()->setFileTypes(array('csv', 'html')); - $typesToBackup = $this->backup()->getFileTypes(); - $this->validator()->validateContents($contents, $config, $typesToBackup); - $errors = $this->validator()->getErrors(); - if (count($errors)) { - throw new Exception("Package '{$pName}' is invalid\n" . implode("\n", $errors)); - } - - $targetPath = rtrim($config->magento_root, "\\/"); - foreach ($contents as $filePath) { - $this->backup()->addFile($filePath, $targetPath); - } - - if ($this->backup()->getFilesCount() > 0) { - $this->ui()->output('
'); - $this->ui()->output('Backup of following files will be created :'); - $this->ui()->output('
'); - $this->backup()->run(); - $this->ui()->output(implode('
', $this->backup()->getAllFiles())); - $this->ui()->output('
'); - $this->ui()->output( - $this->backup()->getFilesCount() . ' files was overwritten by installed extension.' - ); - $this->ui()->output('
'); - $this->backup()->unsetAllFiles(); - } - } - - $conflicts = $package->checkPhpDependencies(); - if (true !== $conflicts) { - $conflicts = implode(",",$conflicts); - $err = "Package {$pChan}/{$pName} {$pVer} depends on PHP extensions: " . $conflicts; - if ($forceMode) { - $this->doError($command, $err); - } else { - throw new Exception($err); - } - } - - $conflicts = $package->checkPhpVersion(); - if (true !== $conflicts) { - $err = "Package {$pChan}/{$pName} {$pVer}: " . $conflicts; - if ($forceMode) { - $this->doError($command, $err); - } else { - throw new Exception($err); - } - } - - if (!$noFilesInstall) { - $this->ui()->output("Installing package {$pChan}/{$pName} {$pVer}"); - if ($ftp) { - $packager->processInstallPackageFtp($package, $file, $config, $ftpObj); - } else { - $packager->processInstallPackage($package, $file, $config); - } - $this->ui()->output("Package {$pChan}/{$pName} {$pVer} installed successfully"); - } - $cache->addPackage($package); - - $installedDepsAssoc[] = array('channel'=>$pChan, 'name'=>$pName, 'version'=>$pVer); - $installedDeps[] = array($pChan, $pName, $pVer); - - } catch(Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - $title = isset($options['title']) ? $options['title'] : "Package installed: "; - $out = array($command => array('data'=>$installedDeps, 'assoc'=>$installedDepsAssoc, 'title'=>$title)); - - if ($ftp) { - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } - - $this->ui()->output($out); - return $out[$command]['data']; - } catch (Exception $e) { - if ($ftp) { - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } - return $this->doError($command, $e->getMessage()); - } - } - - /** - * Upgrade action callback - * - * @param string $command - * @param array $options - * @param array $params - * @return array|null - */ - public function doUpgrade($command, $options, $params) - { - $options['title'] = "Package upgraded: "; - return $this->doInstall($command, $options, $params); - } - - /** - * Updgrade action callback - * - * @param string $command - * @param array $options - * @param array $params - * @return array|null - */ - public function doUpgradeAll($command, $options, $params) - { - $options['title'] = "Package upgraded: "; - return $this->doInstall($command, $options, $params); - } - - /** - * Uninstall package callback - * - * @param string $command - * @param array $options - * @param array $params - * @return array|null - */ - public function doUninstall($command, $options, $params) - { - $this->cleanupParams($params); - - try { - if (count($params) != 2) { - throw new Exception("Argument count should be = 2"); - } - - $channel = $params[0]; - $package = $params[1]; - /** @var $packager Mage_Connect_Packager */ - $packager = $this->getPackager(); - $withDepsMode = !isset($options['nodeps'])? false : (boolean)$options['nodeps']; - $forceMode = isset($options['force']); - - $ftp = empty($options['ftp']) ? false : $options['ftp']; - /** @var $cache Mage_Connect_Singleconfig */ - /** @var $config Mage_Connect_Config */ - /** @var $ftpObj Mage_Connect_Ftp */ - if ($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - } - - $channel = $cache->chanName($channel); - if (!$cache->hasPackage($channel, $package)) { - throw new Exception("Package is not installed"); - } - - $deletedPackages = array(); - $list = $packager->getUninstallList($channel, $package, $cache, $config, $withDepsMode); - foreach ($list['list'] as $packageData) { - try { - $reqd = $cache->requiredByOtherPackages( - $packageData['channel'], - $packageData['name'], - $list['list'] - ); - if (count($reqd)) { - $errMessage = "{$packageData['channel']}/{$packageData['name']} " - . "{$packageData['version']} is required by: "; - $t = array(); - foreach ($reqd as $r) { - $t[] = $r['channel'] . "/" . $r['name'] . " " . $r['version']; - } - $errMessage .= implode(", ", $t); - if ($forceMode) { - $this->ui()->output("Warning: " . $errMessage); - } else { - throw new Exception($errMessage); - } - } - } catch(Exception $e) { - if ($forceMode) { - $this->doError($command, $e->getMessage()); - } else { - throw new Exception($e->getMessage()); - } - } - } - foreach ($list['list'] as $packageData) { - try { - list($chan, $pack) = array($packageData['channel'], $packageData['name']); - $packageName = $packageData['channel'] . "/" . $packageData['name']; - $this->ui()->output("Starting to uninstall $packageName "); - if ($ftp) { - $packager->processUninstallPackageFtp($chan, $pack, $cache, $ftpObj); - } else { - $packager->processUninstallPackage($chan, $pack, $cache, $config); - } - $cache->deletePackage($chan, $pack); - $deletedPackages[] = array($chan, $pack); - $this->ui()->output("Package {$packageName} uninstalled"); - } catch(Exception $e) { - if ($forceMode) { - $this->doError($command, $e->getMessage()); - } else { - throw new Exception($e->getMessage()); - } - } - } - if ($ftp) { - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } - $out = array($command=>array('data'=>$deletedPackages, 'title'=>'Package deleted: ')); - $this->ui()->output($out); - return $out[$command]['data']; - } catch (Exception $e) { - return $this->doError($command, $e->getMessage()); - } - } -} diff --git a/downloader/lib/Mage/Connect/Command/Install_Header.php b/downloader/lib/Mage/Connect/Command/Install_Header.php deleted file mode 100644 index 365a37851b2..00000000000 --- a/downloader/lib/Mage/Connect/Command/Install_Header.php +++ /dev/null @@ -1,237 +0,0 @@ - array( - 'summary' => 'Install Package Archive File', - 'function' => 'doInstall', - 'shortcut' => 'if', - 'options' => array(), - 'doc' => '', - ), - 'install' => array( - 'summary' => 'Install Package', - 'function' => 'doInstall', - 'shortcut' => 'i', - 'options' => array( - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'will overwrite newer installed packages', - ), - 'loose' => array( - 'shortopt' => 'l', - 'doc' => 'do not check for recommended dependency version', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, install anyway', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'alldeps' => array( - 'shortopt' => 'a', - 'doc' => 'install all required and optional dependencies', - ), - 'pretend' => array( - 'shortopt' => 'p', - 'doc' => 'Only list the packages that would be downloaded', - ), - 'ftp=' => array( - 'shortopt' => 'r=', - 'doc' => 'Remote side FTP connect string', - ), - ), - 'doc' => '[channel/] ... -Installs one or more PEAR packages. You can specify a package to -install in four ways: - -"Package-1.0.tgz" : installs from a local file - -"http://example.com/Package-1.0.tgz" : installs from -anywhere on the net. - -"package.xml" : installs the package described in -package.xml. Useful for testing, or for wrapping a PEAR package in -another package manager such as RPM. - -"Package[-version/state][.tar]" : queries your default channel\'s server -({config master_server}) and downloads the newest package with -the preferred quality/state ({config preferred_state}). - -To retrieve Package version 1.1, use "Package-1.1," to retrieve -Package state beta, use "Package-beta." To retrieve an uncompressed -file, append .tar (make sure there is no file by the same name first) - -To download a package from another channel, prefix with the channel name like -"channel/Package" - -More than one package may be specified at once. It is ok to mix these -four ways of specifying packages. -'), - 'upgrade' => array( - 'summary' => 'Upgrade Package', - 'function' => 'doUpgrade', - 'shortcut' => 'up', - 'options' => array( - 'channel' => array( - 'shortopt' => 'c', - 'doc' => 'upgrade packages from a specific channel', - 'arg' => 'CHAN', - ), - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'overwrite newer installed packages', - ), - 'loose' => array( - 'shortopt' => 'l', - 'doc' => 'do not check for recommended dependency version', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'alldeps' => array( - 'shortopt' => 'a', - 'doc' => 'install all required and optional dependencies', - ), - 'onlyreqdeps' => array( - 'shortopt' => 'o', - 'doc' => 'install all required dependencies', - ), - 'offline' => array( - 'shortopt' => 'O', - 'doc' => 'do not attempt to download any urls or contact channels', - ), - 'pretend' => array( - 'shortopt' => 'p', - 'doc' => 'Only list the packages that would be downloaded', - ), - ), - 'doc' => ' ... -Upgrades one or more PEAR packages. See documentation for the -"install" command for ways to specify a package. - -When upgrading, your package will be updated if the provided new -package has a higher version number (use the -f option if you need to -upgrade anyway). - -More than one package may be specified at once. -'), - 'upgrade-all' => array( - 'summary' => 'Upgrade All Packages', - 'function' => 'doUpgradeAll', - 'shortcut' => 'ua', - 'options' => array( - 'channel' => array( - 'shortopt' => 'c', - 'doc' => 'upgrade packages from a specific channel', - 'arg' => 'CHAN', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'loose' => array( - 'doc' => 'do not check for recommended dependency version', - ), - ), - 'doc' => ' -WARNING: This function is deprecated in favor of using the upgrade command with no params - -Upgrades all packages that have a newer release available. Upgrades are -done only if there is a release available of the state specified in -"preferred_state" (currently {config preferred_state}), or a state considered -more stable. -'), - 'uninstall' => array( - 'summary' => 'Un-install Package', - 'function' => 'doUninstall', - 'shortcut' => 'un', - 'options' => array( - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, uninstall anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not remove files, only register the packages as not installed', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'offline' => array( - 'shortopt' => 'O', - 'doc' => 'do not attempt to uninstall remotely', - ), - ), - 'doc' => '[channel/] ... -Uninstalls one or more PEAR packages. More than one package may be -specified at once. Prefix with channel name to uninstall from a -channel not in your default channel ({config default_channel}) -'), - ); diff --git a/downloader/lib/Mage/Connect/Command/Package.php b/downloader/lib/Mage/Connect/Command/Package.php deleted file mode 100644 index df75890628c..00000000000 --- a/downloader/lib/Mage/Connect/Command/Package.php +++ /dev/null @@ -1,225 +0,0 @@ -cleanupParams($params); - - if(count($params) < 1) { - return $this->doError($command, "Parameters count should be >= 1"); - } - - $file = strtolower($params[0]); - $file = realpath($file); - - if(!file_exists($file)) { - return $this->doError($command, "File {$params[0]} doesn't exist"); - } - - try { - $packager = new Mage_Connect_Package($file); - $res = $packager->validate(); - if(!$res) { - $this->doError($command, implode("\n", $packager->getErrors())); - return; - } - $packager->save(dirname($file)); - $this->ui()->output('Done building package'); - } catch (Exception $e) { - $this->doError( $command, $e->getMessage() ); - } - } - - /** - * Display/get installation information for package - * @param string $command - * @param array $options - * @param array $params - * @return void/array - */ - public function doPackagePrepare($command, $options, $params) - { - $this->cleanupParams($params); - $channelAuth = array(); - if (isset($options['auth'])) { - $channelAuth = $options['auth']; - $options['auth'] = null; - } - try { - - if(count($params) < 2) { - return $this->doError($command, "Argument count should be >= 2"); - } - - $channel = $params[0]; - $package = $params[1]; - - $argVersionMin = isset($params[3]) ? $params[3] : false; - $argVersionMax = isset($params[2]) ? $params[2] : false; - - $ftp = empty($options['ftp']) ? false : $options['ftp']; - $packager = $this->getPackager(); - if ($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - } - - $rest = Mage_Connect_Rest_Builder::getAdapter($config->protocol); - if(!empty($channelAuth)){ - $rest->getLoader()->setCredentials($channelAuth['username'], $channelAuth['password']); - } - - $cache->checkChannel($channel, $config, $rest); - - $data = $packager->getDependenciesList($channel, $package, $cache, $config, - $argVersionMax, $argVersionMin, true, false, $rest - ); - - $result = array(); - foreach ($data['result'] as $_package) { - $_result['channel'] = $_package['channel']; - $_result['name'] = $_package['name']; - $_result['version'] = $_package['downloaded_version']; - $_result['stability'] = $_package['stability']; - $_result['install_state'] = $_package['install_state']; - $_result['message'] = $_package['message']; - $result[] = $_result; - } - if (!count($data['result']) && isset($data['failed']) && !empty($data['failed'])) { - foreach ($data['failed'] as $_package) { - $reason = $_package['channel'] . '/' . $_package['name'] . ': ' . $_package['reason']; - $this->doError($command, $reason); - } - } - - $this->ui()->output( - array( - $command=> array( - 'data'=>$result, - 'title'=>"Package installation information for {$params[1]}: " - ) - ) - ); - - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - /** - * Display/get dependencies - * @param string $command - * @param array $options - * @param array $params - * @return void/array - */ - public function doPackageDependencies($command, $options, $params) - { - $this->cleanupParams($params); - try { - if(count($params) < 2) { - return $this->doError($command, "Argument count should be >= 2"); - } - - $channel = $params[0]; - $package = $params[1]; - - $argVersionMin = isset($params[3]) ? $params[3] : false; - $argVersionMax = isset($params[2]) ? $params[2] : false; - - $ftp = empty($options['ftp']) ? false : $options['ftp']; - $packager = $this->getPackager(); - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - } - $data = $packager->getDependenciesList( - $channel, - $package, - $cache, - $config, - $argVersionMax, - $argVersionMin - ); - $this->ui()->output( - array( - $command=> array( - 'data'=>$data['deps'], - 'title'=>"Package deps for {$params[1]}: " - ) - ) - ); - - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - public function doConvert($command, $options, $params) - { - $this->cleanupParams($params); - try { - if (count($params) < 1) { - throw new Exception("Arguments should be: source.tgz [target.tgz]"); - } - $sourceFile = $params[0]; - $converter = new Mage_Connect_Converter(); - $targetFile = isset($params[1]) ? $params[1] : false; - $result = $converter->convertPearToMage($sourceFile, $targetFile); - $this->ui()->output("Saved to: ".$result); - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - - } - -} diff --git a/downloader/lib/Mage/Connect/Command/Package_Header.php b/downloader/lib/Mage/Connect/Command/Package_Header.php deleted file mode 100644 index 6f51411659e..00000000000 --- a/downloader/lib/Mage/Connect/Command/Package_Header.php +++ /dev/null @@ -1,76 +0,0 @@ - array( - 'summary' => 'Build Package', - 'function' => 'doPackage', - 'shortcut' => 'p', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'Do not gzip the package file' - ), - 'showname' => array( - 'shortopt' => 'n', - 'doc' => 'Print the name of the packaged file.', - ), - ), - 'doc' => '[descfile] [descfile2] -Creates a PEAR package from its description file (usually called -package.xml). If a second packagefile is passed in, then -the packager will check to make sure that one is a package.xml -version 1.0, and the other is a package.xml version 2.0. The -package.xml version 1.0 will be saved as "package.xml" in the archive, -and the other as "package2.xml" in the archive" -' - ), - 'package-dependencies' => array( - 'summary' => 'Show package dependencies', - 'function' => 'doPackageDependencies', - 'shortcut' => 'pd', - 'options' => array(), - 'doc' => ' or or -List all dependencies the package has. -Can take a tgz / tar file, package.xml or a package name of an installed package.' - ), - 'package-prepare' => array( - 'summary' => 'Show installation information of package', - 'function' => 'doPackagePrepare', - 'shortcut' => 'pp', - 'options' => array(), - 'doc' => ' or or -List all dependencies the package has. -Can take a tgz / tar file, package.xml or a package name of an installed package.' - ), - 'convert' => array( - 'summary' => 'Convert old magento PEAR package to new format', - 'function' => 'doConvert', - 'shortcut' => 'conv', - 'options' => array(), - 'doc' => '' - ), - ); diff --git a/downloader/lib/Mage/Connect/Command/Registry.php b/downloader/lib/Mage/Connect/Command/Registry.php deleted file mode 100644 index c73284228c6..00000000000 --- a/downloader/lib/Mage/Connect/Command/Registry.php +++ /dev/null @@ -1,364 +0,0 @@ -cleanupParams($params); - try { - $packager = $this->getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $ftpObj) = $packager->getRemoteCache($ftp); - } else { - $cache = $this->getSconfig(); - } - if(!empty($params[0])) { - $chanName = $conf->chanName($params[0]); - $data = $cache->getInstalledPackages($chanName); - } else { - $data = $cache->getInstalledPackages(); - } - if($ftp) { - @unlink($cache->getFilename()); - } - $this->ui()->output(array($command=>array('data'=>$data, 'channel-title'=>"Installed package for channel '%s' :"))); - } catch (Exception $e) { - if($ftp) { - @unlink($cache->getFilename()); - } - $this->doError($command, $e->getMessage()); - } - - } - - /** - * list-files callback - * @param string $command - * @param array $options - * @param array $params - * @return void - */ - public function doFileList($command, $options, $params) - { - $this->cleanupParams($params); - //$this->splitPackageArgs($params); - try { - $channel = false; - if(count($params) < 2) { - throw new Exception("Argument count should be = 2"); - } - $channel = $params[0]; - $package = $params[1]; - - $packager = $this->getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $confif = $this->config(); - } - if(!$cache->hasPackage($channel, $package)) { - return $this->ui()->output("No package found: {$channel}/{$package}"); - } - - $p = $cache->getPackageObject($channel, $package); - $contents = $p->getContents(); - if($ftp) { - $ftpObj->close(); - } - if(!count($contents)) { - return $this->ui()->output("No contents for package {$package}"); - } - $title = ("Contents of '{$package}': "); - if($ftp) { - @unlink($config->getFilename()); - @unlink($cache->getFilename()); - } - - $this->ui()->output(array($command=>array('data'=>$contents, 'title'=>$title))); - - } catch (Exception $e) { - if($ftp) { - @unlink($config->getFilename()); - @unlink($cache->getFilename()); - } - $this->doError($command, $e->getMessage()); - } - - } - - /** - * Installed package info - * info command callback - * @param string $command - * @param array $options - * @param array $params - * @return - */ - public function doInfo($command, $options, $params) - { - $this->cleanupParams($params); - //$this->splitPackageArgs($params); - - $cache = null; - $ftp = empty($options['ftp']) ? false : $options['ftp']; - try { - $channel = false; - if(count($params) < 2) { - throw new Exception("Argument count should be = 2"); - } - $channel = $params[0]; - $package = $params[1]; - $packager = $this->getPackager(); - if($ftp) { - list($cache, $ftpObj) = $packager->getRemoteCache($ftp); - } else { - $cache = $this->getSconfig(); - } - - if(!$cache->isChannel($channel)) { - throw new Exception("'{$channel}' is not a valid installed channel name/uri"); - } - $channelUri = $cache->chanUrl($channel); - $rest = $this->rest(); - $rest->setChannel($channelUri); - $releases = $rest->getReleases($package); - if(false === $releases) { - throw new Exception("No information found about {$channel}/{$package}"); - } - $data = array($command => array('releases'=>$releases)); - if($ftp) { - @unlink($cache->getFilename()); - } - $this->ui()->output($data); - } catch (Exception $e) { - if ($ftp && isset($cache)) { - @unlink($cache->getFilename()); - } - $this->doError($command, $e->getMessage()); - } - } - - /** - * Synchronize manually installed package info with local cache - * - * @param string $command - * @param array $options - * @param array $params - */ - public function doSync($command, $options, $params) - { - $this->cleanupParams($params); - try { - $packager = $this->getPackager(); - $cache = null; - $config = null; - $ftpObj = null; - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $config = $this->config(); - $cache = $this->getSconfig(); - } - if ($this->_checkPearData($config)) { - $this->doSyncPear($command, $options, $params); - } - - $packageDir = $config->magento_root . DS . Mage_Connect_Package::PACKAGE_XML_DIR; - if (is_dir($packageDir)) { - $entries = scandir($packageDir); - foreach ((array)$entries as $entry) { - $path = $packageDir. DS .$entry; - $info = pathinfo($path); - if ($entry == '.' || $entry == '..' || is_dir($path) || $info['extension'] != 'xml') { - continue; - } - - if (is_readable($path)) { - $data = file_get_contents($path); - if ($data === false) { - continue; - } - - $package = new Mage_Connect_Package($data); - $name = $package->getName(); - $channel = $package->getChannel(); - $version = $package->getVersion(); - if (!$cache->isChannel($channel) && $channel == $config->root_channel) { - $cache->addChannel($channel, $config->root_channel_uri); - } - if (!$cache->hasPackage($channel, $name, $version, $version)) { - $cache->addPackage($package); - $this->ui()->output("Successfully added: {$channel}/{$name}-{$version}"); - } - } - } - if ($ftp) { - $packager->writeToRemoteCache($cache, $ftpObj); - } - } - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - /** - * Synchronize packages installed earlier (by pear installer) with local cache - * - * @param string $command - * @param array $options - * @param array $params - */ - public function doSyncPear($command, $options, $params) - { - $this->cleanupParams($params); - try { - $packager = $this->getPackager(); - $cache = null; - $config = null; - $ftpObj = null; - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $config = $this->config(); - $cache = $this->getSconfig(); - } - - $pkglist = array(); - if (!$this->_checkPearData($config)) { - return $pkglist; - } - - $pearStorage = $config->magento_root . DS . $config->downloader_path . DS . self::PACKAGE_PEAR_DIR; - $channels = array( - '.channel.connect.magentocommerce.com_community', - '.channel.connect.magentocommerce.com_core' - ); - foreach ($channels as $channel) { - $channelDirectory = $pearStorage . DS . $channel; - if (!file_exists($channelDirectory) || !is_dir($channelDirectory)) { - continue; - } - - $dp = opendir($channelDirectory); - if (!$dp) { - continue; - } - - while ($ent = readdir($dp)) { - if ($ent[0] == '.' || substr($ent, -4) != '.reg') { - continue; - } - $pkglist[] = array('file'=>$ent, 'channel'=>$channel); - } - closedir($dp); - } - - $package = new Mage_Connect_Package(); - foreach ($pkglist as $pkg) { - $pkgFilename = $pearStorage . DS . $pkg['channel'] . DS . $pkg['file']; - if (!file_exists($pkgFilename)) { - continue; - } - $data = file_get_contents($pkgFilename); - $data = unserialize($data); - - $package->importDataV1x($data); - $name = $package->getName(); - $channel = $package->getChannel(); - $version = $package->getVersion(); - if (!$cache->isChannel($channel) && $channel == $config->root_channel) { - $cache->addChannel($channel, $config->root_channel_uri); - } - if (!$cache->hasPackage($channel, $name, $version, $version)) { - $cache->addPackage($package); - - if($ftp) { - $localXml = tempnam(sys_get_temp_dir(),'package'); - @file_put_contents($localXml, $package->getPackageXml()); - - if (is_file($localXml)) { - $ftpDir = $ftpObj->getcwd(); - $remoteXmlPath = $ftpDir . '/' . Mage_Connect_Package::PACKAGE_XML_DIR; - $remoteXml = $package->getReleaseFilename() . '.xml'; - $ftpObj->mkdirRecursive($remoteXmlPath); - $ftpObj->upload($remoteXml, $localXml, 0777, 0666); - $ftpObj->chdir($ftpDir); - } - } else { - $destDir = rtrim($config->magento_root, "\\/") . DS . Mage_Connect_Package::PACKAGE_XML_DIR; - $destFile = $package->getReleaseFilename() . '.xml'; - $dest = $destDir . DS . $destFile; - - @mkdir($destDir, 0777, true); - @file_put_contents($dest, $package->getPackageXml()); - @chmod($dest, 0666); - } - - $this->ui()->output("Successfully added: {$channel}/{$name}-{$version}"); - } - - } - - $config->sync_pear = true; - if($ftp) { - $packager->writeToRemoteCache($cache, $ftpObj); - @unlink($config->getFilename()); - } - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - - return true; - } - - /** - * Check is need to sync old pear data - * - * @param Mage_Connect_Config $config - * @return boolean - */ - protected function _checkPearData($config) { - $pearStorage = $config->magento_root . DS . $config->downloader_path . DS . self::PACKAGE_PEAR_DIR; - return (!$config->sync_pear) && file_exists($pearStorage) && is_dir($pearStorage); - } - -} diff --git a/downloader/lib/Mage/Connect/Command/Registry_Header.php b/downloader/lib/Mage/Connect/Command/Registry_Header.php deleted file mode 100644 index 9eba7ff749e..00000000000 --- a/downloader/lib/Mage/Connect/Command/Registry_Header.php +++ /dev/null @@ -1,84 +0,0 @@ - array( - 'summary' => 'List Installed Packages In The Default Channel', - 'function' => 'doList', - 'shortcut' => 'l', - 'options' => array( - 'channel' => array( - 'shortopt' => 'c', - 'doc' => 'list installed packages from this channel', - 'arg' => 'CHAN', - ), - 'allchannels' => array( - 'shortopt' => 'a', - 'doc' => 'list installed packages from all channels', - ), - ), - 'doc' => ' -If invoked without parameters, this command lists the PEAR packages -installed in your php_dir ({config php_dir}). With a parameter, it -lists the files in a package. -', - ), - 'list-files' => array( - 'summary' => 'List Files In Installed Package', - 'function' => 'doFileList', - 'shortcut' => 'fl', - 'options' => array(), - 'doc' => ' -List the files in an installed package. -' - ), - 'info' => array( - 'summary' => 'Display information about a package', - 'function' => 'doInfo', - 'shortcut' => 'in', - 'options' => array(), - 'doc' => ' -Displays information about a package. The package argument may be a -local package file, an URL to a package file, or the name of an -installed package.' - ), - 'sync' => array( - 'summary' => 'Synchronize Manually Installed Packages', - 'function' => 'doSync', - 'shortcut' => 'snc', - 'options' => array(), - 'doc' => ' -Synchronize manually installed package info with local cache.' - ), - 'sync-pear' => array( - 'summary' => 'Synchronize already Installed Packages by pear', - 'function' => 'doSyncPear', - 'shortcut' => 'sncp', - 'options' => array(), - 'doc' => ' -Synchronize already Installed Packages by pear.' - ) - ); diff --git a/downloader/lib/Mage/Connect/Command/Remote.php b/downloader/lib/Mage/Connect/Command/Remote.php deleted file mode 100644 index b82382de4b7..00000000000 --- a/downloader/lib/Mage/Connect/Command/Remote.php +++ /dev/null @@ -1,231 +0,0 @@ -cleanupParams($params); - try { - $packager = new Mage_Connect_Packager(); - $channelAuth = isset($options['auth'])?$options['auth']:array(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - } - - if(!empty($params[0])) { - $channels = $params[0]; - $cache->getChannel($channels); - } else { - $channels = $cache->getChannelNames(); - } - $rest = $this->rest(); - if(!empty($channelAuth)){ - $rest->getLoader()->setCredentials($channelAuth['username'], $channelAuth['password']); - } - $ups = $packager->getUpgradesList($channels, $cache, $config, $rest); - - if(count($ups)) { - $data = array($command => array('data'=>$ups)); - } else { - $data = "No upgrades available"; - } - $this->ui()->output($data); - } catch(Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - - /** - * List available - * @param $command - * @param $options - * @param $params - * @return unknown_type - */ - - public function doListAvailable($command, $options, $params) - { - $this->cleanupParams($params); - - try { - $packager = new Mage_Connect_Packager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - } - - if(!empty($params[0])) { - $channels = array($params[0]); - $cache->getChannel($channels[0]); - } else { - $channels = $cache->getChannelNames(); - } - - - - $packs = array(); - foreach ($channels as $channel) { - try { - $chan = $cache->getChannel($channel); - $uri = $cache->chanUrl($channel); - - $rest = $this->rest(); - $rest->setChannel($uri); - - $packages = $rest->getPackages(); - if(!count($packages)) { - $this->ui()->output("Channel '{$channel}' has no packages"); - continue; - } - $packs[$channel]['title'] = "Packages for channel '".$channel."':"; - foreach($packages as $p) { - $packageName = $p['n']; - $releases = array(); - foreach($p['r'] as $k=>$r) { - $releases[$r] = $rest->shortStateToLong($k); - } - $packs[$channel]['packages'][$packageName]['releases'] = $releases; - } - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - $dataOut = array(); - $dataOut[$command]= array('data'=>$packs); - $this->ui()->output($dataOut); - - } catch(Exception $e) { - $this->doError($command, $e->getMessage()); - } - - } - - /** - * Download command callback - * - * @param string $command - * @param array $options - * @param array $params - * @return void - */ - public function doDownload($command, $options, $params) - { - $this->cleanupParams($params); - //$this->splitPackageArgs($params); - try { - if(count($params) < 2) { - throw new Exception("Arguments should be: channel Package"); - } - - $channel = $params[0]; - $package = $params[1]; - - $packager = $this->getPackager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); - } else { - $cache = $this->getSconfig(); - $config = $this->config(); - } - - $chan = $cache->getChannel($channel); - $uri = $cache->chanUrl($channel); - - $rest = $this->rest(); - $rest->setChannel($uri); - $c = $rest->getReleases($package); - if(!count($c)) { - throw new Exception("No releases found for package"); - } - $version = $cache->detectVersionFromRestArray($c); - $dir = $config->getChannelCacheDir($channel); - $file = $dir.DIRECTORY_SEPARATOR.$package."-".$version.".tgz"; - $rest->downloadPackageFileOfRelease($package, $version, $file); - if($ftp) { - @unlink($config->getFilename()); - @unlink($cache->getFilename()); - } - $this->ui()->output("Saved to: ". $file); - } catch (Exception $e) { - if($ftp) { - @unlink($config->getFilename()); - @unlink($cache->getFilename()); - } - $this->doError($command, $e->getMessage()); - } - } - - /** - * Clear cache command callback - * @param string $command - * @param array $options - * @param array $params - * @return void - */ - public function doClearCache($command, $options, $params) - { - $this->cleanupParams($params); - try { - $packager = new Mage_Connect_Packager(); - $ftp = empty($options['ftp']) ? false : $options['ftp']; - if($ftp) { - list($cache, $ftpObj) = $packager->getRemoteCache($ftp); - $cache->clear(); - $packager->writeToRemoteCache($cache, $ftpObj); - } else { - $cache = $this->getSconfig(); - $cache->clear(); - } - } catch (Exception $e) { - $this->doError($command, $e->getMessage()); - } - } - - - - - -} diff --git a/downloader/lib/Mage/Connect/Command/Remote_Header.php b/downloader/lib/Mage/Connect/Command/Remote_Header.php deleted file mode 100644 index 86b97c6e68b..00000000000 --- a/downloader/lib/Mage/Connect/Command/Remote_Header.php +++ /dev/null @@ -1,88 +0,0 @@ - array( - 'summary' => 'List Available Upgrades', - 'function' => 'doListUpgrades', - 'shortcut' => 'lu', - 'options' => array( - 'channelinfo' => array( - 'shortopt' => 'i', - 'doc' => 'output fully channel-aware data, even on failure', - ), - ), - 'doc' => '[preferred_state] -List releases on the server of packages you have installed where -a newer version is available with the same release state (stable etc.) -or the state passed as the second parameter.' - ), - 'list-available' => array( - 'summary' => 'List Available Packages', - 'function' => 'doListAvailable', - 'shortcut' => 'la', - 'options' => array( - 'channel' => - array( - 'shortopt' => 'c', - 'doc' => 'specify a channel other than the default channel', - 'arg' => 'CHAN', - ), - 'channelinfo' => array( - 'shortopt' => 'i', - 'doc' => 'output fully channel-aware data, even on failure', - ), - ), - 'doc' => ' -Lists the packages available on the configured server along with the -latest stable release of each package.', - ), - 'download' => array( - 'summary' => 'Download Package', - 'function' => 'doDownload', - 'shortcut' => 'd', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'download an uncompressed (.tar) file', - ), - ), - 'doc' => '... -Download package tarballs. The files will be named as suggested by the -server, for example if you download the DB package and the latest stable -version of DB is 1.6.5, the downloaded file will be DB-1.6.5.tgz.', - ), - 'clear-cache' => array( - 'summary' => 'Clear Web Services Cache', - 'function' => 'doClearCache', - 'shortcut' => 'cc', - 'options' => array(), - 'doc' => ' -Clear the XML-RPC/REST cache. See also the cache_ttl configuration -parameter. -', - ), - ); diff --git a/downloader/lib/Mage/Connect/Config.php b/downloader/lib/Mage/Connect/Config.php deleted file mode 100644 index bc390817ea4..00000000000 --- a/downloader/lib/Mage/Connect/Config.php +++ /dev/null @@ -1,617 +0,0 @@ - - */ -class Mage_Connect_Config implements Iterator -{ - /** - * Config file name - * - * @var string - */ - protected $_configFile; - - /** - * Config loaded from file - * - * @var bool - */ - protected $_configLoaded; - - /** - * Save file even if it not modified - * - * @var bool - */ - protected $_forceSave = false; - - /** - * Stores last error message - * - * @var string - */ - protected $_configError = ''; - - /** - * Header string - */ - const HEADER = "::ConnectConfig::v::1.0::"; - - /** - * Default paths - */ - const DEFAULT_DOWNLOADER_PATH = "downloader"; - const DEFAULT_CACHE_PATH = ".cache"; - - /** - * Array of default properties - * @var array - */ - protected $defaultProperties = array(); - - /** - * Array of properties - * - * @var array - */ - protected $properties = array(); - - /** - * Constructor loads the data from config file - * @param string $configFile - */ - public function __construct($configFile = "connect.cfg") - { - $this->initProperties(); - $this->_configFile = $configFile; - $this->load(); - } - - /** - * Initialise Properties and Default Properties - * - * @return void - */ - protected function initProperties() - { - $this->defaultProperties = array ( - 'php_ini' => array( - 'type' => 'file', - 'value' => '', - 'prompt' => 'location of php.ini', - 'doc' => "It's a location of PHP.ini to use blah", - 'possible' => '/path/php.ini', - ), - 'protocol' => array( - 'type' => 'set', - 'value' => 'https', - 'prompt' => 'preffered protocol', - 'doc' => 'preffered protocol', - 'rules' => array('http', 'ftp') - ), - 'preferred_state' => array( - 'type' => 'set', - 'value' => 'stable', - 'prompt' => 'preferred package state', - 'doc' => 'preferred package state', - 'rules' => array('beta','alpha','stable','devel') - ), - 'use_custom_permissions_mode' => array ( - 'type' => 'bool', - 'value' => false, - 'prompt' => 'Use custom permissions for directory and file creation', - 'doc' => 'Use custom permissions for directory and file creation', - 'possible' => 'true, false', - ), - 'global_dir_mode' => array ( - 'type' => 'octal', - 'value' => 0777, - 'prompt' => 'directory creation mode', - 'doc' => 'directory creation mode', - 'possible' => '0777, 0666 etc.', - ), - 'global_file_mode' => array ( - 'type' => 'octal', - 'value' => 0666, - 'prompt' => 'file creation mode', - 'doc' => 'file creation mode', - 'possible' => '0777, 0666 etc.', - ), - 'downloader_path' => array( - 'type' => 'dir', - 'value' => 'downloader', - 'prompt' => 'relative path, location of magento downloader', - 'doc' => "relative path, location of magento downloader", - 'possible' => 'path', - ), - 'magento_root' => array( - 'type' => 'dir', - 'value' => '', - 'prompt' => 'location of magento root dir', - 'doc' => "Location of magento", - 'possible' => '/path', - ), - 'root_channel_uri' => array( - 'type' => 'string', - 'value' => 'connect20.magentocommerce.com/community', - 'prompt' => '', - 'doc' => "", - 'possible' => '', - ), - 'root_channel' => array( - 'type' => 'string', - 'value' => 'community', - 'prompt' => '', - 'doc' => "", - 'possible' => '', - ), - 'remote_config' => array( - 'type' => 'string', - 'value' => '', - 'prompt' => '', - 'doc' => "", - 'possible' => 'ftp://name:password@host.com:port/path/to/folder/', - ), - 'sync_pear' => array( - 'type' => 'boolean', - 'value' => false, - 'prompt' => '', - 'doc' => "", - 'possible' => '', - ) - ); - $this->properties = $this->defaultProperties; - } - - /** - * Retrieve Downloader Path - * - * @return string - */ - public function getDownloaderPath() - { - return $this->magento_root . DIRECTORY_SEPARATOR . $this->downloader_path; - } - - /** - * Retrieve Packages Cache Directory - * - * @return string - */ - public function getPackagesCacheDir() - { - return $this->getDownloaderPath() . DIRECTORY_SEPARATOR . self::DEFAULT_CACHE_PATH; - } - - /** - * Retrieve Channel Cache Directory - * - * @param string $channel - * @return string - */ - public function getChannelCacheDir($channel) - { - $channel = trim( $channel, "\\/"); - return $this->getPackagesCacheDir(). DIRECTORY_SEPARATOR . $channel; - } - - /** - * Get Config file name - * - * @return string - */ - public function getFilename() - { - return $this->_configFile; - } - - /** - * Load data from config file - * - * @return bool - */ - public function load() - { - $this->_configLoaded=false; - if (!is_file($this->_configFile)) { - if (!$this->save()) { - $this->_configError = 'Config file does not exists please save Settings'; - } else { - $this->_configLoaded=true; - return true; - } - return false; - } - - try { - $f = fopen($this->_configFile, "r"); - fseek($f, 0, SEEK_SET); - } catch (Exception $e) { - $this->_configError = "Cannot open config file {$this->_configFile} please check file permission"; - return false; - } - - clearstatcache(); - $size = filesize($this->_configFile); - if (!$size) { - $this->_configError = "Wrong config file size {$this->_configFile} please save Settings again"; - return false; - } - - $headerLen = strlen(self::HEADER); - try { - $contents = fread($f, $headerLen); - if (self::HEADER != $contents) { - $this->_configError = "Wrong configuration file {$this->_configFile} please save Settings again"; - return false; - } - - $size -= $headerLen; - $contents = fread($f, $size); - } catch (Exception $e) { - $this->_configError = "Configuration file {$this->_configFile} read error '{$e->getMessage()}'" - . " please save Settings again"; - return false; - } - $data = @unserialize($contents); - if ($data === false) { - $this->_configError = "Wrong configuration file {$this->_configFile} please save Settings again"; - return false; - } - foreach($data as $k=>$v) { - $this->$k = $v; - } - @fclose($f); - $this->_configLoaded=true; - return true; - } - - /** - * Save config file on the disk or over ftp - * - * @return bool - */ - public function store() - { - $result = false; - if ($this->_forceSave || $this->_configLoaded || strlen($this->remote_config)>0) { - $data = serialize($this->toArray()); - if (strlen($this->remote_config)>0) { - //save config over ftp - $confFile = $this->downloader_path . DIRECTORY_SEPARATOR . "connect.cfg"; - try { - $ftpObj = new Mage_Connect_Ftp(); - $ftpObj->connect($this->remote_config); - } catch (Exception $e) { - $this->_configError = 'Cannot access to deployment FTP path. ' - . 'Check deployment FTP Installation path settings.'; - return $result; - } - try { - $tempFile = tempnam(sys_get_temp_dir(),'config'); - $f = fopen($tempFile, "w+"); - fwrite($f, self::HEADER); - fwrite($f, $data); - fclose($f); - } catch (Exception $e) { - $this->_configError = 'Cannot access to temporary file storage to save Settings.' - . 'Contact your system administrator.'; - return $result; - } - try { - $result = $ftpObj->upload($confFile, $tempFile); - $ftpObj->close(); - } catch (Exception $e) { - $this->_configError = 'Cannot write file over FTP. ' - . 'Check deployment FTP Installation path settings.'; - return $result; - } - if (!$result) { - $this->_configError = ''; - } - } elseif (is_file($this->_configFile) && is_writable($this->_configFile) || is_writable(getcwd())) { - try { - $f = fopen($this->_configFile, "w+"); - fwrite($f, self::HEADER); - fwrite($f, $data); - fclose($f); - $result = true; - } catch (Exception $e) { - $result = false; - } - } - } - return $result; - } - - /** - * Validate value for configuration key - * - * @param string $key - * @param mixed $val - * @return bool - */ - public function validate($key, $val) - { - $rules = $this->extractField($key, 'rules'); - if (null === $rules) { - return true; - } elseif ( is_array($rules) ) { - return in_array($val, $rules); - } - return false; - } - - /** - * Get possible values for configuration key - * - * @param string $key - * @return null|string - */ - public function possible($key) - { - $data = $this->getKey($key); - if (! $data) { - return null; - } - if ('set' == $data['type']) { - return implode("|", $data['rules']); - } - if (!empty($data['possible'])) { - return $data['possible']; - } - return "<" . $data['type'] . ">"; - } - - /** - * Get type of key - * - * @param string $key - * @return mixed|null - */ - public function type($key) - { - return $this->extractField($key, 'type'); - } - - /** - * Get documentation information - * - * @param string $key - * @return mixed|null - */ - public function doc($key) - { - return $this->extractField($key, 'doc'); - } - - /** - * Get property of key - * - * @param $key - * @param $field - * @return mixed|null - */ - public function extractField($key, $field) - { - if (!isset($this->properties[$key][$field])) { - return null; - } - return $this->properties[$key][$field]; - } - - /** - * Check Key exists in properties array - * - * @param string $fld - * @return bool - */ - public function hasKey($fld) - { - return isset($this->properties[$fld]); - } - - /** - * Get all Key properties - * - * @param $fld - * @return null - */ - public function getKey($fld) - { - if ($this->hasKey($fld)) { - return $this->properties[$fld]; - } - return null; - } - - /** - * Set the internal pointer of the Properties array to its first element - * - * @return void - */ - public function rewind() { - reset($this->properties); - } - - /** - * Validate current property - * - * @return bool - */ - public function valid() { - return current($this->properties) !== false; - } - - /** - * Get Key of current property - * - * @return mixed - */ - public function key() { - return key($this->properties); - } - - /** - * Get current Property - * - * @return mixed - */ - public function current() { - return current($this->properties); - } - - /** - * Advance the internal array pointer of the Properties array - * - * @return void - */ - public function next() { - next($this->properties); - } - - /** - * Retrieve value of property - * - * @param string $var - * @return null - */ - public function __get($var) - { - if (isset($this->properties[$var]['value'])) { - return $this->properties[$var]['value']; - } - return null; - } - - /** - * Set value of property - * - * @param string $var - * @param mixed $value - * @return void - */ - public function __set($var, $value) - { - if (is_string($value)) { - $value = trim($value); - } - if (isset($this->properties[$var])) { - if ($value === null) { - $value = ''; - } - if ($this->properties[$var]['value'] !== $value) { - $this->properties[$var]['value'] = $value; - $this->store(); - } - } - } - - /** - * Prepare Array of class properties - * - * @param bool $withRules - * @return array - */ - public function toArray($withRules = false) - { - $out = array(); - foreach ($this as $k=>$v) { - $out[$k] = $withRules ? $v : $v['value']; - } - return $out; - } - - /** - * Return default config value by key - * - * @param string $key - * @return mixed - */ - public function getDefaultValue($key) - { - if (isset($this->defaultProperties[$key]['value'])) { - return $this->defaultProperties[$key]['value']; - } - return false; - } - - /** - * Check is config loaded - * - * @return string - */ - public function isLoaded() - { - return $this->_configLoaded; - } - - /** - * Retrieve error message - * - * @return string - */ - public function getError() - { - return $this->_configError; - } - - /** - * Save config - * - * @return string - */ - public function save() - { - $forceSave = $this->_forceSave; - $this->_forceSave = true; - - $result = $this->store(); - - $this->_forceSave = $forceSave; - - return $result; - } -} diff --git a/downloader/lib/Mage/Connect/Converter.php b/downloader/lib/Mage/Connect/Converter.php deleted file mode 100644 index a262732b755..00000000000 --- a/downloader/lib/Mage/Connect/Converter.php +++ /dev/null @@ -1,336 +0,0 @@ - - */ - -final class Mage_Connect_Converter -{ - protected $_archiver; - - /** - * - * @return Mage_Archive - */ - public function arc() - { - if(!$this->_archiver) { - $this->_archiver = new Mage_Archive(); - } - return $this->_archiver; - } - - public function newPackage() - { - return new Mage_Connect_Package(); - } - - /** - * - * @return Pear_Package_Parser_v2 - */ - public function oldPackageReader() - { - return new Pear_Package_Parser_v2(); - } - - - public function __construct() - { - - } - - - public function convertChannelName($channel) - { - return str_replace("connect.magentocommerce.com/", "", $channel); - } - - /** - * Convert package dependencies - urls - by ref - * @param array $deps ref to array - * @return void - */ - public function convertPackageDependencies($oldDeps) - { - $out = array(); - if(empty($oldDeps['required']['package'])) { - return $out; - } - $deps = $oldDeps['required']['package']; - if(!isset($deps[0])) { - $deps = array($deps); - } - for($i=0, $c=count($deps); $i<$c; $i++) { - $deps[$i]['min_version'] = isset($deps[$i]['min']) ? $deps[$i]['min'] : false; - $deps[$i]['max_version'] = isset($deps[$i]['max']) ? $deps[$i]['max'] : false; - $deps[$i]['channel'] = $this->convertChannelName($deps[$i]['channel']); - $out[] = $deps[$i]; - } - - return $out; - } - - public function convertLicense($oldLicense) - { - if(is_scalar($oldLicense)) { - return $oldLicense; - } - return array($oldLicense['_content'], $oldLicense['attribs']['uri']); - } - - public function convertMaintainers($maintainers) - { - if(!is_array($maintainers) || !count($maintainers)) { - return array(); - } - $out = array(); - foreach($maintainers as $row) { - $out[] = array('name'=>$row['name'], 'email'=>$row['email'], 'user'=>'auto-converted'); - } - return $out; - } - - protected $fileMap = array(); - - - /** - * Conver pear package object to magento object - * @param Pear_Package_V2 $pearObject - * @return Mage_Connect_Package - */ - - public function convertPackageObject($pearObject) - { - $data = array(); - $mageObject = $this->newPackage(); - - - - $map = array ( - 'name' => null, - 'version' => array('getterArgs' => array('release') - ), - 'package_deps' => array( 'getter'=>'getDependencies', - 'converter'=>'convertPackageDependencies', - 'setter'=>'setDependencyPackages', - ), - 'stability' => array( 'getter'=>'getState', - 'getterArgs' => array('release'), - ), - 'license' => array( 'getterArgs' => array(true), - 'converter' => 'convertLicense', - 'noArrayWrap' => true, - ), - 'summary' => null, - 'description' => null, - 'notes' => null, - 'date' => null, - 'time' => null, - 'authors' => array( 'converter' => 'convertMaintainers', - 'getter' => 'getMaintainers', - ), - 'channel' => array( 'converter' => 'convertChannelName', - - ), - - ); - foreach($map as $field=>$rules) { - - if(empty($rules)) { - $rules = array('setter'=> '', 'getter'=> ''); - } - - if(empty($rules['getter'])) { - $rules['getter'] = 'get'. ucfirst($field); - } - - $useSetter = empty($rules['noSetter']); - $useGetter = empty($rules['noGetter']); - - - if(empty($rules['setter'])) { - $rules['setter'] = 'set'. ucfirst($field); - } - if(empty($rules['getterArgs'])) { - $rules['getterArgs'] = array(); - } elseif(!is_array($rules['getterArgs'])) { - throw new Exception("Invalid 'getterArgs' for '{$field}', should be array"); - } - - if($useGetter && !method_exists($pearObject, $rules['getter'])) { - $mName = get_class($pearObject)."::".$rules['getter']; - throw new Exception('No getter method exists: '.$mName); - } - - if($useSetter && !method_exists($mageObject, $rules['setter'])) { - $mName = get_class($mageObject)."::".$rules['setter']; - throw new Exception('No setter method exists: '.$mName); - } - - $useConverter = !empty($rules['converter']); - - if($useConverter && false === method_exists($this, $rules['converter'])) { - $mName = get_class($this)."::".$rules['converter']; - throw new Exception('No converter method exists: '.$mName); - } - - if($useGetter) { - $getData = call_user_func_array(array($pearObject, $rules['getter']), $rules['getterArgs']); - } else { - $getData = array(); - } - - if($useConverter) { - $args = array(); - if(!$useGetter && !$useSetter) { - $args = array($pearObject, $mageObject); - } elseif(!$useSetter) { - $args = array($mageObject, $getData); - } else { - $args = array($getData); - } - $getData = call_user_func_array(array($this, $rules['converter']), $args); - } - - $noWrap = !empty($rules['noArrayWrap']); - if($useSetter) { - $setData = call_user_func_array(array($mageObject, $rules['setter']), $noWrap ? $getData : array($getData)); - } - } - return $mageObject; - } - - /** - * Convert PEAR package to Magento package - * @param string $sourceFile path to PEAR .tgz - * @param string|false $destFile path to newly-created Magento .tgz, false to specify auto - * @return bool - */ - public function convertPearToMage($sourceFile, $destFile = false) - { - try { - if(!file_exists($sourceFile)) { - throw new Exception("File doesn't exist: {$sourceFile}"); - } - $arc = $this->arc(); - $tempDir = "tmp-".basename($sourceFile).uniqid(); - $outDir = "out-".basename($sourceFile).uniqid(); - $outDir = rtrim($outDir, "\\/"); - Mage_System_Dirs::mkdirStrict($outDir); - Mage_System_Dirs::mkdirStrict($tempDir); - - $result = $arc->unpack($sourceFile, $tempDir); - if(!$result) { - throw new Exception("'{$sourceFile}' was not unpacked"); - } - - $result = rtrim($result, "\\/"); - $packageXml = $result . DS . "package.xml"; - if(!file_exists($packageXml)) { - throw new Exception("No package.xml found inside '{$sourceFile}'"); - } - - $reader = $this->oldPackageReader(); - $data = file_get_contents($packageXml); - - $pearObject = $reader->parsePackage($data, $packageXml); - $mageObject = $this->convertPackageObject($pearObject); - if(!$mageObject->validate()) { - throw new Exception("Package validation failed.\n". implode("\n", $mageObject->getErrors())); - } - - /** - * Calculate destination file if false - */ - if(false === $destFile) { - $pathinfo = pathinfo($sourceFile); - $destFile = $pathinfo['dirname'] . DS .$pathinfo['filename'].'-converted'; - if(isset($pathinfo['extension'])) { - $destFile .= ".".$pathinfo['extension']; - } - } - - $target = new Mage_Connect_Package_Target("target.xml"); - $targets = $target->getTargets(); - $mageObject->setTarget($target); - $validRoles = array_keys($targets); - $data = $pearObject->getFilelist(); - $pathSource = dirname($pearObject->getPackageFile()).DS.$pearObject->getName()."-".$pearObject->getVersion(); - - $filesToDo = array(); - foreach($data as $file =>$row) { - $name = $row['name']; - $role = $row['role']; - if(!in_array($role, $validRoles)) { - $role = 'mage'; - } - $baseName = ltrim($targets[$role], "\\/."); - $baseName = rtrim($baseName, "\\/"); - $sourceFile = $pathSource.DS.$name; - $targetFile = $outDir . DS . $baseName . DS. $name; - if(file_exists($sourceFile)) { - Mage_System_Dirs::mkdirStrict(dirname($targetFile)); - $copy = @copy($sourceFile, $targetFile); - if(false === $copy) { - throw new Exception("Cannot copy '{$sourceFile}' to '{$targetFile}'"); - } - } - $filesToDo[] = array ('name'=> $name, 'role'=>$role); - } - $cwd = getcwd(); - @chdir($outDir); - foreach($filesToDo as $fileToDo) { - $mageObject->addContent($fileToDo['name'], $fileToDo['role']); - } - $mageObject->save(getcwd()); - @chdir($cwd); - $filename = $outDir. DS . $mageObject->getReleaseFilename().".tgz"; - if(@file_exists($targetArchive)) { - @unlink($targetArchive); - } - Mage_System_Dirs::mkdirStrict(dirname($destFile)); - $copy = @copy($filename, $destFile); - if(false === $copy) { - throw new Exception("Cannot copy '{$filename}' to '{$targetArchive}'"); - } - Mage_System_Dirs::rm($tempDir); - Mage_System_Dirs::rm($outDir); - - } catch (Exception $e) { - throw $e; - } - return $destFile; - } - - - -} diff --git a/downloader/lib/Mage/Connect/Frontend.php b/downloader/lib/Mage/Connect/Frontend.php deleted file mode 100644 index 60f6a88a362..00000000000 --- a/downloader/lib/Mage/Connect/Frontend.php +++ /dev/null @@ -1,267 +0,0 @@ -_errors[] = $data; - } - - /** - * Get errors, clear errors list with first param - * - * @param boolean $clear - * @return array - */ - public function getErrors($clear = true) - { - if(!$clear) { - return $this->_errors; - } - $out = $this->_errors; - $this->clearErrors(); - return $out; - } - - /** - * Clear errors array - * - * @return null - */ - public function clearErrors() - { - $this->_errors = array(); - } - - /** - * Are there any errros? - * - * @return boolean - */ - public function hasErrors() - { - return count($this->_errors) != 0; - } - - /** - * Error processing - * @param string $command - * @param string $message - * @return null - */ - public function doError($command, $message) - { - $this->addError(array($command, $message)); - } - - /** - * Save capture state - * - * @return Mage_Connect_Frontend - */ - public function pushCapture() - { - array_push($this->_captureSaved, $this->_capture); - return $this; - } - - /** - * Restore capture state - * - * @return Mage_Connect_Frontend - */ - public function popCapture() - { - $this->_capture = array_pop($this->_captureSaved); - return $this; - } - - /** - * Set capture mode - * - * @param boolean $arg true by default - * @return Mage_Connect_Frontend - */ - public function setCapture($arg = true) - { - $this->_capture = $arg; - return $this; - } - - /** - * Getter for capture mode - * - * @return boolean - */ - public function isCapture() - { - return $this->_capture; - } - - /** - * Log stub - * - * @param $msg - * @return - */ - public function log($msg) - { - - } - - /** - * Ouptut method - * - * @param array $data - * @return null - */ - public function output($data) - { - - } - - /** - * Get instance of derived class - * - * @param $class CLI for example will produce Mage_Connect_Frontend_CLI - * @return object - */ - public static function getInstance($class) - { - $class = __CLASS__."_".$class; - return new $class(); - } - - /** - * Get output if capture mode set - * Clear prevoius if needed - * - * @param boolean $clearPrevious - * @return mixed - */ - public function getOutput($clearPrevious = true) - { - - } - - /** - * Save silent mode - * - * @return Mage_Connect_Frontend - */ - public function pushSilent() - { - array_push($this->_silentSaved, $this->_silent); - return $this; - } - - /** - * Restore silent mode - * - * @return Mage_Connect_Frontend - */ - public function popSilent() - { - $this->_silent = array_pop($this->_silentSaved); - return $this; - } - - /** - * Set silent mode - * - * @param boolean $value - * @return Mage_Connect_Frontend - */ - public function setSilent($value = true) - { - $this->_silent = (boolean) $value; - return $this; - } - - /** - * Is silent mode? - * - * @return boolean - */ - public function isSilent() - { - return (boolean) $this->_silent; - } - - /** - * Method for ask client about rewrite all files. - * - * @param $string - */ - public function confirm($string) - { - - } -} - diff --git a/downloader/lib/Mage/Connect/Frontend/CLI.php b/downloader/lib/Mage/Connect/Frontend/CLI.php deleted file mode 100644 index a665d62a0e9..00000000000 --- a/downloader/lib/Mage/Connect/Frontend/CLI.php +++ /dev/null @@ -1,456 +0,0 @@ - - */ - -class Mage_Connect_Frontend_CLI -extends Mage_Connect_Frontend -{ - - /** - * Collected output - * @var array - */ - protected $_output = array(); - - /** - * Output error - * @param string $command - * @param string $message - * @return void - */ - public function doError($command, $message) - { - parent::doError($command, $message); - $this->writeln("Error: "); - $this->writeln("$command: $message"); - } - - - /** - * Output config help - * @param array $data - * @return void - */ - public function outputConfigHelp($data) - { - foreach($data['data'] as $k=>$v) { - if(is_scalar($v)) { - $this->writeln($v); - } elseif(is_array($v)) { - $this->writeln(implode(": ", $v)); - } - } - } - - - /** - * Output info - * @param array $data - * @return void - */ - public function outputRemoteInfo($data) - { - if(!is_array($data['releases'])) { - return; - } - foreach ($data['releases'] as $r) { - $this->writeln(implode(" ", $r)); - } - } - - - public function detectMethodByType($type) - { - $defaultMethod = "output"; - $methodMap = array( - 'list-upgrades'=> 'outputUpgrades', - 'list-available' => 'outputChannelsPackages', - 'list-installed' => 'writeInstalledList', - 'package-dependencies' => 'outputPackageDeps', - 'package-prepare' => 'outputPackagePrepare', - 'list-files' => 'outputPackageContents', - 'config-help' => 'outputConfigHelp', - 'info' => 'outputRemoteInfo', - 'config-show' => 'outputConfig', - 'install' => 'outputInstallResult', - 'install-file' => 'outputInstallResult', - 'upgrade' => 'outputInstallResult', - 'upgrade-all' => 'outputInstallResult', - 'uninstall' => 'outputDeleted', - 'list-channels' => 'outputListChannels', - ); - if(isset($methodMap[$type])) { - return $methodMap[$type]; - } - return $defaultMethod; - } - - - public function outputDeleted($data) - { - if(!count($data['data'])) { - return; - } - $this->writeln($data['title']); - foreach($data['data'] as $row) { - $this->writeln("$row[0]/$row[1]"); - } - } - - public function outputListChannels($data) - { - $this->writeln($data['title']); - - $channels =& $data['data'][Mage_Connect_Singleconfig::K_CHAN]; - foreach($channels as $name => $v) { - $this->writeln("$name: {$v[Mage_Connect_Singleconfig::K_URI]}"); - } - $aliases =& $data['data'][Mage_Connect_Singleconfig::K_CHAN_ALIAS]; - if(count($aliases)) { - $this->writeln(); - $this->writeln($data['title_aliases']); - foreach($aliases as $k=>$v) { - $this->writeln("$k => $v"); - } - } - - } - - /** - * Output install result - * @param array $data - * @return void - */ - public function outputInstallResult($data) - { - if(isset($data['title'])) { - $title = trim($data['title'])." "; - } else { - $title = ''; - } - foreach($data['assoc'] as $row) { - $this->printf("%s%s/%s %s\n", $title, $row['channel'], $row['name'], $row['version']); - } - } - - /** - * Ouptut package contents - * @param array $data - * @return void - */ - public function outputPackageContents($data) - { - $this->writeln($data['title']); - foreach($data['data'] as $file) { - $this->writeln($file); - } - } - - /** - * Output package dependencies - * @param $data - * @return void - */ - public function outputPackageDeps($data) - { - $title = $data['title']; - $this->writeln($title); - foreach($data['data'] as $package) { - $this->printf("%-20s %-20s %-20s %-20s\n", $package['channel'], $package['name'], $package['min'], $package['max']); - } - } - - /** - * Output package prepare - * @param $data - * @return void - */ - public function outputPackagePrepare($data) - { - $title = $data['title']; - $this->writeln($title); - foreach($data['data'] as $package) { - $this->printf("%-20s %-20s %-20s %-20s\n", $package['channel'], $package['name'], $package['version'], $package['install_state']); - } - } - - /** - * Ouptut channel packages - * @param $data - * @return unknown_type - */ - public function outputChannelsPackages($data) - { - foreach($data['data'] as $channelInfo) { - $title =& $channelInfo['title']; - $packages =& $channelInfo['packages']; - $this->writeln($title); - foreach($packages as $name=>$package) { - $releases =& $package['releases']; - $tmp = array(); - foreach($releases as $ver=>$state) { - $tmp[] = "$ver $state"; - } - $tmp = implode(',',$tmp); - $this->writeln($name.": ".$tmp); - } - } - } - - - /** - * Make output - * - * @param array $data - * @return void - */ - - public function output($data) - { - $capture = $this->isCapture(); - if($capture) { - $this->_output[] = $data; - return; - } - - if(is_array($data)) { - foreach($data as $type=>$params) { - $method = $this->detectMethodByType($type); - if($method) { - $this->$method($params); - } else { - $this->writeln(__METHOD__." handler not found for {$type}"); - } - } - } else { - $this->writeln($data); - } - } - - - /** - * Detailed package info - * @param Mage_Connect_Package $package - * @return void - */ - public function outputPackage($package) - { - $fields = array( - 'Name'=>'name', - 'Version'=>'version', - 'Stability'=>'stability', - 'Description' => 'description', - 'Date' => 'date', - 'Authors' => 'authors', - ); - - foreach($fields as $title => $fld) { - $method = "get".ucfirst($fld); - $data = $package->$method(); - if(empty($data)) { - continue; - } - $this->write($title.": "); - if(is_array($data)) { - $this->write(print_r($data,true)); - } else { - $this->write($data); - } - $this->writeln(''); - } - } - - - /** - * Write channels list - * @param array $data - * @return void - */ - public function writeChannelsList($data) - { - $this->writeln("Channels available: "); - $this->writeln("==================="); - $out = $data['byName']; - ksort($out); - foreach($out as $k=>$v) { - $this->printf ("%-20s %-20s\n", $k, $v); - } - } - - /** - * Write installed list - * @param array $data - * @return void - */ - public function writeInstalledList($data) - { - $totalCount = 0; - foreach($data['data'] as $channel=>$packages) { - $title = sprintf($data['channel-title'], $channel); - $c = count($packages); - $totalCount += $c; - if(!$c) { - continue; - } - $this->writeln($title); - foreach($packages as $name=>$row) { - $this->printf("%-20s %-20s\n", $name, $row['version']." ".$row['stability']); - } - } - if($totalCount === 0) { - $this->writeln("No installed packages"); - } - } - - /** - * Output commands list - * @param array $data - * @return void - */ - public function outputCommandList($data) - { - $this->writeln("Connect commands available:"); - $this->writeln("==========================="); - foreach ($data as $k=>$v) { - $this->printf ("%-20s %-20s\n", $k, $v['summary']); - } - } - - /** - * Output config - * @param array $data - * @return void - */ - public function outputConfig($data) - { - foreach($data['data'] as $name=>$row) { - $value = $row['value'] === '' ? "" : strval($row['value']); - $this->printf("%-30s %-20s %-20s\n", $row['prompt'], $name, $value); - } - } - - /** - * Output config variable - * @param string $key - * @param string $value - * @return void - */ - public function outputConfigVariable($key, $value) - { - if($value === '') { - $value = ''; - } - $this->writeln("Config variable '{$key}': {$value}"); - } - - /** - * Write data and "\n" afterwards - * @param string $data - * @return void - */ - public function writeln($data = '') - { - $this->write($data."\n"); - } - - - /** - * get output, clear if needed - * - * @param bool $clearPrevoius optional, true by default - * @return array - */ - public function getOutput($clearPrevious = true) - { - $out = $this->_output; - if($clearPrevious) { - $this->_output = array(); - } - return $out; - } - - /** - * Write data to console - * @param string $data - * @return void - */ - public function write($data) - { - if($this->isSilent()) { - return; - } - print $data; - } - - /** - * Output printf-stlye formatted string and args - * @return void - */ - public function printf() - { - $args = func_get_args(); - $this->write(call_user_func_array('sprintf', $args)); - } - - /** - * Readline from console - * @return string - */ - public function readln() - { - $out = ""; - $key = fgetc(STDIN); - while ($key!="\n") { - $out.= $key; - $key = fread(STDIN, 1); - } - return $out; - } - - /** - * Output upgrades - * @param array $data - * @return void - */ - public function outputUpgrades($data) - { - foreach($data['data'] as $chan => $packages) { - $this->writeln("Updates for ".$chan.": "); - foreach($packages as $name => $data) { - $this->writeln(" $name: {$data['from']} => {$data['to']}"); - } - } - } - -} - diff --git a/downloader/lib/Mage/Connect/Ftp.php b/downloader/lib/Mage/Connect/Ftp.php deleted file mode 100644 index 2da949a24d9..00000000000 --- a/downloader/lib/Mage/Connect/Ftp.php +++ /dev/null @@ -1,533 +0,0 @@ - - */ -class Mage_Connect_Ftp -{ - /** - * Connection object - * - * @var resource - */ - protected $_conn = false; - - /** - * Check connected, throw exception if not - * - * @throws Exception - * @return null - */ - protected function checkConnected() - { - if(!$this->_conn) { - throw new Exception(__CLASS__." - no connection established with server"); - } - } - - /** - * ftp_mkdir wrapper - * - * @param string $name - * @return string - */ - public function mdkir($name) - { - $this->checkConnected(); - return @ftp_mkdir($this->_conn, $name); - } - - /** - * Make dir recursive - * - * @param string $path - * @param int $mode - */ - public function mkdirRecursive($path, $mode = 0777) - { - $this->checkConnected(); - $dir = explode('/', $path); - $path= ""; - $ret = true; - for ($i=0; $i < count($dir); $i++) { - $path .= "/" .$dir[$i]; - if(!@ftp_chdir($this->_conn, $path)) { - @ftp_chdir($this->_conn,"/"); - if(!@ftp_mkdir($this->_conn,$path)) { - $ret=false; - break; - } else { - @ftp_chmod($this->_conn, $mode, $path); - } - } - } - return $ret; - } - - /** - * Try to login to server - * - * @param string $login - * @param string $password - * @throws Exception on invalid login credentials - * @return boolean - */ - public function login($login = "anonymous", $password = "test@gmail.com") - { - $this->checkConnected(); - $res = @ftp_login($this->_conn, $login, $password); - if(!$res) { - throw new Exception("Invalid login credentials"); - } - return $res; - } - - /** - * Validate connection string - * - * @param string $string - * @throws Exception - * @return string - */ - public function validateConnectionString($string) - { - if (empty($string)) { - throw new Exception("Connection string is empty"); - } - $data = @parse_url($string); - if(false === $data) { - throw new Exception("Connection string invalid: '{$string}'"); - } - if($data['scheme'] != 'ftp') { - throw new Exception("Support for scheme '{$data['scheme']}' unsupported"); - } - return $data; - } - - /** - * Connect to server using connect string - * Connection string: ftp://user:pass@server:port/path - * user,pass,port,path are optional parts - * - * @param string $string - * @param int $timeout - * @return null - */ - public function connect($string, $timeout = 90) - { - $params = $this->validateConnectionString($string); - $port = isset($params['port']) ? intval($params['port']) : 21; - - $this->_conn = @ftp_connect($params['host'], $port, $timeout); - - if(!$this->_conn) { - throw new Exception("Cannot connect to host: {$params['host']}"); - } - ftp_pasv($this->_conn, true); - if(isset($params['user']) && isset($params['pass'])) { - $this->login($params['user'], $params['pass']); - } else { - $this->login(); - } - if(isset($params['path'])) { - if(!$this->chdir($params['path'])) { - throw new Exception ("Cannot chdir after login to: {$params['path']}"); - } - } - } - - /** - * ftp_fput wrapper - * - * @param string $remoteFile - * @param resource $handle - * @param int $mode FTP_BINARY | FTP_ASCII - * @param int $startPos - * @return boolean - */ - public function fput($remoteFile, $handle, $mode = FTP_BINARY, $startPos = 0) - { - $this->checkConnected(); - return @ftp_fput($this->_conn, $remoteFile, $handle, $mode, $startPos); - } - - /** - * ftp_put wrapper - * - * @param string $remoteFile - * @param string $localFile - * @param int $mode FTP_BINARY | FTP_ASCII - * @param int $startPos - * @return boolean - */ - public function put($remoteFile, $localFile, $mode = FTP_BINARY, $startPos = 0) - { - $this->checkConnected(); - return @ftp_put($this->_conn, $remoteFile, $localFile, $mode, $startPos); - } - - /** - * Get current working directory - * - * @return string - */ - public function getcwd() - { - $d = $this->raw("pwd"); - $data = explode(" ", $d[0], 3); - if(empty($data[1])) { - return false; - } - if(intval($data[0]) != 257) { - return false; - } - $out = trim($data[1], '"'); - if($out !== "/") { - $out = rtrim($out, "/"); - } - return $out; - } - - /** - * ftp_raw wrapper - * - * @param string $cmd - * @return array - */ - public function raw($cmd) - { - $this->checkConnected(); - return @ftp_raw($this->_conn, $cmd); - } - - /** - * Upload local file to remote server. - * Can be used for relative and absoulte remote paths - * Relative: use chdir before calling this - * - * @param string $remote - * @param string $local - * @param int $dirMode - * @param int $fileMode - * @return boolean - */ - public function upload($remote, $local, $dirMode = 0777, $fileMode=0) - { - $this->checkConnected(); - - if(!file_exists($local)) { - throw new Exception("Local file doesn't exist: {$local}"); - } - if(!is_readable($local)) { - throw new Exception("Local file is not readable: {$local}"); - } - if(is_dir($local)) { - throw new Exception("Directory given instead of file: {$local}"); - } - - $globalPathMode = substr($remote, 0, 1) == "/"; - $dirname = dirname($remote); - $cwd = $this->getcwd(); - if(false === $cwd) { - throw new Exception("Server returns something awful on PWD command"); - } - - if(!$globalPathMode) { - $dirname = $cwd."/".$dirname; - $remote = $cwd."/".$remote; - } - $res = $this->mkdirRecursive($dirname, $dirMode); - $this->chdir($cwd); - - if(!$res) { - return false; - } - $res = $this->put($remote, $local); - - if(!$res) { - return false; - } - - if($fileMode){ - $res=$this->chmod($fileMode, $remote); - } - return (boolean)$res; - } - - /** - * Download remote file to local machine - * - * @param string $remote - * @param string $local - * @param int $ftpMode FTP_BINARY|FTP_ASCII - * @return boolean - */ - public function download($remote, $local, $ftpMode = FTP_BINARY) - { - $this->checkConnected(); - return $this->get($local, $remote, $ftpMode); - } - - /** - * ftp_pasv wrapper - * - * @param boolean $pasv - * @return boolean - */ - public function pasv($pasv) - { - $this->checkConnected(); - return @ftp_pasv($this->_conn, (boolean) $pasv); - } - - /** - * Close FTP connection - * - * @return null - */ - public function close() - { - if($this->_conn) { - @ftp_close($this->_conn); - } - } - - /** - * ftp_chmod wrapper - * - * @param $mode - * @param $remoteFile - * @return boolean - */ - public function chmod($mode, $remoteFile) - { - $this->checkConnected(); - return @ftp_chmod($this->_conn, $mode, $remoteFile); - } - - /** - * ftp_chdir wrapper - * - * @param string $dir - * @return boolean - */ - public function chdir($dir) - { - $this->checkConnected(); - return @ftp_chdir($this->_conn, $dir); - } - - /** - * ftp_cdup wrapper - * - * @return boolean - */ - public function cdup() - { - $this->checkConnected(); - return @ftp_cdup($this->_conn); - } - - /** - * ftp_get wrapper - * - * @param string $localFile - * @param string $remoteFile - * @param int $fileMode FTP_BINARY | FTP_ASCII - * @param int $resumeOffset - * @return boolean - */ - public function get($localFile, $remoteFile, $fileMode = FTP_BINARY, $resumeOffset = 0) - { - $remoteFile = $this->correctFilePath($remoteFile); - $this->checkConnected(); - return @ftp_get($this->_conn, $localFile, $remoteFile, $fileMode, $resumeOffset); - } - - /** - * ftp_nlist wrapper - * - * @param string $dir - * @return boolean - */ - public function nlist($dir = "/") - { - $this->checkConnected(); - $dir = $this->correctFilePath($dir); - return @ftp_nlist($this->_conn, $dir); - } - - /** - * ftp_rawlist wrapper - * - * @param string $dir - * @param boolean $recursive - * @return array - */ - public function rawlist( $dir = "/", $recursive = false ) - { - $this->checkConnected(); - $dir = $this->correctFilePath($dir); - return @ftp_rawlist($this->_conn, $dir, $recursive); - } - - /** - * Convert byte count to float KB/MB format - * - * @param int $bytes - * @return string - */ - public static function byteconvert($bytes) - { - $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - $exp = floor( log($bytes) / log(1024) ); - return sprintf( '%.2f ' . $symbol[ $exp ], ($bytes / pow(1024, floor($exp))) ); - } - - /** - * Chmod string "-rwxrwxrwx" to "777" converter - * - * @param string $chmod - * @return string - */ - public static function chmodnum($chmod) - { - $trans = array('-' => '0', 'r' => '4', 'w' => '2', 'x' => '1'); - $chmod = substr(strtr($chmod, $trans), 1); - $array = str_split($chmod, 3); - return array_sum(str_split($array[0])) . array_sum(str_split($array[1])) . array_sum(str_split($array[2])); - } - - /** - * Checks file exists - * - * @param string $path - * @param boolean $excludeIfIsDir - * @return boolean - */ - public function fileExists($path, $excludeIfIsDir = true) - { - $path = $this->correctFilePath($path); - $globalPathMode = substr($path, 0, 1) == "/"; - - $file = basename($path); - $dir = $globalPathMode ? dirname($path) : $this->getcwd()."/".($path==basename($path)?'':$path); - $data = $this->ls($dir); - foreach($data as $row) { - if($file == basename($row['name'])) { - if($excludeIfIsDir && $row['dir']) { - continue; - } - return true; - } - } - return false; - } - - /** - * Get directory contents in PHP array - * - * @param string $dir - * @param boolean $recursive - * @return array - */ - public function ls($dir = "/", $recursive = false) - { - $dir= $this->correctFilePath($dir); - $rawfiles = (array) $this->rawlist($dir, $recursive); - $structure = array(); - $arraypointer = &$structure; - foreach ($rawfiles as $rawfile) { - if ($rawfile[0] == '/') { - $paths = array_slice(explode('/', str_replace(':', '', $rawfile)), 1); - $arraypointer = &$structure; - foreach ($paths as $path) { - foreach ($arraypointer as $i => $file) { - if ($file['name'] == $path) { - $arraypointer = &$arraypointer[ $i ]['children']; - break; - } - } - } - } elseif(!empty($rawfile)) { - $info = preg_split("/[\s]+/", $rawfile, 9); - $arraypointer[] = array( - 'name' => $info[8], - 'dir' => $info[0][0] == 'd', - 'size' => (int) $info[4], - 'chmod' => self::chmodnum($info[0]), - 'rawdata' => $info, - 'raw' => $rawfile - ); - } - } - return $structure; - } - - /** - * Correct file path - * - * @param $str - * @return string - */ - public function correctFilePath($str) - { - $str = str_replace("\\", "/", $str); - $str = preg_replace("/^.\//", "", $str); - return $str; - } - - /** - * Delete file - * - * @param string $file - * @return boolean - */ - public function delete($file) - { - $this->checkConnected(); - $file = $this->correctFilePath($file); - return @ftp_delete($this->_conn, $file); - } - - /** - * Remove directory - * - * @param string $dir - * @return boolean - */ - public function rmdir($dir) - { - $this->checkConnected(); - $dir = $this->correctFilePath($dir); - return @ftp_rmdir($this->_conn, $dir); - } -} diff --git a/downloader/lib/Mage/Connect/Loader.php b/downloader/lib/Mage/Connect/Loader.php deleted file mode 100644 index d962a8d11b0..00000000000 --- a/downloader/lib/Mage/Connect/Loader.php +++ /dev/null @@ -1,50 +0,0 @@ - - */ -class Mage_Connect_Loader -{ - /** - * Factory for HTTP client - * - * @param string|false $protocol 'curl'/'socket' or false for auto-detect - * @return Mage_HTTP_IClient|Mage_Connect_Loader_Ftp - */ - public static function getInstance($protocol='') - { - if ($protocol == 'ftp') { - return new Mage_Connect_Loader_Ftp(); - } else { - return Mage_HTTP_Client::getInstance(); - } - } -} diff --git a/downloader/lib/Mage/Connect/Loader/Ftp.php b/downloader/lib/Mage/Connect/Loader/Ftp.php deleted file mode 100644 index a2ef07a4252..00000000000 --- a/downloader/lib/Mage/Connect/Loader/Ftp.php +++ /dev/null @@ -1,155 +0,0 @@ - - */ -class Mage_Connect_Loader_Ftp -{ - - const TEMPORARY_DIR = '../var/package/tmp'; - - const FTP_USER = 'anonymous'; - - const FTP_PASS = 'test@gmail.com'; - - /** - * Object of Ftp - * - * @var Mage_Connect_Ftp - */ - protected $_ftp = null; - - /** - * User name - * @var string - */ - protected $_ftpUser = ''; - - /** - * User password - * @var string - */ - protected $_ftpPassword = ''; - - /** - * Response body - * @var string - */ - protected $_responseBody = ''; - - /** - * Response status - * @var int - */ - protected $_responseStatus = 0; - - /** - * Constructor - */ - public function __construct() - { - $this->_ftp = new Mage_Connect_Ftp(); - $this->_ftpUser = self::FTP_USER; - $this->_ftpPassword = self::FTP_PASS; - } - - public function getFtp() - { - return $this->_ftp; - } - - /** - * Retrieve file from URI - * - * @param mixed $uri - * @return bool - */ - public function get($uri) - { - $remoteFile = basename($uri); - $uri = dirname($uri); - $uri = str_replace('http://', '', $uri); - $uri = str_replace('https://', '', $uri); - $uri = str_replace('ftp://', '', $uri); - $uri = $this->_ftpUser.":".$this->_ftpPassword."@".$uri; - $this->getFtp()->connect("ftp://".$uri); - $this->getFtp()->pasv(true); - $tmpDir = self::TEMPORARY_DIR . DS; - if (!is_dir($tmpDir)) { - $tmpDir = sys_get_temp_dir(); - } - if (substr($tmpDir, -1) != DS) { - $tmpDir .= DS; - } - $localFile = $tmpDir . time() . ".xml"; - - if ($this->getFtp()->get($localFile, $remoteFile)) { - $this->_responseBody = file_get_contents($localFile); - $this->_responseStatus = 200; - } - @unlink($localFile); - $this->getFtp()->close(); - return $this; - } - - /** - * Get response status code - * - * @return string - */ - public function getStatus() - { - return $this->_responseStatus; - } - - /** - * put your comment there... - * - * @return string - */ - public function getBody() - { - return $this->_responseBody; - } - - /** - * Set login credentials for ftp auth. - * @param string $ftpLogin Ftp User account name - * @param string $ftpPassword User password - * @return string - */ - public function setCredentials($ftpLogin, $ftpPassword) - { - $this->_ftpUser = $ftpLogin; - $this->_ftpPassword = $ftpPassword; - } - -} diff --git a/downloader/lib/Mage/Connect/Package.php b/downloader/lib/Mage/Connect/Package.php deleted file mode 100644 index 060616129af..00000000000 --- a/downloader/lib/Mage/Connect/Package.php +++ /dev/null @@ -1,1505 +0,0 @@ - - */ -class Mage_Connect_Package -{ - - const PACKAGE_XML_DIR = 'var/package'; - - /** - * Contain SimpleXMLElement for composing document. - * - * @var SimpleXMLElement - */ - protected $_packageXml; - - /** - * Internal cache - * - * @var array - */ - protected $_authors; - - /** - * Internal cache - * - * @var array - */ - protected $_contents; - - /** - * Internal cache - * - * @var array - */ - protected $_hashContents; - - /** - * Internal cache - * - * @var array - */ - protected $_compatible; - - /** - * Internal cache - * - * @var array - */ - protected $_dependencyPhpExtensions; - - /** - * Internal cache - * - * @var array - */ - protected $_dependencyPackages; - - /** - * A helper object that can read from a package archive - * - * @var Mage_Connect_Package_Reader - */ - protected $_reader; - - /** - * A helper object that can create and write to a package archive - * - * @var Mage_Connect_Package_Writer - */ - protected $_writer; - - /** - * Validator object - * - * @var Mage_Connect_Validator - */ - protected $_validator = null; - - /** - * Validation errors - * - * @var array - */ - protected $_validationErrors = array(); - - /** - * Object with target - * - * @var Mage_Connect_Package_Target - */ - protected $_target = null; - - /** - * Config object - * - * @var Mage_Connect_Config - */ - protected $_config = null; - - /** - * Creates a package object (empty, or from existing archive, or from package definition xml) - * - * @param null|string|resource $source - */ - public function __construct($source=null) - { - libxml_use_internal_errors(true); - - if (is_string($source)) { - // check what's in the string (a package definition or a package filename) - if (0 === strpos($source, "_init($source); - } elseif (is_file($source) && is_readable($source)) { - // package archive filename - $this->_loadFile($source); - } else { - throw new Mage_Exception('Invalid package source'); - } - } elseif (is_resource($source)) { - $this->_loadResource($source); - } elseif (is_null($source)) { - $this->_init(); - } else { - throw new Mage_Exception('Invalid package source'); - } - } - - /** - * Initializes an empty package object - * - * @param null|string $definition optional package definition xml - * @return Mage_Connect_Package - */ - protected function _init($definition=null) - { - - if (!is_null($definition)) { - $this->_packageXml = simplexml_load_string($definition); - } else { - $packageXmlStub = << - - - - - - - - - - - - -