Esempio n. 1
0
 public function preDispatch()
 {
     if ($this->_getParam('applicationAssetsVersion') && $this->getHelper('ViewRenderer')->isJson()) {
         if (Kwf_Assets_Dispatcher::getInstance()->getAssetsVersion() != $this->_getParam('applicationAssetsVersion')) {
             $this->_forward('json-wrong-version', 'error', 'kwf_controller_action_error');
             return;
         }
     }
     $this->_validateSessionToken();
     $t = microtime(true);
     $allowed = $this->_isAllowedResource();
     if ($allowed) {
         $allowed = $this->_isAllowed($this->_getAuthData());
     }
     if (!$allowed) {
         $params = array('role' => $this->_getUserRole());
         if ($this->getHelper('ViewRenderer')->isJson()) {
             $this->_forward('json-login', 'login', 'kwf_controller_action_user', $params);
         } else {
             $params = array('location' => $this->getRequest()->getBaseUrl() . '/' . ltrim($this->getRequest()->getPathInfo(), '/'));
             $this->_forward('index', 'login', 'kwf_controller_action_user', $params);
         }
     }
     Kwf_Benchmark::subCheckpoint('check acl', microtime(true) - $t);
 }
Esempio n. 2
0
 public function getChildData($parentData, $select = array())
 {
     Kwf_Benchmark::count('GenStatic::getChildData');
     if (is_array($select)) {
         $select = new Kwf_Component_Select($select);
     }
     $pData = $parentData;
     $ret = array();
     if ($p = $select->getPart(Kwf_Component_Select::WHERE_ID)) {
         if (!$this->_idMatches($p)) {
             return $ret;
         }
     }
     if (!$parentData) {
         if ($p = $select->getPart(Kwf_Component_Select::WHERE_CHILD_OF)) {
             throw new Kwf_Exception("this must not happen");
             $p = $p->getPageOrRoot();
             $parentData = $p->getRecursiveChildComponents(array('componentClass' => $this->_class));
         } else {
             $parentSelect = new Kwf_Component_Select();
             $parentSelect->copyParts(array(Kwf_Component_Select::WHERE_SUBROOT, Kwf_Component_Select::IGNORE_VISIBLE, Kwf_Component_Select::WHERE_CHILD_OF), $select);
             $parentData = Kwf_Component_Data_Root::getInstance()->getComponentsBySameClass($this->_class, $parentSelect);
         }
     }
     $parentDatas = is_array($parentData) ? $parentData : array($parentData);
     foreach ($this->_fetchKeys($pData, $select) as $key) {
         foreach ($parentDatas as $parentData) {
             $data = $this->_createData($parentData, $key, $select);
             if ($data) {
                 $ret[] = $data;
             }
         }
     }
     return $ret;
 }
 protected function __construct($class, $settings)
 {
     //self::$objectsCount++;
     $this->_class = $class;
     $this->_settings = $settings;
     $this->_init();
     Kwf_Benchmark::count('generators');
 }
 public function indexAction()
 {
     Kwf_Benchmark::enable();
     Kwf_Benchmark::reset();
     self::setup();
     self::$proxyModel->countRows();
     echo (int) Kwf_Benchmark::getCounterValue('mirror sync');
     exit;
 }
Esempio n. 5
0
 public function queryStart($queryText, $queryType = null)
 {
     if (!$this->_enabled) {
         return null;
     }
     $this->_count++;
     Kwf_Benchmark::countLog('dbqueries');
     return null;
 }
