/** * Load helpers. * * @param array $helpers An array of helpers to load * * @throws coreException */ public static function loadHelpers($helpers) { static $loaded = array(); // directories $dirs = array(); $dirs[] = coreConfig::get('app_lib_dir') . '/helper'; $dirs[] = coreConfig::get('lib_dir') . '/helper'; $dirs[] = coreConfig::get('core_dir') . '/helper'; foreach ((array) $helpers as $helperName) { if (isset($loaded[$helperName])) { continue; } $fileName = $helperName . 'Helper.php'; foreach ($dirs as $dir) { $included = false; if (is_readable($dir . '/' . $fileName)) { include_once $dir . '/' . $fileName; $included = true; break; } } if (!$included) { throw new coreException(sprintf('Unable to load "%sHelper.php" helper in: %s.', $helperName, implode(', ', $dirs))); } $loaded[$helperName] = true; } }
public static function getInstance($file) { if (is_null(self::$_instance)) { self::$_instance = new Config($file); } return self::$_instance; }
/** * Quick solution to include proprietary or sensitive content for the production * build, such as PayPal, advertising, and so on. Some of these are viewable in * the public site html source, but are better left out of the Open Source * repository to avoid misuse of tracking ids, emails and so on. * * If the asset to include is not found, a box displays a message instead. * * Those assets use a file naming pattern excluded from commits (.gitignore) * * TODO: find way to handle a "production site" branch, instead of run time mode. * * @author Fabrice Denis */ function get_local_content($fromTemplate, $assetName) { ob_start(); if (coreConfig::get('koohii_build')) { $assetFile = '__' . $assetName . 'View.php'; $assetPath = dirname(realpath($fromTemplate)); $file = $assetPath . DIRECTORY_SEPARATOR . $assetFile; if (file_exists($file)) { // render as a partial so we have access to the default template variables $view = new coreView(coreContext::getInstance()); $view->setTemplate($file); echo $view->render(); } else { echo <<<EOD <div style="background:red;color:yellow;padding:10px;"> koohii_build content NOT FOUND: <strong>{$assetName}</strong> </div> EOD; } } else { // show a little box with the name of the local asset echo <<<EOD <div style="border-radius:5px;-moz-border-radius:5px;border:none;background:#b2d2e3;color:#42697e;padding:10px;margin:0 0 1em;"> Public site content: <strong>{$assetName}</strong> </div> EOD; } return ob_get_clean(); }
function pre_end() { $text = ob_get_clean(); // Highlight print_r results if (coreConfig::get('pre_highlight_mode') == 'printr') { // highlight array keys $text = preg_replace('/\\[((.)*?)\\]/i', '<span class="key">\\1</span>', $text); $text = preg_replace('/=>/', '<span class="arrow">=></span>', $text); } else { // fix to avoid matching comments in urls $text = preg_replace('/:\\/\\//', '://', $text); // hightlight strings $text = preg_replace('/(["\'])((.)*?)\\1/i', '<span class="string">\\1\\2\\1</span>', $text); // highlight php tags $text = preg_replace('/<\\?php(\\s+)/', '<span class="php"><?php\\1</span>', $text); $text = preg_replace('/\\?>/', '<span class="php">?></span>', $text); // highlight constants $text = preg_replace('/([A-Z_]{3,})/', '<span class="const">\\1</span>', $text); // highlight static function prefix $text = preg_replace('/(::)/', '<span class="static">\\1</span>', $text); // highlight C++ style comments $text = preg_replace('/(\\/\\/[^\\r\\n]+)/', '<span class="comment">\\1</span>', $text); // highlight C style comments $text = preg_replace('/\\/\\*((.|[\\r\\n])*?)\\*\\//', '<span class="comment">/*\\1*/</span>', $text); // highlight Perl style comments $text = preg_replace('/(\\s|^)(#[^\\r\\n]+)/', '\\1<span class="comment">\\2</span>', $text); // highlight variables $text = preg_replace('/(\\$\\w+)/', '<span class="var">\\1</span>', $text); // highlight some keywords $text = preg_replace('/(function|const)(\\s+)/', '<span class="keyword">\\1</span>\\2', $text); // highlight PhpDoc keys $text = preg_replace('/@(return|param)\\s+(\\w+)/', '<span class="phpdoc">@\\1</span> <span class="type">\\2</span>', $text); } echo $text . "</pre>\n"; }
/** * Load helpers. * * @param array $helpers An array of helpers to load * * @throws coreException */ public static function loadHelpers($helpers) { // common mistake, can't use func_get_args() because possible future sf port if (func_num_args() > 1) { throw new coreException('Use array() to pass multiple helpers.'); } foreach ((array) $helpers as $helperName) { if (isset(self::$loadedHelpers[$helperName])) { continue; } $fileName = $helperName . 'Helper.php'; if (!isset($dirs)) { $dirs = array(); $dirs[] = coreConfig::get('app_lib_dir') . '/helper'; $dirs[] = coreConfig::get('lib_dir') . '/helper'; $dirs[] = coreConfig::get('core_dir') . '/helper'; } foreach ($dirs as $dir) { $included = false; if (is_readable($dir . '/' . $fileName)) { include_once $dir . '/' . $fileName; $included = true; break; } } if (!$included) { throw new coreException(sprintf('Unable to load "%sHelper.php" helper in: %s.', $helperName, implode(', ', $dirs))); } self::$loadedHelpers[$helperName] = true; } }
public function init() { parent::init(); // Verify we're on the correct database //print_r(coreConfig::get('database_connection'));exit; $connectionInfo = coreConfig::get('database_connection'); $this->verbose("Using database: %s", $connectionInfo['database']); $username = trim($this->getOption('u')); $raw_password = trim($this->getOption('p')); if (empty($username) || empty($raw_password)) { $this->throwError('Username or password is empty.'); } $userid = UsersPeer::getUserId($username); if (false === $userid) { $this->throwError('User named "%s" not found.', $username); } $this->verbose("Userid: %s", $userid); $this->verbose("Set password to: %s", $raw_password); $this->updateUser($userid, array('raw_password' => $raw_password)); // only with linked PunBB forum if ($this->args->flag('forum')) { if (coreConfig::get('app_path_to_punbb') !== null) { PunBBUsersPeer::setPassword($username, $raw_password); } else { $this->throwError('Forum password: "******" is not defined in environment "%s"', CORE_ENVIRONMENT); } } $this->verbose('Success!'); }
/** * Returns a revved resource url. * * The .htaccess files redirects those "versioned" files to a php script that * will strip the version number to get the actual file, and return the file * gzipped if possible to minimized download size. * * @param string $resource Css or Javascript url * @return string Resource url with version number in it */ protected function getRevvedResourceUrl($url) { // leave absolute URLs (usually from CDNs like Google and Yahoo) unchanged if (stripos($url, 'http:') === 0) { return $url; } // do not use minified javascripts in debug environment if (coreConfig::get('sf_debug')) { $url = preg_replace('/\\.min\\.js/', '.js', $url); } if (coreConfig::get('sf_debug')) { // in development environment, show the url called by mod_rewrite $url = '/version/cache.php?env=' . CORE_ENVIRONMENT . '&app=' . CORE_APP . '&path=' . urlencode($url); } else { $versions = $this->getResourceVersion(); $path = pathinfo($url); if (isset($versions[$url])) { $ver = '_v' . $versions[$url]; } else { // warn so we know that version number file need to be rebuilt // throw doesn't seem to work here, this is for staging anyway die('No version information for ' . $url); } preg_match('/(.+)(\\.[a-z]+)/', $path['basename'], $matches); $url = $path['dirname'] . '/' . $matches[1] . $ver . $matches[2]; } return $url; }
/** * Return the resource version data, which contains the latest * version number (file modified time) for the css and js files in the project. * * @return array */ protected function getResourceVersion() { if ($this->resourceVersion === null) { $this->resourceVersion = (require_once coreConfig::get('config_dir') . '/versioning.inc.php'); } return $this->resourceVersion; }
public function printStackTrace() { $exception = is_null($this->wrappedException) ? $this : $this->wrappedException; $message = $exception->getMessage(); $response = coreContext::getInstance()->getResponse(); $response->setStatusCode(500); // clean current output buffer while (@ob_end_clean()) { } ob_start(coreConfig::get('sf_compressed') ? 'ob_gzhandler' : ''); header('HTTP/1.1 500 Internal Server Error'); header('Content-Type: text/plain'); if ($message !== '') { header('RTK-Error: ' . $message); } // during development, send back ajax request for debugging if (coreConfig::get('sf_debug')) { try { $request = coreContext::getInstance()->getRequest(); $sJson = $request->getParameter('json'); $oJson = null; if ($sJson !== null) { $oJson = coreJson::decode($sJson); } echo 'Json data = ' . "\n" . ($oJson !== null ? print_r($oJson, true) : $sJson); } catch (Exception $e) { echo 'rtkAjaxException - no Json found, $_POST = ' . "\n" . print_r($_POST, true); } } exit(1); }
/** * Class constructor. * * @note Currently bound to coreSessionStorage, move it to arguments if needed * * @see initialize() */ public function __construct($options = array()) { // @todo: Symfony uses sfSessionStorage factory params (factories.yml) $storage = new coreSessionStorage(coreConfig::get('core_session_params', array())); $this->initialize($storage, $options); if ($this->options['auto_shutdown']) { register_shutdown_function(array($this, 'shutdown')); } }
/** * Sends email to confirm the new login details after a password update. * */ public function sendUpdatePasswordConfirmation($userAddress, $userName, $rawPassword) { $from = coreConfig::get('app_email_robot'); $this->setFrom($from['email'], isset($from['name']) ? $from['name'] : ''); $this->addTo($userAddress, $userName); $this->setSubject('Account update at Reviewing the Kanji'); $body = $this->renderTemplate('updatedPasswordConfirmation', array('username' => $userName, 'password' => $rawPassword, 'email' => $userAddress)); $this->setBodyText($body); $this->send(); }
/** * Implement multi-byte aware ucfirst(). * ucfirst() is not utf8-aware and can cause "Invalid multibyte sequence" down the line. * * @uses coreContext 'sf_charset' * * @param object $string */ public static function mb_ucfirst($string) { if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) { $charset = coreConfig::get('sf_charset'); $first = mb_substr($string, 0, 1, $charset); $string = mb_strtoupper($first, $charset) . mb_substr($string, 1, mb_strlen($string), $charset); } else { throw new Exception(__METHOD__ . ': no mb_substr() support.'); } return $string; }
/** * Load a configuration file for this validator, * and do a basic check to verify its consistency. * * @return array Associative array of fields and rules for validation. * @throws coreException If the file could not be loaded. */ protected function loadConfigurationFile($validatorName) { $moduleName = coreContext::getInstance()->getModuleName(); $file = coreConfig::get('app_module_dir') . '/' . $moduleName . '/validate/' . $validatorName . '.php'; if (!is_readable($file)) { throw new coreException(sprintf("Can not read validator file %s in module %s", $validatorName, $moduleName)); } $configuration = (require $file); if (!is_array($configuration) || !$this->hasParameter($configuration, 'fields')) { throw new coreException(sprintf("Invalid validator file %s in module %s", $validatorName, $moduleName)); } return $configuration; }
public function printStackTrace() { $exception = is_null($this->wrappedException) ? $this : $this->wrappedException; if (coreConfig::get('sf_debug')) { $response = coreContext::getInstance()->getResponse(); $response->setStatusCode(404); return parent::printStackTrace(); } else { // debug message //echo $exception->getMessage(); coreContext::getInstance()->getController()->forward(coreConfig::get('error_404_module'), coreConfig::get('error_404_action')); } }
/** * Configures the applicationconfiguration. * * Override this method if you want to customize your application configuration. */ public function configure() { // profile php execution time $this->profileStart(); // Application configuration settings coreConfig::set('app_zend_lib_dir', coreConfig::get('lib_dir')); // Integrate Zend from project level directory /lib/Zend/ if ($sf_zend_lib_dir = coreConfig::get('app_zend_lib_dir')) { set_include_path($sf_zend_lib_dir . PATH_SEPARATOR . get_include_path()); require_once $sf_zend_lib_dir . '/Zend/Loader.php'; spl_autoload_register(array('Zend_Loader', 'autoload')); } // set default timezone setting, fixes php error 'date(): It is not safe to rely on the system's timezone settings' date_default_timezone_set('UTC'); }
/** * Get all configure information. * @return array */ private static function read() { if (!is_null(self::$aConfig)) { return self::$aConfig; } $sConfigFile = ROOT_PATH . 'config.ini'; if (!is_readable($sConfigFile)) { $sConfigFile = ROOT_PATH . 'config-dev.ini'; } if (!is_readable($sConfigFile)) { trigger_error("Configure file does not exist : " . $sConfigFile); } self::$aConfig = parse_ini_file($sConfigFile, true); return self::$aConfig; }
public function init() { parent::init(); // Verify we're on the correct database //print_r(coreConfig::get('database_connection'));exit; $connectionInfo = coreConfig::get('database_connection'); $this->verbose("Using database: %s", $connectionInfo['database']); $username = trim($this->getOption('username')); $raw_password = trim($this->getOption('password')); if (empty($username) || empty($raw_password)) { $this->throwError('Username or password is empty.'); } if (UsersPeer::usernameExists($username)) { $this->throwError('That username already exists, foo!'); } $this->createUser($username, $raw_password); $this->verbose('Success!'); }
/** * 创建配置对象,读取配置 * @param boolean 调试状态 */ public static function init($debug = FALSE) { self::$config = $debugs = new \StdClass(); // 读取目录下所有文件 $files = glob(ROOT_PATH . '/app/config/autoload/*'); if ($debug) { $files[] = ROOT_PATH . '/app/config/debug.php'; } else { $files[] = ROOT_PATH . '/app/config/global.php'; } foreach ($files as $file) { // 文件读取 $class = "\\Phalcon\\Config\\Adapter\\" . ucfirst(substr($file, -3)); // 读取配置信息 $config = new $class($file); // 整合数据 foreach ($config as $key => $val) { self::$config->{$key} = $val; } } }
public function executeIndex($request) { $username = $request->getParameter('username'); if (!$username) { if ($this->getUser()->isAuthenticated()) { $username = $this->getUser()->getUserName(); } else { // if unauthenticated user checks his (bookmarked?) profile, go to login and back $url = $this->getController()->genUrl('profile/index', true); $this->getUser()->redirectToLogin(array('referer' => $url)); } } if ($user = UsersPeer::getUser($username)) { $this->user = $user; $this->self_account = $user['username'] == $this->getUser()->getUserName(); $this->kanji_count = ReviewsPeer::getReviewedFlashcardCount($user['userid']); $this->total_reviews = ReviewsPeer::getTotalReviews($user['userid']); $this->forum_uid = coreConfig::get('app_path_to_punbb') !== null ? PunBBUsersPeer::getInstance()->getForumUID($username) : false; return coreView::SUCCESS; } return coreView::ERROR; }
/** * Adds a unique version identifier to the css and javascript file names, * (using the local file modified times from build script), to prevent client * browsers from using the cache when a css/js file is updated. * * The .htaccess files redirects those "versioned" files to a php script that * will strip the version number to get the actual file, and return the file * gzipped if possible to minimized download size. * * @param string $resource Css or Javascript url * @return string Resource url with version number in it */ protected function getVersionUrl($url) { // leave absolute URLs (usually from CDNs like Google and Yahoo) unchanged if (stripos($url, 'http:') === 0) { return $url; } // do not use minified javascripts in debug environment if (coreConfig::get('sf_debug')) { $url = preg_replace('/\\.min\\.js/', '.js', $url); } if (coreConfig::get('sf_debug')) { // in development environment, show the url called by mod_rewrite $url = '/version/cached-resource.php?path=' . urlencode($url); } else { $versions = $this->getResourceVersion(); $path = pathinfo($url); $ver = isset($versions[$url]) ? '_v' . $versions[$url] : ''; preg_match('/(.+)(\\.[a-z]+)/', $path['basename'], $matches); $url = $path['dirname'] . '/' . $matches[1] . $ver . $matches[2]; } return $url; }
<?php // Print a debug log of all SQL queries run on the page if (0 && CORE_ENVIRONMENT === 'dev') { $_db = coreContext::getInstance()->getDatabase(); $sqlLog = $_db->getDebugLog(); ?> <div style="background:#800;padding:5px 10px;border:1px solid #c80;font:14px/1.2em Consolas, Courier New;color:#fff;"> <div style="color:yellow;font-weight:bold;"><?php echo count($sqlLog); ?> querries:</div> <?php echo implode("<br/>\n", $sqlLog); ?> </div> <?php } ?> <?php if (coreConfig::get('koohii_build')) { use_helper('__Affiliate'); echo analytics_tracking_code(); } ?> </body> </html>
/** * Retrieve the database. * * @return coreDatabase */ public function getDatabase() { if (!isset($this->factories['database'])) { // Create database connection when needed $db = new coreDatabaseMySQL(coreConfig::get('database_connection')); $db->connect(); $this->set('database', $db); } return isset($this->factories['database']) ? $this->factories['database'] : null; }
/** * Returns the css active class for a link or element, if the given id corresponds * to the currently defined SECONDARY navigation (set by set_secondary_nav() in view template). * * The class is returned as html attribute array, as used by the Tag and Url helpers. * */ function nav_sec($nav_id) { return strcasecmp($nav_id, coreConfig::get('layout.secondarynav.current')) == 0 ? array('class' => 'active') : array(); }
/** * Retrieves relative root url. * * @return string URL */ public function getRelativeUrlRoot() { if ($this->relativeUrlRoot === null) { $this->relativeUrlRoot = coreConfig::get('relative_url_root', preg_replace('#/[^/]+\\.php5?$#', '', $this->getScriptName())); } return ''; //$this->relativeUrlRoot; }
/** * Sends the HTTP headers and the content. */ public function send() { // compress output ob_start(coreConfig::get('sf_compressed') ? 'ob_gzhandler' : null); $this->sendHttpHeaders(); if (!$this->headerOnly) { parent::sendContent(); } ob_end_flush(); }
/** * Clears all current config parameters. */ public static function clear() { self::$config = null; self::$config = array(); }
<h2>Forum Registration</h2> <?php echo form_errors(); ?> <p> As a member of Reviewing the Kanji, you have been registered also on the <a href="<?php echo coreConfig::get('app_forum_url'); ?> " target="_blank">RevTK Community forums</a>, with the <strong>same username and password</strong>. </p> <p> For your convenience, when you login on the main site, <strong>you will also be logged in into the forums</strong>. If you update your password on the main site, your forum password is also updated. If you sign off from the main site, you are also signed off from the forums. </p> <p> In the forums you will be able to discuss with other members, exchange tips and advice for completing "Remembering the Kanji", and just generally chat away about all things Japanese and Japanese learning. Please read the <a href="<?php echo coreConfig::get('app_forum_url') . '/misc.php?action=rules'; ?> " target="_blank">forum rules</a>. </p> </div> </div> </div>
/** * Returns a SQL statement which returns a date+time adjusted to the * timezone of the user ($session->timezone). * * The date returned by this statement will switch at midnight time * of the user's timezone (assuming the user set the timezone properly). * (the user's timezone range is -12...+14) * * @param string If set, * * @todo Move to RevTK extension of core class */ public function localTime($column = 'NOW()') { $timezone = coreContext::getInstance()->get('auth')->getTimezone(); $timediff = $timezone - coreConfig::get('server_timezone', 0); $hours = floor($timediff); $minutes = $hours != $timediff ? '30' : '0'; // some timezones have half-hour precision, convert to minutes $s = sprintf('ADDDATE(%s, INTERVAL \'%d:%d\' HOUR_MINUTE)', $column, $hours, $minutes); return $s; }
config_dir # defaults to CORE_ROOT_DIR/config # Application directories app_dir # defaults to CORE_ROOT_DIR/apps/[appname] app_config_dir # defaults to CORE_ROOT_DIR/apps/[appname]/config app_lib_dir # defaults to CORE_ROOT_DIR/apps/[appname]/lib app_module_dir # defaults to CORE_ROOT_DIR/apps/[appname]/modules app_template_dir # defaults to CORE_ROOT_DIR/apps/[appname]/templates sf_web_dir # defaults to CORE_ROOT_DIR/web sf_upload_dir # defaults to CORE_ROOT_DIR/web/uploads sf_cache_dir # cache root directory (sfCache) sf_root_dir # project root directory sf_symfony_lib_dir # where to autoload symfony classes from sf_charset # defaults to 'utf-8' sf_test # defaults to CORE_DEBUG (front controller) sf_debug # defaults to CORE_DEBUG (front controller) sf_compressed # defaults to enabled if support detected <?php pre_end(); ?> <h2>Example</h2> <p> These are all current coreConfig settings: <?php pre_start('printr'); print_r(coreConfig::getAll()); pre_end(); ?>
Username : <?php echo $username . "\n"; ?> Password : <?php echo $password . "\n"; ?> Email : <?php echo $email . "\n"; ?> <?php if ($forum_uid) { ?> You have also been registered with the same username and password on the Reviewing the Kanji community forums: <?php echo coreConfig::get('app_forum_url') . "\n"; ?> You can access your forum profile here: <?php echo coreConfig::get('app_forum_url'); ?> /profile.php?id=<?php echo $forum_uid . "\n"; } ?> -Reviewing the Kanji Mailer.