public function uploadAction() { $this->_helper->viewRenderer->setNoRender(true); $this->view->layout()->disableLayout(true); $adapter = new Zend_ProgressBar_Adapter_JsPush(array('updateMethodName' => 'Zend_ProgressBar_Update', 'finishMethodName' => 'Zend_ProgressBar_Finish')); $progressBar = new Zend_ProgressBar($adapter, 0, 100); for ($i = 1; $i <= 100; $i++) { if ($i < 20) { $text = 'Just beginning'; } else { if ($i < 50) { $text = 'A bit done'; } else { if ($i < 80) { $text = 'Getting closer'; } else { $text = 'Nearly done'; } } } $progressBar->update($i, $text); usleep(100000); } $progressBar->finish(); }
public function initialSync($processInCli = true) { $stepSize = 100; $format = self::_optimalImportExportFormat($this->getProxyModel(), $this->getSourceModel()); $count = $this->_sourceModel->countRows(); $progress = null; if (PHP_SAPI == 'cli' && $processInCli) { $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_ETA, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $progress = new Zend_ProgressBar($c, 0, $count); } $startTime = microtime(true); $this->getProxyModel()->deleteRows(array()); //alles löschen for ($offset = 0; $offset < $count; $offset += $stepSize) { $s = new Kwf_Model_Select(); $s->limit($stepSize, $offset); /* $data = $this->_sourceModel->export($format, $s); $this->getProxyModel()->import($format, $data); */ //warning: slow code ahead foreach ($this->_sourceModel->getRows($s) as $row) { $data = $row->toArray(); $newRow = $this->createRow($data); foreach ($this->getDependentModels() as $rule => $depModel) { if ($depModel instanceof Kwf_Model_RowsSubModel_MirrorCacheSimple) { //dieser code könne vielleicht im Kwf_Model_RowsSubModel_MirrorCacheSimple liegen $m = $depModel->getSourceModel(); $ref = $m->getReferenceByModelClass(get_class($this), null); $select = new Kwf_Model_Select(); $select->whereEquals($ref['column'], $row->{$this->getPrimaryKey()}); $childRows = $m->getRows($select); foreach ($childRows as $childRow) { $newCRow = $newRow->createChildRow($rule, $childRow->toArray()); } } } $newRow->save(); } unset($row); unset($newRow); unset($newCRow); unset($childRows); unset($childRow); foreach (self::getInstances() as $m) { $m->clearRows(); } //echo round(memory_get_usage()/(1024*1024), 3)."MB\n"; if ($progress) { $text = round(($offset + $stepSize) / (microtime(true) - $startTime)) . ' rows/sec'; $progress->next($stepSize, $text); } } }
public function duplicateChild($source, $parentTarget, Zend_ProgressBar $progressBar = null) { if ($progressBar) { $progressBar->next(); } if ($source->generator !== $this) { throw new Kwf_Exception("you must call this only with the correct source"); } $id = $source->id; $target = $parentTarget->getChildComponent(array('id' => $id, 'ignoreVisible' => true)); if (!$target) { return null; } Kwc_Admin::getInstance($source->componentClass)->duplicate($source, $target, $progressBar); return $target; }
public function uploadAction() { $adapter = new Zend_ProgressBar_Adapter_JsPush(array('updateMethodName' => 'Zend_ProgressBar_Update', 'finishMethodName' => 'Zend_ProgressBar_Finish')); $progressBar = new Zend_ProgressBar($adapter, 0, 100); for ($i = 1; $i <= 100; $i++) { if ($i < 20) { $text = 'Just beginning'; } else { if ($i < 50) { $text = 'A bit done'; } else { if ($i < 80) { $text = 'Getting closer'; } else { $text = 'Nearly done'; } } } $progressBar->update($i, $text); usleep(100000); } $progressBar->finish(); }
private function _executeUpdatesAction($method) { $ret = true; foreach ($this->_updates as $update) { Kwf_Model_Abstract::clearInstances(); //wegen eventueller meta-data-caches die sich geändert haben Kwf_Component_Generator_Abstract::clearInstances(); Kwf_Component_Data_Root::reset(); if ($this->_progressBar && $method == 'update') { $this->_progressBar->next(1, $update->getUniqueName()); } $e = false; try { if (!$this->_verbose) { ob_start(); //update script should not output anything, if it still does discard it } $update->{$method}(); if (!$this->_verbose) { ob_end_clean(); } } catch (Exception $e) { if (!$this->_verbose) { ob_end_clean(); } if ($this->_debug) { throw $e; } $this->_errors[] = array('name' => $update->getUniqueName(), 'message' => $e->getMessage()); if ($this->_verbose) { echo "\n[31mError:[0m\n"; echo $e->getMessage() . "\n\n"; flush(); } $ret = false; } } return $ret; }
/** * @param array possible options: types(=all), output(=false), refresh(=true), excludeTypes, skipMaintenanceBootstrap, skipOtherServers */ public final function clearCache(array $options) { $typeNames = $options['types']; $output = isset($options['output']) ? $options['output'] : false; $refresh = isset($options['refresh']) ? $options['refresh'] : false; $excludeTypes = isset($options['excludeTypes']) ? $options['excludeTypes'] : array(); Kwf_Events_ModelObserver::getInstance()->disable(); Kwf_Util_MemoryLimit::set(512); if (!isset($options['skipMaintenanceBootstrap']) || !$options['skipMaintenanceBootstrap']) { Kwf_Util_Maintenance::writeMaintenanceBootstrap($output); } if ($typeNames == 'all') { $types = $this->getTypes(); } else { if (!is_array($typeNames)) { $typeNames = explode(',', $typeNames); } $types = array(); foreach ($this->getTypes() as $t) { if (in_array($t->getTypeName(), $typeNames)) { $types[] = $t; } } } if (is_string($excludeTypes)) { $excludeTypes = explode(',', $excludeTypes); } foreach ($types as $k => $i) { if (in_array($i->getTypeName(), $excludeTypes)) { unset($types[$k]); } } $maxTypeNameLength = 0; $countSteps = 0; foreach ($types as $type) { $type->setVerbosity($output ? Kwf_Util_ClearCache_Types_Abstract::VERBOSE : Kwf_Util_ClearCache_Types_Abstract::SILENT); $maxTypeNameLength = max($maxTypeNameLength, strlen($type->getTypeName())); if ($type->doesClear()) { $countSteps++; } if ($type->doesRefresh()) { $countSteps++; } } $progress = null; if (isset($options['progressAdapter'])) { $progress = new Zend_ProgressBar($options['progressAdapter'], 0, $countSteps); } $currentStep = 0; foreach ($types as $type) { if ($type->doesClear()) { $currentStep++; if ($progress) { $progress->next(1, "clearing " . $type->getTypeName()); } if ($output) { echo "[" . str_repeat(' ', 2 - strlen($currentStep)) . "{$currentStep}/{$countSteps}] "; echo "clearing " . $type->getTypeName() . "..." . str_repeat('.', $maxTypeNameLength - strlen($type->getTypeName())) . " "; } $t = microtime(true); $type->clearCache($options); if ($output) { if ($type->getSuccess()) { echo "[00;32mOK[00m"; } else { echo " [[01;31mERROR[00m]"; } echo " (" . round((microtime(true) - $t) * 1000) . "ms)"; echo "\n"; } } } if ($refresh) { foreach ($types as $type) { if ($type->doesRefresh()) { $currentStep++; if ($progress) { $progress->next(1, "refreshing " . $type->getTypeName()); } if ($output) { echo "[{$currentStep}/{$countSteps}] refreshing " . $type->getTypeName() . "." . str_repeat('.', $maxTypeNameLength - strlen($type->getTypeName())) . " "; } $t = microtime(true); $mem = memory_get_usage(); $type->refreshCache($options); if ($output) { if ($type->getSuccess()) { echo "[00;32mOK[00m"; } else { echo " [[01;31mERROR[00m]"; } echo " (" . round((microtime(true) - $t) * 1000) . "ms"; if (memory_get_usage() - $mem > 1024 * 1024) { echo ", " . round((memory_get_usage() - $mem) / (1024 * 1024), 2) . "MB"; } echo ")\n"; } } } } /* TODO re-enable this somehow * required at all? * own type? or should the different types each also clear the other servers (apc does that already) $skipOtherServers = isset($options['skipOtherServers']) ? $options['skipOtherServers'] : false; if (Kwf_Config::getValue('server.aws') && !$skipOtherServers) { $otherHostsTypes = $this->_getCacheDirs(); //add other types $otherHostsTypes[] = 'config'; $otherHostsTypes[] = 'setup'; $otherHostsTypes[] = 'component'; $otherHostsTypes[] = 'events'; $otherHostsTypes[] = 'trl'; $otherHostsTypes = array_unique($otherHostsTypes); if (in_array('all', $types)) { //use all of $otherHostsTypes } else { $otherHostsTypes = array_intersect($otherHostsTypes, $types); } if ($otherHostsTypes) { $domains = Kwf_Util_Aws_Ec2_InstanceDnsNames::getOther(); foreach ($domains as $domain) { if ($output) { echo "executing clear-cache on $domain:\n"; } $cmd = Kwf_Config::getValue('server.phpCli')." bootstrap.php clear-cache --type=".implode(',', $otherHostsTypes).' --skip-other-servers'; $cmd = "ssh -o 'StrictHostKeyChecking no' $domain ".escapeshellarg('cd '.Kwf_Config::getValue('server.dir').'; '.$cmd); passthru($cmd); if ($output) { echo "\n"; } } } } */ if (!isset($options['skipMaintenanceBootstrap']) || !$options['skipMaintenanceBootstrap']) { Kwf_Util_Maintenance::restoreMaintenanceBootstrap($output); } Kwf_Events_ModelObserver::getInstance()->enable(); return $types; }
public function duplicateChild($source, $parentTarget, Zend_ProgressBar $progressBar = null) { if ($progressBar) { $progressBar->next(); } $progressBar = null; //stop here, as getDuplicateProgressSteps doesn't go any deeper if ($source->generator !== $this) { throw new Kwf_Exception("you must call this only with the correct source"); } $ev = new Kwf_Component_Event_Component_FilterAddComponentClass($source->componentClass, $parentTarget); Kwf_Events_Dispatcher::fireEvent($ev); if ($ev->deny) { return null; } $newRow = $this->_duplicateRow($source, $parentTarget); if (!$newRow) { return null; } $id = $this->_idSeparator . $newRow->{$this->_getModel()->getPrimaryKey()}; $targetGen = Kwf_Component_Generator_Abstract::getInstance($parentTarget->componentClass, $this->getGeneratorKey()); $targetChildData = $targetGen->getChildData($parentTarget, array('id' => $id, 'ignoreVisible' => true, 'limit' => 1)); $target = array_pop($targetChildData); if (!$target) { return null; } Kwc_Admin::getInstance($source->componentClass)->duplicate($source, $target, $progressBar); return $target; }
if ($threadCount == 1) { exec($child . " {$i} {$batchSize} >> " . dirname(__FILE__) . "/url_migration.log 2>&1", $output, $status); } else { waitForChildren($processesCheck, $threadCount); exec($child . " {$i} {$batchSize} >> " . dirname(__FILE__) . "/url_migration.log 2>&1 &", $output, $status); } $progressBar->update(++$i, ''); } if ($threadCount != 1) { waitForChildren($processesCheck, 1); } $progressBar->finish(); $cpbAdapter = new Zend_ProgressBar_Adapter_Console(array('elements' => array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_ETA, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT))); $logger->info('Creating redirects from previous version...'); $batches = ceil($totalRows / $batchSize); $categoriesProgressBar = new Zend_ProgressBar($cpbAdapter, 0, $batches); $child = 'php -f ' . dirname(__FILE__) . '/umt113_redirect.php --'; $processesCheck = "ps x | grep \"{$child}\" | grep -v grep"; $i = 0; for (; $batches; $batches--) { $output = ''; if ($threadCount == 1) { exec($child . " {$i} {$batchSize} >> " . dirname(__FILE__) . "/url_migration.log 2>&1", $output, $status); } else { waitForChildren($processesCheck, $threadCount); exec($child . " {$i} {$batchSize} >> " . dirname(__FILE__) . "/url_migration.log 2>&1 &", $output, $status); } $categoriesProgressBar->update(++$i, ''); } if ($threadCount != 1) { waitForChildren($processesCheck, 1);
* * @category Zend * @package Zend_ProgressBar * @subpackage Demos * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * This sample file demonstrates a simple use case of a jspush-driven progressbar */ if (isset($_GET['progress'])) { set_include_path(realpath(dirname(__FILE__) . '/../../../library') . PATH_SEPARATOR . get_include_path()); require_once 'Zend/ProgressBar.php'; require_once 'Zend/ProgressBar/Adapter/JsPush.php'; $adapter = new Zend_ProgressBar_Adapter_JsPush(array('updateMethodName' => 'Zend_ProgressBar_Update', 'finishMethodName' => 'Zend_ProgressBar_Finish')); $progressBar = new Zend_ProgressBar($adapter, 0, 100); for ($i = 1; $i <= 100; $i++) { if ($i < 20) { $text = 'Just beginning'; } else { if ($i < 50) { $text = 'A bit done'; } else { if ($i < 80) { $text = 'Getting closer'; } else { $text = 'Nearly done'; } } } $progressBar->update($i, $text);
/** * Since many operations can take quite a long time for large cache pools, * this might help ease the waiting time with a nice console progress bar. * * @return Zend_ProgressBar A fresh Zend_ProgressBar instance */ protected function _getProgressBar($min, $max) { $progressBar = new Zend_ProgressBar(new Zend_ProgressBar_Adapter_Console(), $min, $max); $progressBar->getAdapter()->setFinishAction(Zend_ProgressBar_Adapter_Console::FINISH_ACTION_CLEAR_LINE); return $progressBar; }
public function deleteViewCache($select, $progressBarAdapter = null) { $microtime = $this->_getMicrotime(); $select->whereEquals('deleted', false); $model = $this->getModel(); $log = Kwf_Events_Log::getInstance(); $cacheIds = array(); $options = array('columns' => array('component_id', 'renderer', 'type', 'value')); $partialIds = array(); $deleteIds = array(); $checkIncludeIds = array(); $rows = $model->export(Kwf_Model_Abstract::FORMAT_ARRAY, $select, $options); $progress = null; if ($progressBarAdapter) { $count = count($rows); $steps = (int) (count($rows) * 2 / 100 + 3); $step = 0; $progress = new Zend_ProgressBar($progressBarAdapter, 0, $steps); } foreach ($rows as $key => $row) { if ($progress && $key % 100 == 0) { $step += 100; $progress->next(1, "viewcache {$step} / {$count}"); } $cacheIds[] = $this->_getCacheId($row['component_id'], $row['renderer'], $row['type'], $row['value']); Kwf_Benchmark::countLog('viewcache-delete-' . $row['type']); if ($row['type'] != 'fullPage' && !isset($checkIncludeIds[$row['component_id']])) { $checkIncludeIds[$row['component_id']] = true; } if ($log) { $log->log("delete view cache {$row['component_id']} {$row['renderer']} {$row['type']} {$row['value']}", Zend_Log::INFO); } $type = $row['type']; $value = $row['value']; $cId = $row['component_id']; if ($type == 'partial' && $value != '') { if (!isset($partialIds[$cId])) { $partialIds[$cId] = array(); } $partialIds[$cId][] = $value; } else { if ($value == '') { if (!isset($deleteIds[$type])) { $deleteIds[$type] = array(); } $deleteIds[$type][] = $cId; } else { throw new Kwf_Exception('Should not happen.'); } } } // Memcache $this->_beforeMemcacheDelete($select); // For unit testing - DO NOT DELETE! if ($progress) { $step = 0; } foreach ($cacheIds as $key => $cacheId) { if ($progress && $key % 100 == 0) { $step += 100; $progress->next(1, "memcache {$step} / {$count}"); } Kwf_Component_Cache_Memory::getInstance()->remove($cacheId, $microtime); } $this->_afterMemcacheDelete($select); // For unit testing - DO NOT DELETE! // FullPage if ($progress) { $progress->next(1, "fullPage"); } $s = new Kwf_Model_Select(); $s->whereEquals('type', 'fullPage'); if ($checkIncludeIds) { $ids = array_keys($this->_fetchIncludesTree(array_keys($checkIncludeIds))); if ($ids) { foreach ($ids as &$id) { $id = (string) $id; } unset($id); $s->whereEquals('component_id', $ids); if ($log) { foreach ($ids as $id) { $log->log("type=fullPage component_id={$id}", Zend_Log::INFO); } } $this->deleteViewCache($s); } } // Database $this->_beforeDatabaseDelete($select); // For unit testing - DO NOT DELETE! if ($progress) { $progress->next(1, "partialIds"); } foreach ($partialIds as $componentId => $values) { $select = $model->select(); $select->where(new Kwf_Model_Select_Expr_And(array(new Kwf_Model_Select_Expr_Equals('component_id', (string) $componentId), new Kwf_Model_Select_Expr_Equals('type', 'partial'), new Kwf_Model_Select_Expr_Equals('value', $values), new Kwf_Model_Select_Expr_LowerEqual('microtime', $microtime)))); $model->updateRows(array('deleted' => true), $select); } if ($progress) { $progress->next(1, "deleteIds"); } foreach ($deleteIds as $type => $componentIds) { $select = $model->select(); $select->where(new Kwf_Model_Select_Expr_And(array(new Kwf_Model_Select_Expr_Equals('component_id', $componentIds), new Kwf_Model_Select_Expr_Equals('type', $type), new Kwf_Model_Select_Expr_LowerEqual('microtime', $microtime)))); $model->updateRows(array('deleted' => true), $select); } $this->_afterDatabaseDelete($select); // For unit testing - DO NOT DELETE! if ($progress) { $progress->finish(); } file_put_contents('log/clear-view-cache', date('Y-m-d H:i:s') . ' ' . round(microtime(true) - Kwf_Benchmark::$startTime, 2) . 's; ' . Kwf_Events_Dispatcher::$eventsCount . ' events; ' . count($deleteIds) . ' view cache entries deleted; ' . (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '') . "\n", FILE_APPEND); return count($cacheIds); }
/** * @param array possible options: types(=all), output(=false), refresh(=true), excludeTypes */ public final function clearCache(array $options) { $typeNames = $options['types']; $output = isset($options['output']) ? $options['output'] : false; $refresh = isset($options['refresh']) ? $options['refresh'] : false; $excludeTypes = isset($options['excludeTypes']) ? $options['excludeTypes'] : array(); Kwf_Events_ModelObserver::getInstance()->disable(); Kwf_Util_MemoryLimit::set(512); if ($typeNames == 'all') { $types = $this->getTypes(); } else { if (!is_array($typeNames)) { $typeNames = explode(',', $typeNames); } $types = array(); foreach ($this->getTypes() as $t) { if (in_array($t->getTypeName(), $typeNames)) { $types[] = $t; } } } if (is_string($excludeTypes)) { $excludeTypes = explode(',', $excludeTypes); } foreach ($types as $k => $i) { if (in_array($i->getTypeName(), $excludeTypes)) { unset($types[$k]); } } $maxTypeNameLength = 0; $countSteps = 0; foreach ($types as $type) { $type->setVerbosity($output ? Kwf_Util_ClearCache_Types_Abstract::VERBOSE : Kwf_Util_ClearCache_Types_Abstract::SILENT); $maxTypeNameLength = max($maxTypeNameLength, strlen($type->getTypeName())); if ($type->doesClear()) { $countSteps++; } if ($type->doesRefresh()) { $countSteps++; } } $progress = null; if (isset($options['progressAdapter'])) { $progress = new Zend_ProgressBar($options['progressAdapter'], 0, $countSteps); } $currentStep = 0; foreach ($types as $type) { if ($type->doesClear()) { $currentStep++; if ($progress) { $progress->next(1, "clearing " . $type->getTypeName()); } if ($output) { echo "[" . str_repeat(' ', 2 - strlen($currentStep)) . "{$currentStep}/{$countSteps}] "; echo "clearing " . $type->getTypeName() . "..." . str_repeat('.', $maxTypeNameLength - strlen($type->getTypeName())) . " "; } $t = microtime(true); $type->clearCache($options); if ($output) { if ($type->getSuccess()) { echo "[00;32mOK[00m"; } else { echo " [[01;31mERROR[00m]"; } echo " (" . round((microtime(true) - $t) * 1000) . "ms)"; echo "\n"; } } } if ($refresh) { foreach ($types as $type) { if ($type->doesRefresh()) { $currentStep++; if ($progress) { $progress->next(1, "refreshing " . $type->getTypeName()); } if ($output) { echo "[{$currentStep}/{$countSteps}] refreshing " . $type->getTypeName() . "." . str_repeat('.', $maxTypeNameLength - strlen($type->getTypeName())) . " "; } $t = microtime(true); $mem = memory_get_usage(); $type->refreshCache($options); if ($output) { if ($type->getSuccess()) { echo "[00;32mOK[00m"; } else { echo " [[01;31mERROR[00m]"; } echo " (" . round((microtime(true) - $t) * 1000) . "ms"; if (memory_get_usage() - $mem > 1024 * 1024) { echo ", " . round((memory_get_usage() - $mem) / (1024 * 1024), 2) . "MB"; } echo ")\n"; } } } } Kwf_Events_ModelObserver::getInstance()->enable(); return $types; }
/** * Action - pdf * сreate a PDF document using the mPDF library * * Access to the action is possible in the following paths: * - /admin/tools/pdf * * @return void */ public function pdfAction() { $isCommonFont = false; $pdfParams = array(); //--------------------- // Получим параметры $params = $this->getRequest()->getParams(); $report = $params['name']; // Определим параметры для конвертации HTML в PDF switch ($report) { case 'phpinfo': // Установим параметры для отчета $html = Default_Plugin_SysBox::getPHPInfo(); $pdfParams['pdfReport'] = $report; $pdfParams['html'] = $html; $pdfParams['isCommonFont'] = true; $pdfParams['pathStylesheet'] = 'css/report/phpinfo.css'; $pdfParams['headerLeftMargin'] = 'Params of PHP'; $pdfParams['headerCentreMargin'] = Default_Plugin_SysBox::getFullURL_Res('/images/system/settings32x32.png'); $pdfParams['footerRightMargin'] = Default_Plugin_SysBox::getFullUrl_For_FilePDF($report); break; case 'zend-progress': $adapter = new Zend_ProgressBar_Adapter_JsPush(array('updateMethodName' => 'BSA.Dialogs.Zend_ProgressBar_Update', 'finishMethodName' => 'BSA.Dialogs.Zend_ProgressBar_Finish')); $progressBar = new Zend_ProgressBar($adapter, 0, 100); for ($i = 1; $i <= 100; $i++) { if ($i < 20) { $text = 'Just beginning'; } else { if ($i < 50) { $text = 'A bit done'; } else { if ($i < 80) { $text = 'Getting closer'; } else { $text = 'Nearly done'; } } } $progressBar->update($i, $text); usleep(100000); } $progressBar->finish(); die; break; default: break; } // Создать PDF файл из HTML $urlFilePDF = Default_Plugin_SysBox::mpdfGenerator_Html2PDF($pdfParams); // Установим свой и предыдущий Breadcrumbs $Zend_Auth = Zend_Registry::get("Zend_Auth"); $lastBreadcrumbs = $Zend_Auth->lastBreadcrumbs; $this->_breadcrumbs->addStep($lastBreadcrumbs['title'], $this->getUrl($lastBreadcrumbs['action'], $lastBreadcrumbs['controller'], $lastBreadcrumbs['module'])); $this->_breadcrumbs->addStep($this->Translate('Отчет в PDF формате')); $this->view->urlFilePDF = $urlFilePDF; }
protected function _build($options) { if (!file_exists('build/assets')) { mkdir('build/assets'); } Kwf_Assets_BuildCache::getInstance()->building = true; Kwf_Assets_BuildCache::getInstance()->clean(); Kwf_Assets_BuildCache::getInstance()->save(time(), 'assetsVersion'); $langs = $this->getAllLanguages(); $packages = $this->getAllPackages(); $exts = array('js', 'defer.js', 'css', 'ie8.css', 'ie8.js'); $providers = array(); foreach ($packages as $p) { foreach ($p->getProviderList()->getProviders() as $provider) { if (!in_array($provider, $providers)) { $providers[] = $provider; } } } echo "\ninitializing providers...\n"; $steps = count($providers); $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(80); $progress = new Zend_ProgressBar($c, 0, $steps); foreach ($providers as $provider) { $progress->next(1, get_class($provider)); $provider->initialize(); } $progress->finish(); echo "calculating dependencies...\n"; $steps = count($packages) * count($exts); $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(80); $progress = new Zend_ProgressBar($c, 0, $steps); $countDependencies = 0; foreach ($packages as $p) { $depName = $p->getDependencyName(); foreach ($exts as $extension) { $progress->next(1, "{$depName} {$extension}"); $p->getFilteredUniqueDependencies(self::$_mimeTypeByExtension[$extension]); } $it = new RecursiveIteratorIterator(new Kwf_Assets_Dependency_Iterator_UniqueFilter(new Kwf_Assets_Dependency_Iterator_Recursive($p->getDependency(), Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_ALL)), RecursiveIteratorIterator::CHILD_FIRST); foreach ($it as $i) { $countDependencies++; } } $progress->finish(); echo "compiling assets...\n"; $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_ETA, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(80); $progress = new Zend_ProgressBar($c, 0, $countDependencies); foreach ($packages as $p) { $it = new RecursiveIteratorIterator(new Kwf_Assets_Dependency_Iterator_UniqueFilter(new Kwf_Assets_Dependency_Iterator_Recursive($p->getDependency(), Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_ALL)), RecursiveIteratorIterator::CHILD_FIRST); foreach ($it as $dep) { $progress->next(1, "{$dep}"); if ($dep->getMimeType()) { $mimeType = $dep->getMimeType(); $p->warmupDependencyCaches($dep, $mimeType, $progress); if ($mimeType == 'text/css') { $p->warmupDependencyCaches($dep, 'text/css; ie8', $progress); } } } } $progress->finish(); echo "generating package urls...\n"; $steps = count($packages) * count($langs) * count($exts); $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(80); $progress = new Zend_ProgressBar($c, 0, $steps); $allUrls = array(); foreach ($packages as $p) { $depName = $p->getDependencyName(); foreach ($langs as $language) { foreach ($exts as $extension) { $progress->next(1, "{$depName} {$extension} {$language}"); $urls = $p->getPackageUrls(self::$_mimeTypeByExtension[$extension], $language); if (Kwf_Setup::getBaseUrl()) { foreach ($urls as $k => $i) { $urls[$k] = substr($i, strlen(Kwf_Setup::getBaseUrl())); } } $cacheId = $p->getPackageUrlsCacheId(self::$_mimeTypeByExtension[$extension], $language); Kwf_Assets_BuildCache::getInstance()->save($urls, $cacheId); foreach ($urls as $url) { if (!in_array($url, $allUrls)) { $allUrls[] = $url; } } } } } echo "generating package contents...\n"; $steps = count($allUrls) * 2; $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(80); $progress = new Zend_ProgressBar($c, 0, $steps); foreach ($allUrls as $url) { if (substr($url, 0, 8) != '/assets/') { continue; } $param = explode('/', $url); if (count($param) != 7) { continue; } $dependencyClass = $param[3]; $dependencyParams = $param[4]; $urlLanguage = $param[5]; $urlExtension = $param[6]; $urlExtension = substr($urlExtension, 0, strpos($urlExtension, '?')); if (!class_exists($dependencyClass)) { throw new Kwf_Exception(); } if (!is_instance_of($dependencyClass, 'Kwf_Assets_Interface_UrlResolvable')) { throw new Kwf_Exception(); } $p = call_user_func(array($dependencyClass, 'fromUrlParameter'), $dependencyClass, $dependencyParams); if (!$p instanceof Kwf_Assets_Package) { throw new Kwf_Exception(); } $contents = $p->getUrlContents($urlExtension, $urlLanguage); $progress->next(1, "{$p->getDependencyName()} {$urlExtension} {$urlLanguage} source"); $cacheId = Kwf_Assets_Dispatcher::getInstance()->getCacheIdByPackage($p, $urlExtension, $urlLanguage); Kwf_Assets_BuildCache::getInstance()->save($contents, $cacheId); //save generated caches for clear-cache-watcher $fileName = 'build/assets/output-cache-ids-' . $urlExtension; if (!file_exists($fileName) || strpos(file_get_contents($fileName), $cacheId . "\n") === false) { file_put_contents($fileName, $cacheId . "\n", FILE_APPEND); } $contents = $p->getUrlContents($urlExtension . '.map', $urlLanguage); $progress->next(1, "{$p->getDependencyName()} {$urlExtension} {$urlLanguage} map"); $cacheId = Kwf_Assets_Dispatcher::getInstance()->getCacheIdByPackage($p, $urlExtension . '.map', $urlLanguage); Kwf_Assets_BuildCache::getInstance()->save($contents, $cacheId); } Kwf_Assets_Cache::getInstance()->clean(); Kwf_Assets_BuildCache::getInstance()->building = false; }
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * This sample file demonstrates a simple use case of a jspull-driven progressbar */ if (isset($_GET['uploadId'])) { set_include_path(realpath(dirname(__FILE__) . '/../../../library') . PATH_SEPARATOR . get_include_path()); // require_once 'Zend/ProgressBar.php'; // require_once 'Zend/ProgressBar/Adapter/JsPull.php'; // require_once 'Zend/Session/Namespace.php'; $data = uploadprogress_get_info($_GET['uploadId']); $bytesTotal = $data === null ? 0 : $data['bytes_total']; $bytesUploaded = $data === null ? 0 : $data['bytes_uploaded']; $adapter = new Zend_ProgressBar_Adapter_JsPull(); $progressBar = new Zend_ProgressBar($adapter, 0, $bytesTotal, 'uploadProgress'); if ($bytesTotal === $bytesUploaded) { $progressBar->finish(); } else { $progressBar->update($bytesUploaded); } } ?> <html> <head> <title>Zend_ProgressBar Upload Demo</title> <style type="text/css"> iframe { position: absolute; left: -100px; top: -100px;
/** * @param array possible options: types(=all), output(=false), excludeTypes */ public final function build(array $options) { $typeNames = $options['types']; $output = isset($options['output']) ? $options['output'] : false; $excludeTypes = isset($options['excludeTypes']) ? $options['excludeTypes'] : array(); Kwf_Cache_SimpleStatic::disableFileCache(); Kwf_Events_ModelObserver::getInstance()->disable(); Kwf_Util_MemoryLimit::set(1024 * 2); Kwf_Registry::set('db', false); if ($typeNames == 'all') { $types = $this->getTypes(); } else { if (!is_array($typeNames)) { $typeNames = explode(',', $typeNames); } $types = array(); foreach ($this->getTypes() as $t) { if (in_array($t->getTypeName(), $typeNames)) { $types[] = $t; } } } if (is_string($excludeTypes)) { $excludeTypes = explode(',', $excludeTypes); } foreach ($types as $k => $i) { if (in_array($i->getTypeName(), $excludeTypes)) { unset($types[$k]); } } $maxTypeNameLength = 0; $countSteps = 0; foreach ($types as $type) { $type->setVerbosity($output ? Kwf_Util_Build_Types_Abstract::VERBOSE : Kwf_Util_Build_Types_Abstract::SILENT); $maxTypeNameLength = max($maxTypeNameLength, strlen($type->getTypeName())); $countSteps++; } $progress = null; if (isset($options['progressAdapter'])) { $progress = new Zend_ProgressBar($options['progressAdapter'], 0, $countSteps); } if (!file_exists('build')) { mkdir('build'); } $currentStep = 0; foreach ($types as $type) { $currentStep++; if ($progress) { $progress->next(1, "building " . $type->getTypeName()); } if ($output) { echo "[" . str_repeat(' ', 2 - strlen($currentStep)) . "{$currentStep}/{$countSteps}] "; echo "building " . $type->getTypeName() . "..." . str_repeat('.', $maxTypeNameLength - strlen($type->getTypeName())) . " "; } $t = microtime(true); $type->build($options); if ($output) { if ($type->getSuccess()) { echo "[00;32mOK[00m"; } else { echo " [[01;31mERROR[00m]"; return false; } echo " (" . round((microtime(true) - $t) * 1000) . "ms)"; echo "\n"; } } Kwf_Events_ModelObserver::getInstance()->enable(); return $types; }
protected function _build($options) { if (!file_exists('build/assets')) { mkdir('build/assets'); } Kwf_Assets_BuildCache::getInstance()->building = true; Kwf_Assets_BuildCache::getInstance()->clean(); Kwf_Assets_BuildCache::getInstance()->save(time(), 'assetsVersion'); $langs = $this->getAllLanguages(); $packages = $this->getAllPackages(); $exts = array('js', 'defer.js', 'css'); echo "\ncalculating dependencies...\n"; $steps = count($packages) * count($exts); $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(50); $progress = new Zend_ProgressBar($c, 0, $steps); $countDependencies = 0; foreach ($packages as $p) { $depName = $p->getDependencyName(); foreach ($exts as $extension) { $progress->next(1, "{$depName} {$extension}"); $p->getFilteredUniqueDependencies(self::$_mimeTypeByExtension[$extension]); $cacheId = $p->getMaxMTimeCacheId(self::$_mimeTypeByExtension[$extension]); if (!$cacheId) { throw new Kwf_Exception("Didn't get cacheId for " . get_class($p)); } $maxMTime = $p->getMaxMTime(self::$_mimeTypeByExtension[$extension]); Kwf_Assets_BuildCache::getInstance()->save($maxMTime, $cacheId); //save generated caches for clear-cache-watcher $fileName = 'build/assets/package-max-mtime-' . $extension; if (!file_exists($fileName) || strpos(file_get_contents($fileName), $cacheId . "\n") === false) { file_put_contents($fileName, $cacheId . "\n", FILE_APPEND); } } $it = new RecursiveIteratorIterator(new Kwf_Assets_Dependency_Iterator_UniqueFilter(new Kwf_Assets_Dependency_Iterator_Recursive($p->getDependency(), Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_ALL)), RecursiveIteratorIterator::CHILD_FIRST); foreach ($it as $i) { $countDependencies++; } } $progress->finish(); echo "compiling assets...\n"; $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(50); $progress = new Zend_ProgressBar($c, 0, $countDependencies); foreach ($packages as $p) { $it = new RecursiveIteratorIterator(new Kwf_Assets_Dependency_Iterator_UniqueFilter(new Kwf_Assets_Dependency_Iterator_Recursive($p->getDependency(), Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_ALL)), RecursiveIteratorIterator::CHILD_FIRST); foreach ($it as $dep) { $progress->next(1, "{$dep}"); $dep->warmupCaches(); } } $progress->finish(); echo "generating packages...\n"; $steps = count($packages) * count($langs) * count($exts) * 4; $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(50); $progress = new Zend_ProgressBar($c, 0, $steps); foreach ($packages as $p) { $depName = $p->getDependencyName(); foreach ($langs as $language) { foreach ($exts as $extension) { $progress->next(1, "{$depName} {$extension} {$language}"); $packageContents = $p->getPackageContents(self::$_mimeTypeByExtension[$extension], $language); $maxMTime = $p->getMaxMTime(self::$_mimeTypeByExtension[$extension]); $progress->next(1, "{$depName} {$extension} {$language} source"); $this->_buildPackageContents($packageContents, $maxMTime, $p, $extension, $language); $progress->next(1, "{$depName} {$extension} {$language} map"); $this->_buildPackageSourceMap($packageContents, $maxMTime, $p, $extension, $language); $progress->next(1, "{$depName} {$extension} {$language} url"); $urls = $p->getPackageUrls(self::$_mimeTypeByExtension[$extension], $language); if (Kwf_Setup::getBaseUrl()) { foreach ($urls as $k => $i) { $urls[$k] = substr($i, strlen(Kwf_Setup::getBaseUrl())); } } $cacheId = $p->getPackageUrlsCacheId(self::$_mimeTypeByExtension[$extension], $language); Kwf_Assets_BuildCache::getInstance()->save($urls, $cacheId); } } } Kwf_Assets_Cache::getInstance()->clean(); Kwf_Assets_BuildCache::getInstance()->building = false; }
private function _duplicatePageRecursive($parentSourceId, $parentTargetId, $childId, Zend_ProgressBar $progressBar = null) { $pd = $this->_getPageData($childId); if ($progressBar) { $progressBar->next(1, trlKwf("Pasting {0}", $pd['name'])); } $data = array(); $data['parent_id'] = Kwf_Component_Data_Root::getInstance()->getComponentById($parentTargetId, array('ignoreVisible' => true))->dbId; $sourceRow = $this->getModel()->getRow($childId); if ($sourceRow->is_home) { //copy is_home only if target has no home yet $t = Kwf_Component_Data_Root::getInstance()->getComponentById($parentTargetId, array('ignoreVisible' => true)); while ($t && !Kwc_Abstract::getFlag($t->componentClass, 'hasHome')) { $t = $t->parent; } if (!$t || $t->getChildPage(array('home' => true, 'ignoreVisible' => true), array())) { $data['is_home'] = false; } } $newRow = $sourceRow->duplicate($data); //clear cache in here as while duplicating the modelobserver might be disabled Kwf_Cache_Simple::delete('pcIds-' . $newRow->parent_id); //ids are numeric, we don't have to use parentSource/parentTarget $source = Kwf_Component_Data_Root::getInstance()->getComponentById($childId, array('ignoreVisible' => true)); $target = Kwf_Component_Data_Root::getInstance()->getComponentById($newRow->id, array('ignoreVisible' => true)); if (!$target) { throw new Kwf_Exception("didn't find just duplicated component '{$newRow->id}' below '{$parentTarget->componentId}'"); } Kwc_Admin::getInstance($source->componentClass)->duplicate($source, $target, $progressBar); $sourceId = $source->componentId; $targetId = $target->componentId; unset($source); unset($target); unset($sourceRow); unset($newRow); /* echo round(memory_get_usage()/1024/1024, 2)."MB"; echo " gen: ".Kwf_Component_Generator_Abstract::$objectsCount.', '; echo " data: ".Kwf_Component_Data::$objectsCount.', '; echo " row: ".Kwf_Model_Row_Abstract::$objectsCount.''; $s = microtime(true); */ Kwf_Component_Data_Root::getInstance()->freeMemory(); /* echo ' / '.round((microtime(true)-$s)*1000, 2).' ms '; echo ' / '.round(memory_get_usage()/1024/1024, 2)."MB"; echo " gen: ".Kwf_Component_Generator_Abstract::$objectsCount.', '; echo " data: ".Kwf_Component_Data::$objectsCount.', '; echo " row: ".Kwf_Model_Row_Abstract::$objectsCount.''; //var_dump(Kwf_Model_Row_Abstract::$objectsByModel); //var_dump(Kwf_Component_Data::$objectsById); echo "\n"; */ foreach ($this->_getChildPageIds($childId) as $i) { if ($i != $targetId) { //no endless recursion id page is pasted below itself $this->_duplicatePageRecursive($sourceId, $targetId, $i, $progressBar); } } return $targetId; }
protected function _build($options) { if (!file_exists('build/assets')) { mkdir('build/assets'); } Kwf_Assets_BuildCache::getInstance()->building = true; Kwf_Assets_BuildCache::getInstance()->clean(); Kwf_Assets_BuildCache::getInstance()->save(time(), 'assetsVersion'); $langs = $this->_getAllLanguages(); $packages = $this->_getAllPackages(); $exts = array('js', 'defer.js', 'css', 'printcss'); echo "\ncalculating dependencies...\n"; $steps = count($packages) * count($exts); $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(50); $progress = new Zend_ProgressBar($c, 0, $steps); $countDependencies = 0; foreach ($packages as $p) { $depName = $p->getDependencyName(); foreach ($exts as $extension) { $progress->next(1, "{$depName} {$extension}"); $countDependencies += count($p->getFilteredUniqueDependencies(self::$_mimeTypeByExtension[$extension])); $cacheId = $p->getMaxMTimeCacheId(self::$_mimeTypeByExtension[$extension]); if (!$cacheId) { throw new Kwf_Exception("Didn't get cacheId for " . get_class($p)); } $maxMTime = $p->getMaxMTime(self::$_mimeTypeByExtension[$extension]); Kwf_Assets_BuildCache::getInstance()->save($maxMTime, $cacheId); //save generated caches for clear-cache-watcher $fileName = 'build/assets/package-max-mtime-' . $extension; if (!file_exists($fileName) || strpos(file_get_contents($fileName), $cacheId . "\n") === false) { file_put_contents($fileName, $cacheId . "\n", FILE_APPEND); } } } $progress->finish(); echo "compiling assets...\n"; $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(50); $progress = new Zend_ProgressBar($c, 0, $countDependencies); foreach ($packages as $p) { foreach ($exts as $extension) { foreach ($p->getFilteredUniqueDependencies(self::$_mimeTypeByExtension[$extension]) as $dep) { $progress->next(1, "{$dep}"); $dep->warmupCaches(); } } } $progress->finish(); echo "generating packages...\n"; $steps = count($packages) * count($langs) * count($exts) * 4; $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT)); $c->setTextWidth(50); $progress = new Zend_ProgressBar($c, 0, $steps); foreach ($packages as $p) { $depName = $p->getDependencyName(); foreach ($langs as $language) { foreach ($exts as $extension) { $packageContents = $p->getPackageContents(self::$_mimeTypeByExtension[$extension], $language); $maxMTime = $p->getMaxMTime(self::$_mimeTypeByExtension[$extension]); $progress->next(1, "{$depName} {$extension} {$language}"); $progress->next(1, "{$depName} {$extension} {$language} source"); $this->_buildPackageContents($packageContents, $maxMTime, $p, $extension, $language); $progress->next(1, "{$depName} {$extension} {$language} map"); $this->_buildPackageSourceMap($packageContents, $maxMTime, $p, $extension, $language); $progress->next(1, "{$depName} {$extension} {$language} url"); $urls = $p->getPackageUrls(self::$_mimeTypeByExtension[$extension], $language); if (Kwf_Setup::getBaseUrl()) { foreach ($urls as $k => $i) { $urls[$k] = substr($i, strlen(Kwf_Setup::getBaseUrl())); } } $cacheId = $p->getPackageUrlsCacheId(self::$_mimeTypeByExtension[$extension], $language); Kwf_Assets_BuildCache::getInstance()->save($urls, $cacheId); } } } Kwf_Assets_Cache::getInstance()->clean(); Kwf_Assets_BuildCache::getInstance()->building = false; $exts = array('js', 'defer.js', 'css'); foreach ($packages as $p) { $depName = $p->getDependencyName(); $language = $langs[0]; foreach ($exts as $extension) { $cacheId = Kwf_Assets_Dispatcher::getCacheIdByPackage($p, $extension, $language); $cacheContents = Kwf_Assets_BuildCache::getInstance()->load($cacheId); echo "{$depName} "; $h = new Kwf_View_Helper_FileSize(); echo "{$extension} size: " . $h->fileSize(strlen(gzencode($cacheContents['contents'], 9, FORCE_GZIP))); echo "\n"; } } $d = Kwf_Assets_Package_Default::getDefaultProviderList()->findDependency('Frontend'); foreach ($d->getFilteredUniqueDependencies('text/javascript') as $i) { if ($i instanceof Kwf_Assets_Dependency_File && $i->getType() == 'ext2') { echo "\n[WARNING] Frontend text/javascript contains ext2\n"; echo "To improve frontend performance all ext2 dependencies should be moved to defer\n\n"; break; } } }
/** * Returns the actual progress of file up-/downloads * * @param string $id The upload to get the progress for * @return array|null */ public static function getProgress($id = null) { if (!function_exists('apc_fetch') and !function_exists('uploadprogress_get_info')) { // require_once 'Zend/File/Transfer/Exception.php'; throw new Zend_File_Transfer_Exception('Neither APC nor uploadprogress extension installed'); } $session = 'Zend_File_Transfer_Adapter_Http_ProgressBar'; $status = array('total' => 0, 'current' => 0, 'rate' => 0, 'message' => '', 'done' => false); if (is_array($id)) { if (isset($id['progress'])) { $adapter = $id['progress']; } if (isset($id['session'])) { $session = $id['session']; } if (isset($id['id'])) { $id = $id['id']; } else { unset($id); } } if (!empty($id) && ($id instanceof Zend_ProgressBar_Adapter || $id instanceof Zend_ProgressBar)) { $adapter = $id; unset($id); } if (empty($id)) { if (!isset($_GET['progress_key'])) { $status['message'] = 'No upload in progress'; $status['done'] = true; } else { $id = $_GET['progress_key']; } } if (!empty($id)) { if (self::isApcAvailable()) { $call = call_user_func(self::$_callbackApc, ini_get('apc.rfc1867_prefix') . $id); if (is_array($call)) { $status = $call + $status; } } else { if (self::isUploadProgressAvailable()) { $call = call_user_func(self::$_callbackUploadProgress, $id); if (is_array($call)) { $status = $call + $status; $status['total'] = $status['bytes_total']; $status['current'] = $status['bytes_uploaded']; $status['rate'] = $status['speed_average']; if ($status['total'] == $status['current']) { $status['done'] = true; } } } } if (!is_array($call)) { $status['done'] = true; $status['message'] = 'Failure while retrieving the upload progress'; } else { if (!empty($status['cancel_upload'])) { $status['done'] = true; $status['message'] = 'The upload has been canceled'; } else { $status['message'] = self::_toByteString($status['current']) . " - " . self::_toByteString($status['total']); } } $status['id'] = $id; } if (isset($adapter) && isset($status['id'])) { if ($adapter instanceof Zend_ProgressBar_Adapter) { // require_once 'Zend/ProgressBar.php'; $adapter = new Zend_ProgressBar($adapter, 0, $status['total'], $session); } if (!$adapter instanceof Zend_ProgressBar) { // require_once 'Zend/File/Transfer/Exception.php'; throw new Zend_File_Transfer_Exception('Unknown Adapter given'); } if ($status['done']) { $adapter->finish(); } else { $adapter->update($status['current'], $status['message']); } $status['progress'] = $adapter; } return $status; }
public static function downloadUpdates($request, $view) { $urls = array(); if ($request->getParam('libraryUrl')) { $urls['library.tar.gz'] = $request->getParam('libraryUrl'); } $urls['kwf.tar.gz'] = $request->getParam('kwfUrl'); $urls['app.tar.gz'] = $request->getParam('appUrl'); $c = new Kwf_Util_ProgressBar_Adapter_Cache($request->getParam('progressNum')); $progress = new Zend_ProgressBar($c, 0, 6); foreach ($urls as $target => $url) { $progress->next(1, 'Downloading ' . $target); exec("wget -O " . escapeshellarg($target) . " " . escapeshellarg($url) . " 2>&1", $out, $ret); if ($ret) { throw new Kwf_Exception_Client("Download Failed:" . implode("\n", $out)); } } foreach ($urls as $target => $url) { $progress->next(1, 'Extracting ' . $target); $dir = tempnam('.', 'downloader'); unlink($dir); mkdir($dir); exec("tar xfz {$target} -C {$dir}" . " 2>&1", $out, $ret); if ($ret) { throw new Kwf_Exception_Client("Extraction failed"); } $dirs = glob("{$dir}/*"); if (count($dirs) != 1) { throw new Kwf_Exception_Client("more than one directory extracted"); } if (!is_dir($dirs[0])) { throw new Kwf_Exception_Client("no directory extracted"); } if ($target == 'app.tar.gz') { //move away current files to backup $backupDir = uniqid("backup" . date('Y-m-d')) . 'app'; mkdir($backupDir); $it = new DirectoryIterator(getcwd()); foreach ($it as $file) { if ($file->isDot()) { continue; } if (substr($file->getFilename(), -4) == '-lib' || $file->getFilename() == 'library') { continue; } if (substr($file->getFilename(), 0, 6) == 'backup') { continue; } if ($file->getFilename() == 'config.local.ini') { continue; } if ($file->getFilename() == 'config_section') { continue; } if ($file->getFilename() == 'php.ini') { continue; } //php config might be in document_root (wtf, godaddy) if ($file->getFilename() == 'php5.ini') { continue; } //php config might be in document_root (wtf, godaddy) if ($file->getFilename() == $backupDir) { continue; } if ($file->getPathname() == $dir) { continue; } if ($file->getFilename() == 'app.tar.gz') { continue; } if ($file->getFilename() == 'temp') { continue; } if ($file->getFilename() == 'log') { continue; } if ($file->getFilename() == 'uploads') { continue; } rename($file->getPathname(), $backupDir . '/' . $file->getFilename()); } //move in new files $it = new DirectoryIterator($dirs[0]); foreach ($it as $file) { if ($file->isDot()) { continue; } if ($file->getFilename() == 'temp') { continue; } if ($file->getFilename() == 'log') { continue; } if ($file->getFilename() == 'uploads') { continue; } rename($file->getPathname(), './' . $file->getFilename()); } system("rm -r " . escapeshellarg($dirs[0])); $oldHtaccess = file_get_contents($backupDir . '/.htaccess'); if (!strpos('php_flag magic_quotes_gpc off', $oldHtaccess)) { $c = file_get_contents('.htaccess'); $c = str_replace('php_flag magic_quotes_gpc off', '', $c); file_put_contents('.htaccess', $c); } } else { $targetDir = false; if ($target == 'library.tar.gz') { $targetDir = 'library'; } else { if ($target == 'kwf.tar.gz') { $targetDir = 'kwf-lib'; copy($targetDir . '/include_path', $dirs[0] . '/include_path'); } } rename($targetDir, uniqid("backup" . date('Y-m-d')) . $targetDir); rename("{$dirs['0']}", $targetDir); } rmdir($dir); unlink($target); } Kwf_Util_ClearCache::getInstance()->clearCache(array('types' => 'all', 'output' => false, 'refresh' => true)); }