Esempio n. 6
0
 public function __call($name, $arguments)
 {
     $b = Kwf_Benchmark::start('soapCall', $name);
     $ret = parent::__call($name, $arguments);
     if ($b) {
         $b->stop();
     }
     return $ret;
 }
 public function indexAction()
 {
     Zend_Registry::set('db', false);
     Kwf_Test_SeparateDb::setDbFromCookie();
     // setzt es nur wenn es das cookie wirklich gibt
     //FnF models setzen damit tests nicht in echte tabellen schreiben
     Kwf_Component_Cache::setInstance(Kwf_Component_Cache::CACHE_BACKEND_FNF);
     Kwf_Component_Cache_Memory::setInstance(new Kwf_Component_Cache_MemoryBlackHole());
     /*
     if (class_exists('APCIterator')) {
         $prefix = Kwf_Cache::getUniquePrefix();
         apc_delete_file(new APCIterator('user', '#^'.$prefix.'#'));
     } else {
         apc_clear_cache('user');
     }
     */
     Kwf_Component_Data_Root::setComponentClass($this->_getParam('root'));
     Zend_Registry::set('testRootComponentClass', $this->_getParam('root'));
     $root = Kwf_Component_Data_Root::getInstance();
     $root->setFilename('kwf/kwctest/' . $this->_getParam('root'));
     $url = $this->_getParam('url');
     $urlParts = explode('/', $url);
     if (is_array($urlParts) && $urlParts[0] == 'media') {
         if (sizeof($urlParts) != 7) {
             throw new Kwf_Exception_NotFound();
         }
         $class = $urlParts[1];
         $id = $urlParts[2];
         $type = $urlParts[3];
         $checksum = $urlParts[4];
         // time() wäre der 5er, wird aber nur wegen browsercache benötigt
         $filename = $urlParts[6];
         if ($checksum != Kwf_Media::getChecksum($class, $id, $type, $filename)) {
             throw new Kwf_Exception_AccessDenied('Access to file not allowed.');
         }
         Kwf_Media_Output::output(Kwf_Media::getOutput($class, $id, $type));
     }
     if ($url == 'kwf/util/kwc/render') {
         if (isset($_REQUEST['url'])) {
             $_REQUEST['url'] = str_replace('/' . $root->filename, '', $_REQUEST['url']);
         }
         Kwf_Util_Component::dispatchRender();
     }
     $domain = 'http://' . Zend_Registry::get('config')->server->domain;
     $data = $root->getPageByUrl($domain . Kwf_Setup::getBaseUrl() . '/' . $url, null);
     if (!$data) {
         throw new Kwf_Exception_NotFound();
     }
     $root->setCurrentPage($data);
     $contentSender = Kwc_Abstract::getSetting($data->componentClass, 'contentSender');
     $contentSender = new $contentSender($data);
     $contentSender->sendContent(true);
     Kwf_Benchmark::shutDown();
     Kwf_Benchmark::output();
     exit;
 }
Esempio n. 8
0
 public function renderMaster($component)
 {
     static $benchmarkEnabled;
     if (!isset($benchmarkEnabled)) {
         $benchmarkEnabled = Kwf_Benchmark::isEnabled();
     }
     $content = false;
     if ($this->_enableCache) {
         $content = Kwf_Component_Cache::getInstance()->load($component->componentId, $this->_getRendererName(), 'fullPage');
         $this->_minLifetime = null;
     }
     Kwf_Benchmark::checkpoint('load fullPage cache');
     $statType = null;
     if (!$content) {
         if ($benchmarkEnabled) {
             $startTime = microtime(true);
         }
         if (!$this->_enableCache || ($content = Kwf_Component_Cache::getInstance()->load($component, $this->_getRendererName(), 'page')) === null) {
             $masterHelper = new Kwf_Component_View_Helper_Master();
             $masterHelper->setRenderer($this);
             $content = $masterHelper->master($component);
             if ($this->_enableCache) {
                 Kwf_Component_Cache::getInstance()->save($component, $content, $this->_getRendererName(), 'page', '', '', null);
                 $statType = 'miss';
             } else {
                 $statType = 'noviewcache';
             }
         } else {
             $statType = 'hit';
         }
         if ($statType) {
             Kwf_Benchmark::count("rendered {$statType}", $component->componentId . ': page');
         }
         Kwf_Benchmark::countLog('render-' . $statType);
         if ($benchmarkEnabled) {
             Kwf_Benchmark::subCheckpoint($component->componentId . ' page', microtime(true) - $startTime);
         }
         Kwf_Benchmark::checkpoint('render page');
         $pass1Cacheable = true;
         $content = $this->_renderPass1($content, $pass1Cacheable);
         Kwf_Benchmark::checkpoint('render pass 1');
         if ($this->_enableCache && $pass1Cacheable) {
             Kwf_Component_Cache::getInstance()->save($component, $content, $this->_getRendererName(), 'fullPage', '', '', $this->_minLifetime);
         }
         Kwf_Benchmark::count("rendered miss", $component->componentId . ': fullPage');
         Kwf_Benchmark::countLog('fullpage-miss');
     } else {
         Kwf_Benchmark::count("rendered hit", $component->componentId . ': fullPage');
         Kwf_Benchmark::countLog('fullpage-hit');
     }
     $content = $this->_renderPass2($content);
     Kwf_Benchmark::checkpoint('render pass 2');
     Kwf_Component_Cache::getInstance()->writeBuffer();
     return $content;
 }
