public function jsonDuplicateAction() { if (!isset($this->_permissions['duplicate']) || !$this->_permissions['duplicate']) { throw new Kwf_Exception("Duplicate is not allowed."); } $ids = $this->getRequest()->getParam($this->_primaryKey); $ids = explode(';', $ids); $this->view->data = array('duplicatedIds' => array()); $parentTarget = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($this->_getParam('componentId')); foreach ($ids as $id) { $sourceId = $this->_getParam('componentId') . '_' . $id; $source = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($sourceId); // Switch off observer due to performance - it's not necessary here Kwf_Events_ModelObserver::getInstance()->disable(); $newDetail = Kwf_Util_Component::duplicate($source, $parentTarget); Kwf_Util_Component::afterDuplicate($source, $newDetail); Kwf_Events_ModelObserver::getInstance()->enable(); $newDetailRow = $newDetail->row; $newDetailRow->create_date = date('Y-m-d H:i:s'); $newDetailRow->mails_per_minute = 'normal'; $newDetailRow->start_date = null; $newDetailRow->resume_date = null; $newDetailRow->last_sent_date = null; $newDetailRow->count_sent = null; $newDetailRow->status = null; $newDetailRow->save(); $mailRow = $newDetail->getChildComponent('_mail')->getComponent()->getRow(); $mailRow->subject = trlKwf('Copy of') . ' ' . $mailRow->subject; $mailRow->save(); } }
protected final function _process() { $filename = $this->_root->filename; Kwf_Events_ModelObserver::getInstance()->process(); Kwf_Component_Data_Root::reset(); $this->_root = Kwf_Component_Data_Root::getInstance(); $this->_root->setFilename($filename); }
public function tearDown() { Kwf_Events_ModelObserver::getInstance()->setSkipFnF(true); Kwf_Component_Data_Root::reset(); Kwf_Component_Cache::clearInstance(); Kwf_Model_Abstract::clearInstances(); Kwf_Events_Dispatcher::clearCache(); Kwf_Events_Subscriber::clearInstances(); Kwf_Component_PagesMetaModel::clearInstance(); Kwf_Trl::getInstance()->unsetTrlElements(); }
protected static function _callPostProcessInput($process) { $postData = self::_getRequestWithFiles(); foreach ($process as $i) { if (method_exists($i->getComponent(), 'postProcessInput')) { $i->getComponent()->postProcessInput($postData); } } if (class_exists('Kwf_Events_ModelObserver', false)) { //Nur wenn klasse jemals geladen wurde kann auch was zu processen drin sein Kwf_Events_ModelObserver::getInstance()->process(); } }
public function testClearOutputCacheWhenChangingCropOptions() { $this->assertEquals('dh-{width}-dc16b9', $this->_root->getComponentById('root_page')->getComponent()->getBaseType()); $dim = $this->_root->getComponentById('root_page')->getComponent()->getImageDimensions(); Kwf_Media::clearCache('Kwc_Basic_Image_Crop_ImageComponent', 'root_page', Kwf_Media::DONT_HASH_TYPE_PREFIX . $dim['width'] . '-dc16b9'); Kwc_Basic_Image_Crop_ImageComponent::$getMediaOutputCalled = 0; Kwf_Media::getOutput('Kwc_Basic_Image_Crop_ImageComponent', 'root_page', Kwf_Media::DONT_HASH_TYPE_PREFIX . $dim['width'] . '-dc16b9'); $this->assertEquals(1, Kwc_Basic_Image_Crop_ImageComponent::$getMediaOutputCalled); Kwf_Media::getOutput('Kwc_Basic_Image_Crop_ImageComponent', 'root_page', Kwf_Media::DONT_HASH_TYPE_PREFIX . $dim['width'] . '-dc16b9'); $this->assertEquals(1, Kwc_Basic_Image_Crop_ImageComponent::$getMediaOutputCalled); $c = $this->_root->getComponentById('root_page'); $row = Kwf_Model_Abstract::getInstance('Kwc_Basic_Image_Crop_TestModel')->getRow('root_page'); $row->crop_x = 20; $row->save(); Kwf_Events_ModelObserver::getInstance()->process(); Kwf_Media::getOutput('Kwc_Basic_Image_Crop_ImageComponent', 'root_page', Kwf_Media::DONT_HASH_TYPE_PREFIX . $dim['width'] . '-dc16b9'); $this->assertEquals(2, Kwc_Basic_Image_Crop_ImageComponent::$getMediaOutputCalled); }
public function processInput() { if (!$this->_getSetting('saveReferer')) { return; } if (!isset($_SERVER['HTTP_REFERER'])) { return; } if (!$_SERVER['HTTP_REFERER']) { return; } $referer = $_SERVER['HTTP_REFERER']; $host = parse_url($referer, PHP_URL_HOST); $allowedHosts = $this->_getSetting('allowedHosts'); if (preg_match('/^(www\\.)?((' . implode(')|(', $allowedHosts) . '))\\.[a-z]+$/i', $host)) { $model = $this->getChildModel(); $rowCompare = $model->getRow($model->select()->whereEquals('component_id', $this->getData()->componentId)->order('id', 'DESC')); $query = self::getQueryVar($referer); if ($query) { if ($rowCompare) { $hostCompare = parse_url($rowCompare->referer_url, PHP_URL_HOST); $queryCompare = self::getQueryVar($rowCompare->referer_url); } if ((!$rowCompare || $hostCompare != $host || $queryCompare != $query) && strpos($query, 'site:') === false) { $row = $model->createRow(); $row->component_id = $this->getData()->componentId; $row->referer_url = $referer; $row->save(); // alte löschen $select = new Kwf_Model_Select(); $select->whereEquals('component_id', $row->component_id)->order('id', 'DESC')->limit(20, 10); $deleteRows = $model->getRows($select); foreach ($deleteRows as $deleteRow) { $deleteRow->delete(); } Kwf_Events_ModelObserver::getInstance()->process(); } } else { file_put_contents('log/unknownsearchenginereferer', $referer . "\n", FILE_APPEND); } } }
public function import($format, $data, $options = array()) { if ($format == self::FORMAT_ARRAY) { if (isset($options['replace']) && $options['replace']) { throw new Kwf_Exception_NotYetImplemented(); } Kwf_Events_ModelObserver::getInstance()->disable(); foreach ($data as $k => $v) { $this->createRow($v)->save(); } Kwf_Events_ModelObserver::getInstance()->enable(); $this->_afterImport($format, $data, $options); } else { throw new Kwf_Exception_NotYetImplemented(); } }
/** * @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; }
public function testAction() { $source = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($this->_getParam('source'), array('ignoreVisible' => true)); if (!$source) { throw new Kwf_Exception_Client("source not found"); } $parentTarget = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($this->_getParam('target'), array('ignoreVisible' => true)); if (!$parentTarget) { throw new Kwf_Exception_Client("target not found"); } Kwf_Events_ModelObserver::getInstance()->disable(); //This would be slow as hell. But luckily we can be sure that for the new (duplicated) components there will be no view cache to clear. echo "counting pages..."; $steps = Kwf_Util_Component::getDuplicateProgressSteps($source); echo " " . $steps . "\n"; $ad = new Zend_ProgressBar_Adapter_Console(); $ad->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, Zend_ProgressBar_Adapter_Console::ELEMENT_TEXT, Zend_ProgressBar_Adapter_Console::ELEMENT_ETA)); $progressBar = new Zend_ProgressBar($ad, 0, $steps); $target = Kwf_Util_Component::duplicate($source, $parentTarget, $progressBar); Kwf_Util_Component::afterDuplicate($source, $target); $progressBar->finish(); exit; }
protected function _updateModelObserver($options, array $ids = null) { if (isset($options['skipModelObserver']) && $options['skipModelObserver']) { return; } Kwf_Events_ModelObserver::getInstance()->add('update', $this, $ids); }
public function testClearOutputCache() { $c = $this->_root->getComponentById('1600'); $this->assertEquals(Kwf_Media::DONT_HASH_TYPE_PREFIX . '{width}-76b7ff', $c->getComponent()->getBaseType()); Kwf_Media::clearCache('Kwc_Basic_Image_FixDimensionComponent', '1600', Kwf_Media::DONT_HASH_TYPE_PREFIX . '16-76b7ff'); Kwc_Basic_Image_FixDimensionComponent::$getMediaOutputCalled = 0; Kwf_Media::getOutput('Kwc_Basic_Image_FixDimensionComponent', '1600', Kwf_Media::DONT_HASH_TYPE_PREFIX . '16-76b7ff'); $this->assertEquals(1, Kwc_Basic_Image_FixDimensionComponent::$getMediaOutputCalled); Kwf_Media::getOutput('Kwc_Basic_Image_FixDimensionComponent', '1600', Kwf_Media::DONT_HASH_TYPE_PREFIX . '16-76b7ff'); $this->assertEquals(1, Kwc_Basic_Image_FixDimensionComponent::$getMediaOutputCalled); Kwf_Media::clearCache('Kwc_Basic_Image_FixDimensionComponent', '1600', Kwf_Media::DONT_HASH_TYPE_PREFIX . '16-76b7ff'); Kwf_Media::getOutput('Kwc_Basic_Image_FixDimensionComponent', '1600', Kwf_Media::DONT_HASH_TYPE_PREFIX . '16-76b7ff'); $this->assertEquals(2, Kwc_Basic_Image_FixDimensionComponent::$getMediaOutputCalled); $row = Kwf_Model_Abstract::getInstance('Kwc_Basic_Image_TestModel')->getRow('1600'); $row->kwf_upload_id = 2; $row->save(); Kwf_Events_ModelObserver::getInstance()->process(); Kwf_Component_Data_Root::reset(); Kwf_Media::getOutput('Kwc_Basic_Image_FixDimensionComponent', '1600', Kwf_Media::DONT_HASH_TYPE_PREFIX . '100-76b7ff'); $this->assertEquals(3, Kwc_Basic_Image_FixDimensionComponent::$getMediaOutputCalled); }
public function jsonPasteAction() { $session = new Kwf_Session_Namespace('Kwc_Paragraphs:copy'); $id = $session->id; if (!$id || !Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, array('ignoreVisible' => true))) { throw new Kwf_Exception_Client(trlKwf('Clipboard is empty')); } $target = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($this->_getParam('componentId'), array('ignoreVisible' => true)); $source = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, array('ignoreVisible' => true)); $c = $target; while ($c->parent) { if ($c->dbId == $source->dbId) { throw new Kwf_Exception_Client(trlKwf("You can't paste a paragraph into itself.")); } if ($c->isPage) { break; } $c = $c->parent; } $sourceIsParagraphs = is_instance_of($source->componentClass, 'Kwc_Paragraphs_Component'); if ($source->isPage && $sourceIsParagraphs) { //a whole paragraphs component is in clipboard $sources = $source->getChildComponents(array('generator' => 'paragraphs', 'ignoreVisible' => true)); } else { if (!$source->isPage && !is_instance_of($source->parent->componentClass, 'Kwc_Paragraphs_Component')) { //a whole paragraphs component is in clipboard $sources = $source->getChildComponents(array('generator' => 'paragraphs', 'ignoreVisible' => true)); } else { //a single paragraph (paragraphs child) is in clipboard $sources = array($source); } } $classes = Kwc_Abstract::getChildComponentClasses($target->componentClass, 'paragraphs'); Kwf_Events_ModelObserver::getInstance()->disable(); //This would be slow as hell. But luckily we can be sure that for the new (duplicated) components there will be no view cache to clear. $progressBar = new Zend_ProgressBar(new Kwf_Util_ProgressBar_Adapter_Cache($this->_getParam('progressNum')), 0, Kwf_Util_Component::getDuplicateProgressSteps($source)); $newPos = $this->_getParam('pos'); $countDuplicated = 0; $errorMsg = false; foreach ($sources as $s) { $targetCls = false; if (isset($classes[$s->row->component])) { $targetCls = $classes[$s->row->component]; } $sourceCls = $s->componentClass; $sourceCls = strpos($sourceCls, '.') ? substr($sourceCls, 0, strpos($sourceCls, '.')) : $sourceCls; $targetCls = strpos($targetCls, '.') ? substr($targetCls, 0, strpos($targetCls, '.')) : $targetCls; if ($sourceCls != $targetCls) { if (Kwc_Abstract::hasSetting($s->componentClass, 'componentName')) { $name = Kwf_Trl::getInstance()->trlStaticExecute(Kwc_Abstract::getSetting($s->componentClass, 'componentName')); $errorMsg = trlKwf("Can't paste paragraph type '{0}', as it is not avaliable here.", $name); } else { $errorMsg = trlKwf('Source and target paragraphs are not compatible.'); } continue; //skip this one } $newParagraph = Kwf_Util_Component::duplicate($s, $target, $progressBar); $countDuplicated++; $row = $newParagraph->row; $row->pos = $newPos++; $row->visible = false; $row->save(); } Kwf_Util_Component::afterDuplicate($source, $target); $progressBar->finish(); Kwf_Events_ModelObserver::getInstance()->enable(); if (!$countDuplicated && $errorMsg) { //if at least one was duplicated show no error, else show one throw new Kwf_Exception_Client($errorMsg); } }
public function jsonPasteAction() { $this->_validateMaxEntries(); $session = new Kwf_Session_Namespace('Kwc_Abstract_List:copy'); $id = $session->id; if (!$id || !Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, array('ignoreVisible' => true))) { throw new Kwf_Exception_Client(trlKwf('Clipboard is empty')); } $target = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($this->_getParam('componentId'), array('ignoreVisible' => true)); $source = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, array('ignoreVisible' => true)); if ($source->parent->componentClass != $target->componentClass) { throw new Kwf_Exception_Client(trlKwf('Source and target paragraphs are not compatible.')); } Kwf_Events_ModelObserver::getInstance()->disable(); //This would be slow as hell. But luckily we can be sure that for the new (duplicated) components there will be no view cache to clear. $progressBar = null; $newItem = Kwf_Util_Component::duplicate($source, $target, $progressBar); $row = $newItem->row; $target->getChildComponents(array('ignoreVisible' => true)); $row->pos = null; //moves to end of list $row->visible = false; $row->save(); Kwf_Util_Component::afterDuplicate($source, $target); Kwf_Events_ModelObserver::getInstance()->enable(); }
private function _unlockSync() { $this->_lockCount--; if ($this->_lockCount == 0) { fclose($this->_lockSync); $this->_lockSync = null; $observedRows = $this->_observedRows; $this->_observedRows = array(); foreach ($observedRows as $action => $rows) { foreach ($rows as $row) { Kwf_Events_ModelObserver::getInstance()->add($action, $row); } } } }
public function sendAction() { $this->_helper->viewRenderer->setNoRender(true); Kwf_Events_ModelObserver::getInstance()->disable(); $newsletterId = $this->_getParam('newsletterId'); $nlRow = Kwf_Model_Abstract::getInstance('Kwc_Newsletter_Model')->getRow($newsletterId); $mailsPerMinute = $nlRow->getCountOfMailsPerMinute(); // In Schleife senden $queueLogModel = $nlRow->getModel()->getDependentModel('QueueLog'); $count = 0; $countErrors = 0; $countNoUser = 0; $start = microtime(true); do { // Schlafen bis errechnet Zeit if ($nlRow->mails_per_minute != 'unlimited') { $sleep = $start + 60 / $mailsPerMinute * $count - microtime(true); if ($sleep > 0) { usleep($sleep * 1000000); } if ($this->_getParam('debug')) { echo "sleeping {$sleep}s\n"; } } $nlStatus = Kwf_Model_Abstract::getInstance('Kwc_Newsletter_Model')->fetchColumnByPrimaryId('status', $nlRow->id); if ($nlStatus != 'sending') { if ($this->_getParam('debug')) { echo "break sending because newsletter status changed to '{$nlStatus}'\n"; } break; } Kwf_Benchmark::enable(); Kwf_Benchmark::reset(); Kwf_Benchmark::checkpoint('start'); $userStart = microtime(true); // Zeile aus queue holen, falls nichts gefunden, Newsletter fertig $row = $nlRow->getNextQueueRow(getmypid()); Kwf_Benchmark::checkpoint('get next recipient'); if ($row) { $recipient = $row->getRecipient(); if (!$recipient || !$recipient->getMailEmail()) { $countNoUser++; $status = 'usernotfound'; } else { if ($recipient instanceof Kwc_Mail_Recipient_UnsubscribableInterface && $recipient->getMailUnsubscribe()) { $countNoUser++; $status = 'usernotfound'; } else { if ($recipient instanceof Kwf_Model_Row_Abstract && $recipient->hasColumn('activated') && !$recipient->activated) { $countNoUser++; $status = 'usernotfound'; } else { try { $mc = $nlRow->getMailComponent(); $t = microtime(true); $mail = $mc->createMail($recipient); $createTime = microtime(true) - $t; $t = microtime(true); $mail->send(); $sendTime = microtime(true) - $t; Kwf_Benchmark::checkpoint('send mail'); $count++; $status = 'sent'; } catch (Exception $e) { echo 'Exception in Sending Newsletter with id ' . $nlRow->id . ' with recipient ' . $recipient->getMailEmail(); echo $e->__toString(); $countErrors++; $status = 'failed'; } $nlRow->getModel()->getTable()->update(array('count_sent' => new Zend_Db_Expr('count_sent + 1'), 'last_sent_date' => date('Y-m-d H:i:s')), 'id = ' . $nlRow->id); } } } $queueLogModel->createRow(array('newsletter_id' => $row->newsletter_id, 'recipient_model' => $row->recipient_model, 'recipient_id' => $row->recipient_id, 'status' => $status, 'send_date' => date('Y-m-d H:i:s')))->save(); $row->delete(); Kwf_Benchmark::checkpoint('update queue'); if ($this->_getParam('verbose')) { if (Kwf_Benchmark::isEnabled() && $this->_getParam('benchmark')) { echo Kwf_Benchmark::getCheckpointOutput(); } echo "[" . getmypid() . "] {$status} in " . round((microtime(true) - $userStart) * 1000) . "ms ("; echo "create " . round($createTime * 1000) . "ms, "; echo "send " . round($sendTime * 1000) . "ms"; echo ") [" . round(memory_get_usage() / (1024 * 1024)) . "MB] [" . round($count / (microtime(true) - $start), 1) . " mails/s]\n"; } if ($status == 'failed' && $this->_getParam('debug')) { echo "stopping because sending failed in debug mode\n"; break; } if (memory_get_usage() > 100 * 1024 * 1024) { if ($this->_getParam('debug')) { echo "stopping because of >100MB memory usage\n"; } break; } } } while ($row); $stop = microtime(true); // Log schreiben $logModel = $nlRow->getModel()->getDependentModel('Log'); $row = $logModel->createRow(array('newsletter_id' => $nlRow->id, 'start' => date('Y-m-d H:i:s', floor($start)), 'stop' => date('Y-m-d H:i:s', floor($stop)), 'count' => $count, 'countErrors' => $countErrors)); $row->save(); // Debugmeldungen if ($this->_getParam('debug')) { $average = round($count / ($stop - $start) * 60); $info = $nlRow->getInfo(); echo "\n"; echo "{$count} Newsletters sent ({$average}/minute), {$countErrors} errors, {$countNoUser} user not found.\n"; echo $info['text'] . "\n"; } Kwf_Events_ModelObserver::getInstance()->enable(); }
protected function _callObserver($fn) { Kwf_Events_ModelObserver::getInstance()->add($fn, $this); }
public function jsonPasteAction() { $session = new Kwf_Session_Namespace('PagesController:copy'); $id = $session->id; if (!$id || !Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, array('ignoreVisible' => true))) { throw new Kwf_Exception_Client(trlKwf('Clipboard is empty')); } $source = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, array('ignoreVisible' => true)); $target = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($this->_getParam('id'), array('ignoreVisible' => true)); $user = Zend_Registry::get('userModel')->getAuthedUser(); $acl = Kwf_Registry::get('acl')->getComponentAcl(); if (!$acl->isAllowed($user, $source) || !$acl->isAllowed($user, $target)) { throw new Kwf_Exception_AccessDenied(); } $progressBar = new Zend_ProgressBar(new Kwf_Util_ProgressBar_Adapter_Cache($this->_getParam('progressNum')), 0, Kwf_Util_Component::getDuplicateProgressSteps($source)); Kwf_Util_MemoryLimit::set(256); Kwf_Events_ModelObserver::getInstance()->disable(); //This would be slow as hell. But luckily we can be sure that for the new (duplicated) components there will be no view cache to clear. $newPage = Kwf_Util_Component::duplicate($source, $target, $progressBar); Kwf_Util_Component::afterDuplicate($source, $newPage); Kwf_Events_ModelObserver::getInstance()->enable(); $progressBar->finish(); $s = new Kwf_Model_Select(); $s->whereEquals('parent_id', $newPage->row->parent_id); $s->order('pos', 'DESC'); $s->limit(1); $lastRow = $newPage->generator->getModel()->getRow($s); $row = $newPage->generator->getModel()->getRow($newPage->row->id); $row->pos = $lastRow ? $lastRow->pos + 1 : 1; $row->visible = false; $row->save(); }
public function changeWebCodeLanguageAction() { Kwf_Events_ModelObserver::getInstance()->disable(); $target = $this->_getParam('target'); if (!$target) { throw new Kwf_Exception_Client("target parameter required"); } $source = Kwf_Config::getValue('webCodeLanguage'); $c = file_get_contents('config.ini'); $c = str_replace("webCodeLanguage = " . $source . "\n", "webCodeLanguage = {$target}\n", $c); file_put_contents('config.ini', $c); $texts = array('trl' => array(), 'trlc' => array(), 'trlp' => array(), 'trlcp' => array()); foreach (Kwf_Model_Abstract::getInstance('Kwf_Trl_Model_Web')->getRows() as $row) { $type = 'trl'; if ($row->context) { $type .= 'c'; } if ($row->{$source . '_plural'}) { $type .= 'p'; } if (!$row->{$target}) { continue; } if (substr(trim($row->{$target}), 0, 1) == '?') { continue; } $texts[$type][] = array('source' => $row->{$source}, 'source_plural' => $row->{$source . '_plural'}, 'target' => $row->{$target}, 'target_plural' => $row->{$target . '_plural'}, 'context' => $row->context); } $iterator = new RecursiveDirectoryIterator('.'); foreach (new RecursiveIteratorIterator($iterator) as $file) { if ($file->isDir()) { continue; } if (strpos($file->getPathname(), ".svn")) { continue; } if (strpos($file->getPathname(), ".git")) { continue; } if (stripos($file->getPathname(), KWF_PATH) !== false) { continue; } if (stripos($file->getPathname(), '/cache/') !== false) { continue; } $extension = end(explode('.', $file->getFileName())); if ($extension != 'php' && $extension != 'js' && $extension != 'tpl') { continue; } $file = $file->getPathname(); echo $file; $c = file_get_contents($file); $changedC = $c; foreach ($texts as $type => $t) { foreach ($t as $text) { if ($type == 'trl') { $changedC = preg_replace('#(trl(Static)?\\((\'|"))' . preg_quote($text['source']) . '(\\3)#', '\\1' . $text['target'] . '\\4', $changedC); } else { if ($type == 'trlc') { $changedC = preg_replace('#(trlc(Static)?\\((\'|")' . preg_quote($text['context']) . '\\3,\\s*(\'|"))' . preg_quote($text['source']) . '(\\4)#', '\\1' . $text['target'] . '\\5', $changedC); } } } } if ($changedC != $c) { echo " [changed]"; file_put_contents($file, $changedC); } echo "\n"; } exit; }
private static function _getAllListeners() { Kwf_Events_ModelObserver::getInstance()->disable(); $models = array(); $subscribers = array(); foreach (Kwc_Abstract::getComponentClasses() as $componentClass) { $subscribers = array_merge($subscribers, self::_getSubscribersFromComponent($componentClass)); } if (Kwf_Component_Data_Root::getComponentClass()) { $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_ViewCache'); $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_UrlCache'); $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_ProcessInputCache'); $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_PagesMeta'); } foreach (Kwf_Model_Abstract::findAllInstances() as $m) { $subscribers = array_merge($subscribers, self::_getSubscribersFromModel($m)); } foreach (Kwf_Config::getValueArray('eventSubscribers') as $subscriber) { if ($subscriber) { $subscriber = Kwf_Events_Subscriber::getInstance($subscriber); $subscribers[] = $subscriber; } } $ret = array(); self::_addListenersFromSubscribers($ret, $subscribers); Kwf_Events_ModelObserver::getInstance()->enable(); return $ret; }
/** * @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; }
public function jsonSaveAction() { $postData = $this->getRequest()->getParams(); if (!isset($postData['componentId'])) { throw new Kwf_Exception_Client('component not found'); } $component = Kwf_Component_Data_Root::getInstance()->getComponentById((string) $postData['componentId'], array('ignoreVisible' => true)); if (!$component) { throw new Kwf_Exception_Client('component not found'); } $component = $component->getComponent(); $postData['doNotRelocate'] = true; $component->preProcessInput($postData); $component->processInput($postData); $errors = $component->getErrors(); $this->view->errorPlaceholder = $component->getPlaceholder('error'); $this->view->errorFields = array(); $this->view->errorMessages = array(); foreach ($errors as $error) { if (isset($error['message'])) { $error['messages'] = array($error['message']); } $msgs = array(); foreach ($error['messages'] as $msg) { $msgs[] = htmlspecialchars($msg); } if (isset($error['field'])) { //if message is associated with a specific field show it there $this->view->errorFields[$error['field']->getFieldName()] = implode('<br />', $msgs); } else { //else just above the form $this->view->errorMessages = array_merge($this->view->errorMessages, $msgs); } } $this->view->successContent = null; if (!$this->view->errorMessages && !$this->view->errorFields) { $success = $component->getData()->getComponent()->getSuccessComponent(); if ($success instanceof Kwf_Component_Data) { if ($success->isPage) { $this->view->successUrl = $success->url; } else { $process = $success->getRecursiveChildComponents(array('page' => false, 'flags' => array('processInput' => true))); if (Kwf_Component_Abstract::getFlag($success->componentClass, 'processInput')) { $process[] = $success; } $postData = array(); //empty because there can't be anything as we didn't display the success yet foreach ($process as $i) { if (method_exists($i->getComponent(), 'preProcessInput')) { $i->getComponent()->preProcessInput($postData); } } foreach ($process as $i) { if (method_exists($i->getComponent(), 'processInput')) { $i->getComponent()->processInput($postData); } } if (class_exists('Kwf_Events_ModelObserver', false)) { //Nur wenn klasse jemals geladen wurde kann auch was zu processen drin sein Kwf_Events_ModelObserver::getInstance()->process(false); } $renderer = new Kwf_Component_Renderer(); $this->view->successContent = $renderer->renderComponent($success); } } else { if (is_string($success)) { $this->view->successUrl = $success; } } } $this->view->errorFields = (object) $this->view->errorFields; }
private static function _getAllListeners() { Kwf_Events_ModelObserver::getInstance()->disable(); $models = array(); $subscribers = array(); $hasFulltext = false; foreach (Kwc_Abstract::getComponentClasses() as $componentClass) { $subscribers = array_merge($subscribers, self::_getSubscribersFromComponent($componentClass)); if (Kwc_Abstract::getFlag($componentClass, 'usesFulltext')) { $hasFulltext = true; } } if (Kwf_Component_Data_Root::getComponentClass()) { $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_ViewCache'); $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_UrlCache'); $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_ProcessInputCache'); $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_RequestHttpsCache'); } if ($hasFulltext) { $subscribers[] = Kwf_Events_Subscriber::getInstance('Kwf_Component_Events_Fulltext'); } foreach (Kwf_Model_Abstract::findAllInstances() as $m) { $subscribers = array_merge($subscribers, self::_getSubscribersFromModel($m)); } $ret = array(); self::_addListenersFromSubscribers($ret, $subscribers); Kwf_Events_ModelObserver::getInstance()->enable(); return $ret; }
public function testDuplicate() { $source = $this->_root->getComponentById('1'); $target = $this->_root->getComponentById('4'); $this->assertEquals(0, count($target->getChildPages())); Kwf_Events_ModelObserver::getInstance()->disable(); //PagesController also does that (for performance reasons) Kwf_Util_Component::duplicate($source, $target); Kwf_Events_ModelObserver::getInstance()->enable(); $this->assertEquals(1, count($target->getChildPages())); $this->assertEquals(1, count($target->getChildPage()->getChildPages())); }
public function postDispatch() { Kwf_Events_ModelObserver::getInstance()->process(); Kwf_Component_Cache::getInstance()->writeBuffer(); }
public function import($format, $data, $options = array()) { if ($format == self::FORMAT_ARRAY) { if (isset($options['replace']) && $options['replace'] && !isset($this->_uniqueColumns)) { throw new Kwf_Exception('You must set uniqueColumns for this model if you use replace'); } $ids = array(); Kwf_Events_ModelObserver::getInstance()->disable(); foreach ($data as $k => $v) { if (is_array($ids) && isset($v[$this->getPrimaryKey()])) { $ids[] = $v[$this->getPrimaryKey()]; } else { //if we don't know all imported ids, pass null $ids = null; } if (isset($options['replace']) && $options['replace']) { $s = $this->select(); foreach ($this->_uniqueColumns as $c) { if (is_null($v[$c])) { $s->whereNull($c); } else { $s->whereEquals($c, $v[$c]); } } $row = $this->getRow($s); if (!$row) { $row = $this->createRow(); } } else { $row = $this->createRow(); } foreach ($v as $k => $i) { $row->{$k} = $i; } $row->save(); } Kwf_Events_ModelObserver::getInstance()->enable(); $this->_updateModelObserver($options, $ids); $this->_afterImport($format, $data, $options); } else { throw new Kwf_Exception_NotYetImplemented(); } }
public function indexAction() { Kwf_Util_MemoryLimit::set(512); Kwf_Events_ModelObserver::getInstance()->disable(); //try to update old-style db config if (file_exists('config.db.ini')) { $db = file_get_contents('config.db.ini'); if (file_exists('config.local.ini')) { $c = file_get_contents('config.local.ini'); } else { $c = "[production]\n"; } $c .= "\n"; $db = str_replace("[database]\n", '', $db); foreach (explode("\n", trim($db)) as $line) { if (trim($line)) { $c .= "database." . $line . "\n"; } } file_put_contents('config.local.ini', $c); unlink('config.db.ini'); } if ($this->_getParam('rev')) { throw new Kwf_Exception("rev parameter is not supported anymore"); } if ($this->_getParam('class')) { throw new Kwf_Exception("class parameter is not supported anymore"); } $skipClearCache = $this->_getParam('skip-clear-cache'); $doneNames = Kwf_Util_Update_Helper::getExecutedUpdatesNames(); if ($this->_getParam('name')) { $updates = Kwf_Util_Update_Helper::getUpdates(); foreach ($updates as $k => $u) { $n = $u->getUniqueName(); $n = substr($n, strrpos($n, '_') + 1); if ($n != $this->_getParam('name')) { unset($updates[$k]); } } } else { if (!$skipClearCache) { Kwf_Util_ClearCache::getInstance()->clearCache(array('types' => 'all', 'output' => true, 'refresh' => false)); } echo "Looking for update-scripts..."; $updates = Kwf_Util_Update_Helper::getUpdates(); foreach ($updates as $k => $u) { if (in_array($u->getUniqueName(), $doneNames) || $u->getLegacyName() && in_array($u->getLegacyName(), $doneNames)) { unset($updates[$k]); } } echo " found " . count($updates) . "\n\n"; } if (!$this->_getParam('debug')) { Kwf_Util_Maintenance::writeMaintenanceBootstrap(); } $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); $runner = new Kwf_Util_Update_Runner($updates); $progress = new Zend_ProgressBar($c, 0, $runner->getProgressSteps()); $runner->setProgressBar($progress); $runner->setVerbose(true); $runner->setEnableDebug($this->_getParam('debug')); $runner->setSkipClearCache($skipClearCache); if (!$runner->checkUpdatesSettings()) { echo "\ncheckSettings failed, update stopped\n"; } else { $executedUpdates = $runner->executeUpdates(); echo "\n[32mupdate finished[0m\n"; $doneNames = array_unique(array_merge($doneNames, $executedUpdates)); $runner->writeExecutedUpdates($doneNames); } if (!$this->_getParam('debug')) { Kwf_Util_Maintenance::restoreMaintenanceBootstrap(); } $errors = $runner->getErrors(); if ($errors) { echo "\n\n" . str_repeat('=', 16) . "\n"; echo count($errors) . " update script(s) failed:\n"; foreach ($errors as $error) { echo $error['name'] . ": \n"; echo $error['message'] . "\n\n"; } exit(1); } else { echo "\n" . count($updates) . " update script(s) successfully executed.\n"; exit(0); } }
/** * @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; }