/** * Rolls back a transaction. * @throws CException if the transaction or the DB connection is not active. */ public function rollback() { if ($this->_active && $this->_connection->getActive()) { Prado::trace('Rolling back transaction', 'System.Testing.Data.TDbTransaction'); $this->_connection->getPdoInstance()->rollBack(); $this->_active = false; } else { throw new TDbException('dbtransaction_transaction_inactive'); } }
/** * Loads the template from the specified file. * @return ITemplate template parsed from the specified file, null if the file doesn't exist. */ public function getTemplateByFileName($fileName) { if (($fileName = $this->getLocalizedTemplate($fileName)) !== null) { Prado::trace("Loading template {$fileName}", 'System.Web.UI.TTemplateManager'); if (($cache = $this->getApplication()->getCache()) === null) { return new TTemplate(file_get_contents($fileName), dirname($fileName), $fileName); } else { $array = $cache->get(self::TEMPLATE_CACHE_PREFIX . $fileName); if (is_array($array)) { list($template, $timestamps) = $array; if ($this->getApplication()->getMode() === TApplicationMode::Performance) { return $template; } $cacheValid = true; foreach ($timestamps as $tplFile => $timestamp) { if (!is_file($tplFile) || filemtime($tplFile) > $timestamp) { $cacheValid = false; break; } } if ($cacheValid) { return $template; } } $template = new TTemplate(file_get_contents($fileName), dirname($fileName), $fileName); $includedFiles = $template->getIncludedFiles(); $timestamps = array(); $timestamps[$fileName] = filemtime($fileName); foreach ($includedFiles as $includedFile) { $timestamps[$includedFile] = filemtime($includedFile); } $cache->set(self::TEMPLATE_CACHE_PREFIX . $fileName, array($template, $timestamps)); return $template; } } else { return null; } }
/** * Applies the theme to a particular control. * The control's class name and SkinID value will be used to * identify which skin to be applied. If the control's SkinID is empty, * the default skin will be applied. * @param TControl the control to be applied with a skin * @return boolean if a skin is successfully applied * @throws TConfigurationException if any error happened during the skin application */ public function applySkin($control) { $type = get_class($control); if (($id = $control->getSkinID()) === '') { $id = 0; } if (isset($this->_skins[$type][$id])) { foreach ($this->_skins[$type][$id] as $name => $value) { Prado::trace("Applying skin {$name} to {$type}", 'System.Web.UI.TThemeManager'); if (is_array($value)) { switch ($value[0]) { case TTemplate::CONFIG_EXPRESSION: $value = $this->evaluateExpression($value[1]); break; case TTemplate::CONFIG_ASSET: $value = $this->_themeUrl . '/' . ltrim($value[1], '/'); break; case TTemplate::CONFIG_DATABIND: $control->bindProperty($name, $value[1]); break; case TTemplate::CONFIG_PARAMETER: $control->setSubProperty($name, $this->getApplication()->getParameters()->itemAt($value[1])); break; case TTemplate::CONFIG_TEMPLATE: $control->setSubProperty($name, $value[1]); break; case TTemplate::CONFIG_LOCALIZATION: $control->setSubProperty($name, Prado::localize($value[1])); break; default: throw new TConfigurationException('theme_tag_unexpected', $name, $value[0]); break; } } if (!is_array($value)) { if (strpos($name, '.') === false) { if ($control->hasProperty($name)) { if ($control->canSetProperty($name)) { $setter = 'set' . $name; $control->{$setter}($value); } else { throw new TConfigurationException('theme_property_readonly', $type, $name); } } else { throw new TConfigurationException('theme_property_undefined', $type, $name); } } else { // complex property $control->setSubProperty($name, $value); } } } return true; } else { return false; } }
/** * Sends a header. * @param string header * @param boolean whether the header should replace a previous similar header, or add a second header of the same type */ public function appendHeader($value, $replace = true) { Prado::trace("Sending header '{$value}'", 'System.Web.THttpResponse'); header($value, $replace); }
private function _buildSmartToString($tableInfo) { $code = "\tpublic function __toString() {"; $property = "throw new THttpException(500, 'Not implemented yet.');"; try { foreach ($tableInfo->getColumns() as $column) { if (isset($column->IsPrimaryKey) && $column->IsPrimaryKey) { $property = str_replace($this->uqChars, "", $column->ColumnName); } elseif ($column->PdoType == PDO::PARAM_STR && $column->DBType != "date") { $property = str_replace($this->uqChars, "", $column->ColumnName); break; } } } catch (Exception $ex) { Prado::trace($ex->getMessage()); } $code .= "\n\t\treturn \$this->{$property};"; $code .= "\n\t}"; return $code; }
/** * Loads a specific config file. * @param string config file name * @param string the page path that the config file is associated with. The page path doesn't include the page name. */ public function loadFromFile($fname, $configPagePath) { Prado::trace("Loading page configuration file {$fname}", 'System.Web.Services.TPageService'); if (empty($fname) || !is_file($fname)) { return; } $dom = new TXmlDocument(); if ($dom->loadFromFile($fname)) { $this->loadFromXml($dom, dirname($fname), $configPagePath); } else { throw new TConfigurationException('pageserviceconf_file_invalid', $fname); } }
/** * Copies a file to a directory. * Copying is done only when the destination file does not exist * or has an older file modification time. * @param string source file path * @param string destination directory (if not exists, it will be created) */ protected function copyFile($src, $dst) { if (!is_dir($dst)) { @mkdir($dst); @chmod($dst, PRADO_CHMOD); } $dstFile = $dst . DIRECTORY_SEPARATOR . basename($src); if (@filemtime($dstFile) < @filemtime($src)) { Prado::trace("Publishing file {$src} to {$dstFile}", 'System.Web.TAssetManager'); @copy($src, $dstFile); } }
/** * Resolves the requested service. * This method implements a URL-based service resolution. * A URL in the format of /index.php?sp=serviceID.serviceParameter * will be resolved with the serviceID and the serviceParameter. * You may override this method to provide your own way of service resolution. * @param array list of valid service IDs * @return string the currently requested service ID, null if no service ID is found * @see constructUrl */ public function resolveRequest($serviceIDs) { Prado::trace("Resolving request from " . $_SERVER['REMOTE_ADDR'], 'System.Web.THttpRequest'); $getParams = $this->parseUrl(); foreach ($getParams as $name => $value) { $_GET[$name] = $value; } $this->_items = array_merge($_GET, $_POST); $this->_requestResolved = true; foreach ($serviceIDs as $serviceID) { if ($this->contains($serviceID)) { $this->setServiceID($serviceID); $this->setServiceParameter($this->itemAt($serviceID)); return $serviceID; } } return null; }
/** * @param string method of PDOStatement to be called * @param mixed the first parameter to be passed to the method * @return mixed the method execution result */ private function queryInternal($method, $mode) { $params = $this->_connection->enableParamLogging && !empty($this->_params) ? '. Bind with parameter ' . implode(', ', $this->_params) : ''; Prado::trace('Querying SQL: ' . $this->getText() . $params, 'System.Testing.Data.TDbCommand'); try { /* if($this->_connection->enableProfiling) Prado::beginProfile('System.Testing.Data.TDbCommand.query('.$this->getText().')','System.Testing.Data.TDbCommand.query'); */ if ($this->_statement instanceof PDOStatement) { $this->_statement->execute(); } else { $this->_statement = $this->getConnection()->getPdoInstance()->query($this->getText()); } if ($method === '') { $result = new TDbDataReader($this); } else { $result = $this->_statement->{$method}($mode); $this->_statement->closeCursor(); } /* if($this->_connection->enableProfiling) Prado::endProfile('System.Testing.Data.TDbCommand.query('.$this->getText().')','System.Testing.Data.TDbCommand.query'); */ return $result; } catch (Exception $e) { /* if($this->_connection->enableProfiling) prado::endProfile('System.Testing.Data.TDbCommand.query('.$this->getText().')','System.Testing.Data.TDbCommand.query'); */ Prado::log('Error in querying SQL: ' . $this->getText() . $params, TLogger::ERROR, 'System.Testing.Data..TDbCommand'); throw new TDbException('TDbCommand failed to execute the SQL statement: {0}', $e->getMessage()); } }
/** * Loads the template associated with this control class. * @return ITemplate the parsed template structure */ protected function loadTemplate() { Prado::trace("Loading template " . get_class($this), 'System.Web.UI.TTemplateControl'); $template = $this->getService()->getTemplateManager()->getTemplateByClassName(get_class($this)); return $template; }
/** * Loads configuration and initializes application. * Configuration file will be read and parsed (if a valid cached version exists, * it will be used instead). Then, modules are created and initialized; * Afterwards, the requested service is created and initialized. * @param string configuration file path (absolute or relative to current executing script) * @param string cache file path, empty if no present or needed * @throws TConfigurationException if module is redefined of invalid type, or service not defined or of invalid type */ protected function initApplication() { Prado::trace('Initializing application', 'System.TApplication'); if ($this->_configFile !== null) { if ($this->_cacheFile === null || @filemtime($this->_cacheFile) < filemtime($this->_configFile)) { $config = new TApplicationConfiguration(); $config->loadFromFile($this->_configFile); if ($this->_cacheFile !== null) { file_put_contents($this->_cacheFile, Prado::serialize($config), LOCK_EX); } } else { $config = Prado::unserialize(file_get_contents($this->_cacheFile)); } $this->applyConfiguration($config, false); } if (($serviceID = $this->getRequest()->resolveRequest(array_keys($this->_services))) === null) { $serviceID = $this->getPageServiceID(); } $this->startService($serviceID); }
/** * Raises 'OnDataBinding' event. * This method is invoked when {@link dataBind} is invoked. * @param TEventParameter event parameter to be passed to the event handlers */ public function onDataBinding($param) { Prado::trace("onDataBinding()", 'System.Web.UI.TControl'); $this->raiseEvent('OnDataBinding', $this, $param); }
/** * This is the relational version of {@link CActiveRecord::count()}. * @since 1.0.3 */ public function count($condition = '', $params = array()) { Prado::trace(get_class($this->_joinTree->model) . '.count() eagerly', 'System.Testing.Data.ActiveRecord.TActiveRecord'); $criteria = $this->_builder->createCriteria($condition, $params); if ($this->_criteria !== null) { $this->_criteria->mergeWith($criteria); $criteria = $this->_criteria; } return $this->_joinTree->count($criteria); }
/** * Raises onInitComplete event. * At the time when this method is invoked, application modules are loaded, * user request is resolved and the corresponding service * is loaded and initialized. The application is about to start processing * the user request. */ public function onInitComplete() { Prado::trace("Executing onInitComplete()", 'System.TApplication'); $this->raiseEvent('onInitComplete', $this, null); }
/** * Closes the currently active DB connection. * It does nothing if the connection is already closed. */ protected function close() { Prado::trace('Closing DB connection', 'System.Testing.Data.TDbConnection'); $this->_pdo = null; $this->_active = false; $this->_schema = null; }
/** * Deletes rows with the specified condition. * See {@link find()} for detailed explanation about $condition and $params. * @param mixed query condition or criteria. * @param array parameters to be bound to an SQL statement. * @return integer the number of rows deleted */ public function deleteAll($condition = '', $params = array()) { Prado::trace(get_class($this) . '.deleteAll()', 'System.Testing.Data.ActiveRecord.TActiveRecord'); $builder = $this->getCommandBuilder(); $criteria = $builder->createCriteria($condition, $params); $this->applyScopes($criteria); $command = $builder->createDeleteCommand($this->getTableSchema(), $criteria); return $command->execute(); }
/** * Saves page state from persistent storage. */ protected function savePageState() { Prado::trace("Saving state", 'System.Web.UI.TPage'); $state =& $this->saveStateRecursive($this->getEnableViewState()); $this->getStatePersister()->save($state); }
/** * Flush expired values from cache depending on {@link setFlushInterval FlushInterval} * @param boolean override {@link setFlushInterval FlushInterval} and force deletion of expired items * @return void * @since 3.1.5 */ public function flushCacheExpired($force = false) { $interval = $this->getFlushInterval(); if (!$force && $interval === 0) { return; } $key = 'TDbCache:' . $this->_cacheTable . ':flushed'; $now = time(); $next = $interval + (int) $this->getApplication()->getGlobalState($key, 0); if ($force || $next <= $now) { if (!$this->_cacheInitialized) { $this->initializeCache(); } Prado::trace(($force ? 'Force flush of expired items: ' : 'Flush expired items: ') . $this->id . ', ' . $this->_cacheTable, 'System.Caching.TDbCache'); $sql = 'DELETE FROM ' . $this->_cacheTable . ' WHERE expire<>0 AND expire<' . $now; $this->getDbConnection()->createCommand($sql)->execute(); $this->getApplication()->setGlobalState($key, $now); } }
/** * Loads a specific config file. * @param string config file name * @param string the page path that the config file is associated with. The page path doesn't include the page name. */ public function loadFromFile($fname, $configPagePath) { Prado::trace("Loading page configuration file {$fname}", 'System.Web.Services.TPageService'); if (empty($fname) || !is_file($fname)) { return; } if (Prado::getApplication()->getConfigurationType() == TApplication::CONFIG_TYPE_PHP) { $fcontent = (include $fname); $this->loadFromPhp($fcontent, dirname($fname), $configPagePath); } else { $dom = new TXmlDocument(); if ($dom->loadFromFile($fname)) { $this->loadFromXml($dom, dirname($fname), $configPagePath); } else { throw new TConfigurationException('pageserviceconf_file_invalid', $fname); } } }
/** * Renders the callback response by adding additional callback data and * javascript actions in the header and page state if required. * @param THtmlWriter html content writer. */ protected function renderResponse($writer) { Prado::trace("ActivePage renderResponse()", 'System.Web.UI.ActiveControls.TActivePageAdapter'); //renders all the defered render() calls. foreach ($this->_controlsToRender as $rid => $forRender) { $forRender[0]->render($forRender[1]); } $response = $this->getResponse(); //send response data in header if ($response->getHasAdapter()) { $responseData = $response->getAdapter()->getResponseData(); if ($responseData !== null) { $data = TJavaScript::jsonEncode($responseData); $this->appendContentPart($response, self::CALLBACK_DATA_HEADER, $data); //$response->appendHeader(self::CALLBACK_DATA_HEADER.': '.$data); } } //sends page state in header if (($handler = $this->getCallbackEventTarget()) !== null) { if ($handler->getActiveControl()->getClientSide()->getEnablePageStateUpdate()) { $pagestate = $this->getPage()->getClientState(); $this->appendContentPart($response, self::CALLBACK_PAGESTATE_HEADER, $pagestate); //$response->appendHeader(self::CALLBACK_PAGESTATE_HEADER.': '.$pagestate); } } //safari must receive at least 1 byte of data. $writer->write(" "); //output the end javascript if ($this->getPage()->getClientScript()->hasEndScripts()) { $writer = $response->createHtmlWriter(); $this->getPage()->getClientScript()->renderEndScripts($writer); $this->getPage()->getCallbackClient()->evaluateScript($writer); } //output the actions $executeJavascript = $this->getCallbackClientHandler()->getClientFunctionsToExecute(); $actions = TJavaScript::jsonEncode($executeJavascript); $this->appendContentPart($response, self::CALLBACK_ACTION_HEADER, $actions); //$response->appendHeader(self::CALLBACK_ACTION_HEADER.': '.$actions); }
/** * Generate a SOAP fault message. * @param string message title * @param mixed message details * @param string message code, defalt is 'SERVER'. * @param string actors * @param string message name */ public function fault($title, $details = '', $code = 'SERVER', $actor = '', $name = '') { Prado::trace('SOAP-Fault ' . $code . ' ' . $title . ' : ' . $details, 'System.Web.Services.TSoapService'); $this->_server->fault($code, $title, $actor, $details, $name); }
/** * Runs the service. */ public function run() { Prado::trace("Running XMLRPC service", 'System.Web.Services.TXmlRpcService'); $server = $this->createServer(); $this->getResponse()->setContentType('text/xml'); $this->getResponse()->setCharset('UTF-8'); // provide XMLRPC service Prado::trace("Handling XMLRPC request", 'System.Web.Services.TXmlRpcService'); $server->run(); }
/** * Initializes this module. * This method is required by the IModule interface. It makes sure that * UniquePrefix has been set, creates a Memcache instance and connects * to the memcache server. * @param TApplication Prado application, can be null * @param TXmlElement configuration for this module, can be null * @throws TConfigurationException if memcache extension is not installed or memcache sever connection fails */ public function init($config) { if (!extension_loaded('memcache')) { throw new TConfigurationException('memcache_extension_required'); } $this->_cache = new Memcache(); $this->loadConfig($config); if (count($this->_servers)) { foreach ($this->_servers as $server) { Prado::trace('Adding server ' . $server['Host'] . ' from serverlist', 'System.Caching.TMemCache'); if ($this->_cache->addServer($server['Host'], $server['Port'], $server['Persistent'], $server['Weight'], $server['Timeout'], $server['RetryInterval']) === false) { throw new TConfigurationException('memcache_connection_failed', $server['Host'], $server['Port']); } } } else { Prado::trace('Adding server ' . $this->_host, 'System.Caching.TMemCache'); if ($this->_cache->addServer($this->_host, $this->_port) === false) { throw new TConfigurationException('memcache_connection_failed', $this->_host, $this->_port); } } $this->_initialized = true; parent::init($config); }
/** * Renders the callback response by adding additional callback data and * javascript actions in the header and page state if required. * @param THtmlWriter html content writer. */ protected function renderResponse($writer) { Prado::trace("ActivePage renderResponse()", 'System.Web.UI.ActiveControls.TActivePageAdapter'); //renders all the defered render() calls. foreach ($this->_controlsToRender as $rid => $forRender) { $forRender[0]->render($forRender[1]); } $response = $this->getResponse(); //send response data in header if ($response->getHasAdapter()) { $responseData = $response->getAdapter()->getResponseData(); if ($responseData !== null) { $data = TJavaScript::jsonEncode($responseData); $this->appendContentPart($response, self::CALLBACK_DATA_HEADER, $data); } } //sends page state in header if (($handler = $this->getCallbackEventTarget()) !== null) { if ($handler->getActiveControl()->getClientSide()->getEnablePageStateUpdate()) { $pagestate = $this->getPage()->getClientState(); $this->appendContentPart($response, self::CALLBACK_PAGESTATE_HEADER, $pagestate); } } //safari must receive at least 1 byte of data. $writer->write(" "); //output the end javascript if ($this->getPage()->getClientScript()->hasEndScripts()) { $writer = $response->createHtmlWriter(); $this->getPage()->getClientScript()->renderEndScriptsCallback($writer); $this->getPage()->getCallbackClient()->evaluateScript($writer); } //output the actions $executeJavascript = $this->getCallbackClientHandler()->getClientFunctionsToExecute(); $actions = TJavaScript::jsonEncode($executeJavascript); $this->appendContentPart($response, self::CALLBACK_ACTION_HEADER, $actions); $cs = $this->Page->getClientScript(); // collect all stylesheet file references $stylesheets = $cs->getStyleSheetUrls(); if (count($stylesheets) > 0) { $this->appendContentPart($response, self::CALLBACK_STYLESHEETLIST_HEADER, TJavaScript::jsonEncode($stylesheets)); } // collect all stylesheet snippets references $stylesheets = $cs->getStyleSheetCodes(); if (count($stylesheets) > 0) { $this->appendContentPart($response, self::CALLBACK_STYLESHEET_HEADER, TJavaScript::jsonEncode($stylesheets)); } // collect all script file references $scripts = $cs->getScriptUrls(); if (count($scripts) > 0) { $this->appendContentPart($response, self::CALLBACK_SCRIPTLIST_HEADER, TJavaScript::jsonEncode($scripts)); } // collect all hidden field references $fields = $cs->getHiddenFields(); if (count($fields) > 0) { $this->appendContentPart($response, self::CALLBACK_HIDDENFIELDLIST_HEADER, TJavaScript::jsonEncode($fields)); } }