Esempio n. 9
0
 public static function ensureHttp()
 {
     if (php_sapi_name() != 'cli') {
         if (isset($_SERVER['HTTPS']) && $_SERVER['REQUEST_METHOD'] != 'POST' && !Kwf_Session::sessionExists()) {
             $redirect = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
             header('Location: ' . $redirect, true, 302);
             Kwf_Benchmark::shutDown();
             exit;
         }
     }
 }
Esempio n. 10
0
 public function testRequests()
 {
     Kwf_Benchmark::enable();
     Kwf_Benchmark::reset();
     $this->_proxyModel->getRows();
     $this->assertEquals(1, Kwf_Benchmark::getCounterValue('mirror sync'));
     $this->_proxyModel->getRow(3);
     $this->assertEquals(1, Kwf_Benchmark::getCounterValue('mirror sync'));
     $this->_proxyModel->getIds();
     $this->assertEquals(1, Kwf_Benchmark::getCounterValue('mirror sync'));
     $this->_proxyModel->countRows();
     $this->assertEquals(1, Kwf_Benchmark::getCounterValue('mirror sync'));
     Kwf_Benchmark::disable();
 }
Esempio n. 11
0
 public function testProcessInputPerformance()
 {
     Kwf_Benchmark::enable();
     Kwf_Benchmark::reset();
     $p = $this->_root->getChildComponent('_table1');
     $process = $p->getRecursiveChildComponents(array('page' => false, 'flags' => array('processInput' => true)));
     $process = array_values($process);
     $this->assertEquals(1, count($process));
     $this->assertEquals('root_table1-1-1', $process[0]->componentId);
     //Kwf_Benchmark::output();
     //root gibts schon
     //root_table, root_table-1, root_table-1-1
     $this->assertEquals(3, Kwf_Benchmark::getCounterValue('componentDatas'));
     Kwf_Benchmark::disable();
 }
Esempio n. 12
0
 public function preDispatch()
 {
     $t = microtime(true);
     if (!isset($this->_form)) {
         if (isset($this->_formName)) {
             $this->_form = new $this->_formName(null, $this->_getParam('class'));
         } else {
             $this->_form = Kwc_Abstract_Form::createComponentForm($this->_getParam('class'), 'component');
         }
     }
     Kwf_Benchmark::subCheckpoint('create component form', microtime(true) - $t);
     $this->_form->setBodyStyle('padding: 10px');
     $this->_form->setId($this->_getParam('componentId'));
     parent::preDispatch();
 }
Esempio n. 13
0
 public static function registerAutoload()
 {
     if (!class_exists('Kwf_Benchmark', false)) {
         require KWF_PATH . '/Kwf/Benchmark.php';
     }
     if (Kwf_Benchmark::isEnabled()) {
         $class = 'Kwf_Loader_Benchmark';
         if (!class_exists($class, false)) {
             require KWF_PATH . '/Kwf/Loader/Benchmark.php';
         }
     } else {
         //für performance
         $class = 'Kwf_Loader';
     }
     spl_autoload_register(array($class, 'loadClass'));
 }
 public function testNoSyncWhenOnlySavedToSibling()
 {
     sleep(2);
     Kwf_Benchmark::enable();
     Kwf_Benchmark::reset();
     $mirror = new Kwf_Model_MirrorCache_MirrorCacheModel();
     $r = $mirror->getRow(1);
     $r->siblingcol = 'sib val 1';
     $r->save();
     $r = $mirror->getRow(1);
     $r->firstname = 'Herbert';
     $r->save();
     $this->assertEquals(1, Kwf_Benchmark::getCounterValue('mirror sync'));
     Kwf_Benchmark::reset();
     Kwf_Benchmark::disable();
     $this->assertEquals('sib val 1', $mirror->getRow(1)->siblingcol);
 }
Esempio n. 15
0
 public function getChildData($parentData, $select = array())
 {
     Kwf_Benchmark::count('GenTable::getChildData');
     if (is_array($select)) {
         $select = new Kwf_Component_Select($select);
     }
     $ret = array();
     if (!$parentData && ($p = $select->getPart(Kwf_Component_Select::WHERE_CHILD_OF)) && !$this->_getUseComponentId()) {
         $parentDatas = $p->getRecursiveChildComponents(array('componentClass' => $this->_class));
     } else {
         $parentDatas = array($parentData);
     }
     foreach ($parentDatas as $parentData) {
         $s = $this->_formatSelect($parentData, clone $select);
         $rows = array();
         if ($s) {
             $rows = $this->_fetchRows($parentData, $s);
         }
         foreach ($rows as $row) {
             $currentPd = $parentData;
             if (!$currentPd) {
                 $currentPd = $this->_getParentDataByRow($row, $s);
             }
             if (!is_array($currentPd)) {
                 if ($currentPd) {
                     $currentPds = array($currentPd);
                 } else {
                     $currentPds = array();
                 }
             } else {
                 $currentPds = $currentPd;
             }
             foreach ($currentPds as $currentPd) {
                 if (!$currentPd) {
                     throw new Kwf_Exception("No parentData returned in '" . get_class($this) . "'");
                 }
                 $data = $this->_createData($currentPd, $row, $s);
                 if ($data) {
                     $ret[] = $data;
                 }
             }
         }
     }
     return $ret;
 }
Esempio n. 16
0
 public function __call($method, $args)
 {
     $log = date('Y-m-d H:i:s') . " (start) {$this->_serverUrl} {$method} " . Kwf_Setup::getRequestPath() . "\n";
     file_put_contents('log/srpc-call', $log, FILE_APPEND);
     $start = microtime(true);
     $b = Kwf_Benchmark::start('srpc call', $this->_serverUrl . ' ' . $method);
     $params = array('method' => $method, 'arguments' => array(), 'extraParams' => array());
     if (is_array($args) && count($args)) {
         $params['arguments'] = $args;
     }
     if ($this->_extraParams) {
         $params['extraParams'] = $this->_extraParams;
     }
     $params['arguments'] = serialize($params['arguments']);
     $params['extraParams'] = serialize($params['extraParams']);
     if (strpos($params['arguments'], 'Kwf_') !== false || strpos($params['extraParams'], 'Kwf_') !== false) {
         $ex = new Kwf_Exception("a class name with 'Kwf_' must not be sent through srpc client");
         $ex->logOrThrow();
     }
     $response = $this->_performRequest($params);
     $log = date('Y-m-d H:i:s') . ' ' . round(microtime(true) - $start, 2) . "s {$this->_serverUrl} {$method} " . Kwf_Setup::getRequestPath() . "\n";
     file_put_contents('log/srpc-call', $log, FILE_APPEND);
     if ($b) {
         $b->stop();
     }
     try {
         $result = unserialize($response);
     } catch (Exception $e) {
         throw new Kwf_Exception('Srpc Server Response is not serialized: ' . $response);
     }
     if ($result === false) {
         throw new Kwf_Exception('Srpc Server Response is not serialized: ' . $response);
     }
     // result könnte eine Exception sein, wenn ja wird sie weitergeschmissen
     if ($result instanceof Kwf_Exception_Serializable) {
         throw $result->getException();
     } else {
         if ($result instanceof Exception) {
             throw $result;
         }
     }
     return $result;
 }
 public function getChildData($parentData, $select = array())
 {
     if (is_array($select)) {
         $select = new Kwf_Component_Select($select);
     }
     if (!is_instance_of($this->_class, 'Kwc_Root_Component') && $select->hasPart(Kwf_Component_Select::WHERE_SUBROOT)) {
         //abkürzung wenn mehrere domains mit unterschiedlichen component-Klassen
         //im prinzip gleicher code wie in _GetParentDataByRow wenn return null gemacht wird, aber das hier wird früher gemacht
         $subroot = $select->getPart(Kwf_Component_Select::WHERE_SUBROOT);
         $component = $subroot[0];
         while (!Kwc_Abstract::getFlag($component->componentClass, 'subroot')) {
             $component = $component->parent;
         }
         if ($component->componentClass != $this->getClass()) {
             Kwf_Benchmark::count('GenTable::getChildData skipped');
             return array();
         }
     }
     return parent::getChildData($parentData, $select);
 }
Esempio n. 18
0
 public function testCached()
 {
     Kwf_Benchmark::enable();
     Kwf_Benchmark::reset();
     $d = Kwf_Registry::get('testDomain');
     $c = $this->_root->getPageByUrl("http://{$d}/foo", null);
     //uncached
     $this->assertEquals('1', $c->componentId);
     $this->assertEquals(1, Kwf_Benchmark::getCounterValue('componentDatas'));
     $this->assertEquals(0, (int) Kwf_Benchmark::getCounterValue('unserialized componentDatas'));
     Kwf_Component_Data_Root::reset();
     Kwf_Component_Data_Root::setComponentClass('Kwf_Component_Cache_UrlClearCache_Root');
     $this->_root = Kwf_Component_Data_Root::getInstance();
     Kwf_Benchmark::reset();
     $c = $this->_root->getPageByUrl("http://{$d}/foo", null);
     //cached
     $this->assertEquals('1', $c->componentId);
     $this->assertEquals(0, (int) Kwf_Benchmark::getCounterValue('componentDatas'));
     $this->assertEquals(1, Kwf_Benchmark::getCounterValue('unserialized componentDatas'));
 }
 public function indexAction()
 {
     $id = $this->_getParam('id');
     if (!$id) {
         throw new Kwf_ClientException("Missing Parameter: id");
     }
     $c = Kwf_Component_Data_Root::getInstance()->getComponentById($id, array('ignoreVisible' => true));
     if (!$c) {
         $c = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, array('ignoreVisible' => true));
     }
     if (!$c) {
         throw new Kwf_ClientException("Component with id '{$id}' not found");
     }
     $process = $c->getRecursiveChildComponents(array('page' => false, 'flags' => array('processInput' => true)));
     if (Kwf_Component_Abstract::getFlag($c->componentClass, 'processInput')) {
         $process[] = $c;
     }
     $postData = array();
     foreach ($process as $i) {
         Kwf_Benchmark::count('processInput', $i->componentId);
         if (method_exists($i->getComponent(), 'preProcessInput')) {
             $i->getComponent()->preProcessInput($postData);
         }
     }
     foreach ($process as $i) {
         if (method_exists($i->getComponent(), 'processInput')) {
             $i->getComponent()->processInput($postData);
         }
     }
     /*
     //deaktivert: funktioniert nicht
     $c->getComponent()->sendContent('views/component-master.tpl', true);
     */
     //zwischenlösung:
     //(unschön: keine assets, kein html-header usw)
     echo $c->render();
     Kwf_Benchmark::output();
     exit;
 }
 public function testSyncWithCli()
 {
     Kwf_Benchmark::enable();
     Kwf_Benchmark::reset();
     Kwf_Model_MirrorCache_TestController::setup();
     Kwf_Model_MirrorCache_TestController::$proxyModel->synchronize(Kwf_Model_MirrorCache::SYNC_ONCE);
     $this->assertEquals(1, (int) Kwf_Benchmark::getCounterValue('mirror sync'));
     $url = 'http://' . Kwf_Registry::get('testDomain') . '/kwf/test/kwf_model_mirror-cache_test';
     $this->assertEquals(0, file_get_contents($url));
     sleep(6);
     //sync delay ist 5 sec
     $this->assertEquals(1, file_get_contents($url));
     $this->assertEquals(0, file_get_contents($url));
     Kwf_Benchmark::reset();
     Kwf_Model_MirrorCache_TestController::$proxyModel->countRows();
     $this->assertEquals(0, (int) Kwf_Benchmark::getCounterValue('mirror sync'));
     sleep(6);
     //sync delay ist 5 sec
     Kwf_Benchmark::reset();
     Kwf_Model_MirrorCache_TestController::$proxyModel->synchronize(Kwf_Model_MirrorCache::SYNC_ALWAYS);
     $this->assertEquals(1, (int) Kwf_Benchmark::getCounterValue('mirror sync'));
     $this->assertEquals(0, file_get_contents($url));
 }
Esempio n. 21
0
 public function queryStart($queryText, $queryType = null)
 {
     if (!$this->_enabled) {
         return null;
     }
     Kwf_Benchmark::countLog('dbqueries');
     // make sure we have a query type
     if (null === $queryType) {
         switch (strtolower(substr($queryText, 0, 6))) {
             case 'insert':
                 $queryType = self::INSERT;
                 break;
             case 'update':
                 $queryType = self::UPDATE;
                 break;
             case 'delete':
                 $queryType = self::DELETE;
                 break;
             case 'select':
                 $queryType = self::SELECT;
                 break;
             default:
                 $queryType = self::QUERY;
                 break;
         }
     }
     $this->_lastQuery = new Zend_Db_Profiler_Query($queryText, $queryType);
     $this->_count++;
     self::$_staticCount++;
     if ($this->_logger) {
         $this->_logger->info($this->_count . ' ----------------------');
         $this->_logger->debug($queryText);
         //$this->_logger->debug(btString());
     }
     return $this->_count;
 }
Esempio n. 22
0
 public function getDb($db = 'web')
 {
     if (!isset($this->_db[$db])) {
         $dbConfig = $this->getDbConfig($db);
         $this->_db[$db] = Zend_Db::factory('PDO_MYSQL', $dbConfig);
         $this->_db[$db]->query('SET names UTF8');
         $this->_db[$db]->query('SET SESSION sql_mode=\'\'');
         if (Kwf_Config::getValue('debug.disableMysqlQueryCache')) {
             $this->_db[$db]->query('SET SESSION query_cache_type=0');
         }
         /**
          * lc_time_names wird hier nicht gesetzt weil man für trlKwf
          * momentan das userModel benötigt und das gibts ohne DB
          * Verbindung nicht -> Endlosschleifen gefahr.
          * lc_time_names wurde früher vermutlich im TreeCache noch benötigt
          * (z.B. bei den News Month), aber das macht jetzt das PHP, dehalb
          * ist es nicht mehr nötig dies zu setzen.
          */
         //             $this->_db[$db]->query("SET lc_time_names = '".trlKwf('en_US')."'");
         if (Kwf_Config::getValue('debug.querylog')) {
             $profiler = new Kwf_Db_Profiler(true);
             $this->_db[$db]->setProfiler($profiler);
         } else {
             if (Kwf_Config::getValue('debug.queryTimeout')) {
                 $profiler = new Kwf_Db_Profiler_Timeout(Kwf_Config::getValue('debug.queryTimeout'), true);
                 $this->_db[$db]->setProfiler($profiler);
             } else {
                 if (Kwf_Benchmark::isEnabled() || Kwf_Benchmark::isLogEnabled()) {
                     $profiler = new Kwf_Db_Profiler_Count(true);
                     $this->_db[$db]->setProfiler($profiler);
                 }
             }
         }
     }
     return $this->_db[$db];
 }
 /**
  * cache write - this is called when the script is about to finish, or when session_write_close() is called
  * data are written only when something has changed
  *
  * @param string $sessionId
  * @param string $data
  * @return bool
  */
 public function write($sessionId, $data)
 {
     $t = microtime(true);
     $expiration = $this->_lifeTime + time();
     //we store time of the db record expiration in the Memcache
     if ($this->_initSessionData !== $data) {
         Kwf_Registry::get('db')->query("REPLACE INTO kwf_sessions (sessionId, expiration, data) VALUES(?, ?, ?)", array($sessionId, $expiration, $data));
         $this->_memcacheSet($sessionId, $data);
     }
     Kwf_Benchmark::count('sessionhdl', 'read: ' . (microtime(true) - $t) * 1000 . 'ms');
     return true;
 }
Esempio n. 24
0
 public function getChildData($parentDatas, $select = array())
 {
     Kwf_Benchmark::count('GenChained::getChildData');
     $ret = array();
     if (is_array($select)) {
         $select = new Kwf_Component_Select($select);
     }
     $chainedType = $this->getGeneratorFlag('chainedType');
     $slaveData = $select->getPart(Kwf_Component_Select::WHERE_CHILD_OF);
     while ($slaveData) {
         if (Kwc_Abstract::getFlag($slaveData->componentClass, 'chainedType') == $chainedType) {
             break;
         }
         $slaveData = $slaveData->parent;
     }
     $parentDataSelect = new Kwf_Component_Select();
     $parentDataSelect->copyParts(array('ignoreVisible'), $select);
     $parentDatas = is_array($parentDatas) ? $parentDatas : array($parentDatas);
     foreach ($parentDatas as $parentData) {
         foreach ($this->_getChainedChildComponents($parentData, $select) as $component) {
             $pData = array();
             if (!$parentData) {
                 if (!$slaveData) {
                     $pData = Kwc_Chained_Abstract_Component::getAllChainedByMaster($component->parent, $chainedType, $parentDataSelect);
                 } else {
                     $chainedComponent = Kwc_Chained_Abstract_Component::getChainedByMaster($component->parent, $slaveData, $chainedType, $parentDataSelect);
                     if ($chainedComponent) {
                         $pData = array($chainedComponent);
                     }
                 }
             } else {
                 $pData = array($parentData);
             }
             foreach ($pData as $d) {
                 $data = $this->_createData($d, $component, $select);
                 if ($data) {
                     $ret[] = $data;
                 }
             }
         }
     }
     return $ret;
 }
 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();
 }
Esempio n. 26
0
 private static function _getIndirectChildComponentClasses($class, $select, $cacheId)
 {
     static $ccc = array();
     $currentCacheId = 'iccc-' . md5($class . $cacheId);
     if (isset($ccc[$class . $cacheId])) {
         Kwf_Benchmark::count('iccc cache hit');
         return $ccc[$class . $cacheId];
     }
     $ret = Kwf_Cache_SimpleStatic::fetch($currentCacheId, $success);
     if ($success) {
         $ccc[$class . $cacheId] = $ret;
         Kwf_Benchmark::count('iccc cache semi-hit');
         return $ret;
     }
     Kwf_Benchmark::count('iccc cache miss', $class . ' ' . print_r($select->getParts(), true));
     $childConstraints = array('page' => false);
     $ccc[$class . $cacheId] = array();
     foreach (Kwc_Abstract::getChildComponentClasses($class, $childConstraints) as $childClass) {
         if (Kwc_Abstract::getChildComponentClasses($childClass, $select, $cacheId)) {
             $ccc[$class . $cacheId][] = $childClass;
             continue;
         }
         $classes = Kwc_Abstract::_getIndirectChildComponentClasses($childClass, $select, $cacheId);
         if ($classes) {
             $ccc[$class . $cacheId][] = $childClass;
         }
     }
     $ccc[$class . $cacheId] = array_unique(array_values($ccc[$class . $cacheId]));
     Kwf_Cache_SimpleStatic::add($currentCacheId, $ccc[$class . $cacheId]);
     return $ccc[$class . $cacheId];
 }
Esempio n. 27
0
 public function getChildData($parentData, $select = array())
 {
     Kwf_Benchmark::count('GenStaticSelect::getChildData');
     if (is_array($select)) {
         $select = new Kwf_Component_Select($select);
     }
     if ($select->hasPart(Kwf_Component_Select::WHERE_COMPONENT_CLASSES)) {
         $continue = false;
         foreach ($select->getPart(Kwf_Component_Select::WHERE_COMPONENT_CLASSES) as $componentClass) {
             if (in_array($componentClass, $this->getChildComponentClasses())) {
                 $continue = true;
             }
         }
         if (!$continue) {
             return array();
         }
     }
     if (!$parentData) {
         if (!$select->hasPart(Kwf_Component_Select::WHERE_COMPONENT_CLASSES)) {
             throw new Kwf_Exception_NotYetImplemented();
         }
         $selectClasses = $select->getPart(Kwf_Component_Select::WHERE_COMPONENT_CLASSES);
         $possibleClasses = $this->getChildComponentClasses();
         if (in_array(array_shift($possibleClasses), $selectClasses)) {
             throw new Kwf_Exception("You can't search for component which is first (=default) in StaticSelect");
         }
         $searchFor = array();
         foreach ($selectClasses as $c) {
             $searchFor[] = array_search($c, $possibleClasses);
         }
         $s = new Kwf_Model_Select();
         $s->whereEquals('component', $searchFor);
         $s->where(new Kwf_Model_Select_Expr_Like('component_id', '%-' . $this->getGeneratorKey()));
         $rows = $this->_getModel()->export(Kwf_Model_Abstract::FORMAT_ARRAY, $s, array('columns' => array('component_id')));
         $parentDatas = array();
         foreach ($rows as $row) {
             $id = substr($row['component_id'], 0, -(strlen($this->getGeneratorKey()) + 1));
             $s = new Kwf_Component_Select();
             $s->copyParts(array(Kwf_Component_Select::IGNORE_VISIBLE, Kwf_Component_Select::WHERE_SUBROOT), $select);
             $d = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($id, $s);
             if ($d) {
                 $parentDatas[] = $d;
             }
         }
     } else {
         $parentDatas = array($parentData);
     }
     $ret = array();
     foreach ($parentDatas as $parentData) {
         $data = $this->_createData($parentData, $this->getGeneratorKey(), $select);
         if (!$data) {
             continue;
         }
         if ($select->hasPart('whereId')) {
             if ('-' . $data->id != $select->getPart('whereId')) {
                 continue;
             }
         }
         $ret[] = $data;
     }
     return $ret;
 }
Esempio n. 28
0
 /**
  * Lädt Resourcen die von Komponenten kommen.
  * Muss extra aufgerufen werden wenn diese Resourcen benötigt werden, aus
  * performance gründen
  */
 public function loadKwcResources()
 {
     if (!Kwf_Registry::get('db')) {
         return;
     }
     //if we don't have a db configured yet skip kwc resources. required to be able to build assets without db
     if ($this->_kwcResourcesLoaded) {
         return;
     }
     $this->_kwcResourcesLoaded = true;
     $t = microtime(true);
     $menuConfigs = array();
     foreach (Kwc_Abstract::getComponentClasses() as $c) {
         if (Kwc_Abstract::getFlag($c, 'hasResources')) {
             Kwc_Admin::getInstance($c)->addResources($this);
         }
         if (Kwc_Abstract::hasSetting($c, 'menuConfig') && Kwc_Abstract::getSetting($c, 'menuConfig')) {
             $menuConfigs[] = Kwf_Component_Abstract_MenuConfig_Abstract::getInstance($c);
         }
     }
     usort($menuConfigs, array(get_class($this), '_compareMenuConfig'));
     foreach ($menuConfigs as $cfg) {
         $cfg->addResources($this);
     }
     Kwf_Benchmark::subCheckpoint('kwc resources', microtime(true) - $t);
 }
Esempio n. 29
0
 public static function output($file)
 {
     self::outputWithoutShutdown($file);
     Kwf_Benchmark::shutDown();
     exit;
 }
Esempio n. 30
0
 public function dispatch(Zend_Controller_Request_Abstract $request = null, Zend_Controller_Response_Abstract $response = null)
 {
     if ($request === null) {
         if (PHP_SAPI == 'cli') {
             $request = new Kwf_Controller_Request_Cli();
         } else {
             $request = new Kwf_Controller_Request_Http();
         }
     }
     if ($response === null) {
         $response = new Kwf_Controller_Response_Http();
     }
     try {
         $ret = parent::dispatch($request, $response);
     } catch (Zend_Controller_Router_Exception $e) {
         if ($e->getCode() == 404) {
             //fired by Zend_Controller_Router_Rewrite::route, transform into proper 404
             throw new Kwf_Exception_NotFound();
         } else {
             throw $e;
         }
     }
     Kwf_Benchmark::shutDown();
     return $ret;
 }