/** * Function: submit * Submits a post to the blog owner. */ public function route_submit() { if (!Visitor::current()->group->can("submit_article")) { show_403(__("Access Denied"), __("You do not have sufficient privileges to submit articles.")); } if (!empty($_POST)) { if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey) { show_403(__("Access Denied"), __("Invalid security key.")); } if (empty($_POST['body'])) { Flash::notice(__("Post body can't be empty!"), redirect("/")); } if (!isset($_POST['draft'])) { $_POST['draft'] = "true"; } $_POST['body'] = "{$_POST['body']}\n\n\n{$_POST['name']}\n{$_POST['email']}\n"; $post = Feathers::$instances[$_POST['feather']]->submit(); if (!in_array(false, $post)) { Flash::notice(__("Thank you for your submission. ", "submission"), "/"); } } if (Theme::current()->file_exists("forms/post/submit")) { MainController::current()->display("forms/post/submit", array("feather" => $feather), __("Submit a Text Post")); } else { require "pages/submit.php"; } }
/** * Initialize the database connection * * @param string $type Either mysql, mysqli, oracle. Default is mysql * @return boolean */ public static function init($type = 'mysql') { if ($type == 'mysql' || $type == '') { if (!(self::$DB = new DB_MySQL())) { self::$error = self::$DB->error; self::$errno = self::$DB->errno; return false; } self::connect(Config::current()->db_username, Config::current()->db_password, Config::current()->db_name, Config::current()->db_host); self::set_table_prefix(Config::current()->db_prefix); } elseif ($type == 'mysqli') { if (!(self::$DB = new DB_MySQLi())) { self::$error = self::$DB->error; self::$errno = self::$DB->errno; return false; } self::connect(Config::current()->db_username, Config::current()->db_password, Config::current()->db_name, Config::current()->db_host); self::set_table_prefix(Config::current()->db_prefix); } elseif ($type == 'pdo') { if (!(self::$DB = new DB_PDO())) { self::$error = self::$DB->error; self::$errno = self::$DB->errno; return false; } self::connect('sqlite:' . Config::current()->db_name); self::set_table_prefix(Config::current()->db_prefix); } else { self::$DB = new DB_MySQL(); self::$error = 'Invalid database type'; return false; } return true; }
public function thumbnail($width = 20, $height = 20) { if (!in_array(strtolower($this->info["extension"]), array("png", "jpg", "jpeg", "gif"))) { return; } echo '<img src="' . Config::current()->chyrp_url . '/includes/thumb.php?file=../uploads/' . $this->path . '&max_width=' . $width . '&max_height=' . $height . '" class="thumbnail" alt="attachment" />'; }
static function scripts($scripts) { $route = Route::current()->action; if ($route == "index" or $route == "archive" or $route == "search") { $scripts[] = Config::current()->chyrp_url . "/modules/cascade/javascript.php"; return $scripts; } }
public function indexAction($uri = array()) { $this->post = new Post($uri['post']); // $this->paginator = new Void; if (!$this->post->success) { return Error::quit(404, 'So Sorry!', 'The post you are trying to view doesn\'t exist. Please try visiting the <a href="' . Config::current()->url . '">home page</a>.'); } return $this->output(); }
/** * Function: group * Returns the user's <Group> or the "Guest Group". * * !! DEPRECATED AFTER 2.0 !! */ public function group() { if (!isset($this->group_id)) { return new Group(Config::current()->guest_group); } elseif (isset($this->group_name)) { return new Group(null, array("read_from" => array("id" => $this->group_id, "name" => $this->group_name))); } else { $group = new Group($this->group_id); return $group->no_results ? new Group(Config::current()->default_group) : $group; } }
/** * Function: add * Adds a user to the database with the passed username, password, and e-mail. * * Calls the @add_user@ trigger with the inserted user. * * Parameters: * $login - The Login for the new user. * $password - The Password for the new user. Don't hash this, it's done in the function. * $email - The E-Mail for the new user. * * Returns: * The newly created <User>. * * See Also: * <update> */ static function add($login, $password, $email, $full_name = "", $website = "", $group_id = null, $joined_at = null) { $config = Config::current(); $sql = SQL::current(); $trigger = Trigger::current(); $new_values = array("login" => strip_tags($login), "password" => self::hashPassword($password), "email" => strip_tags($email), "full_name" => strip_tags($full_name), "website" => strip_tags($website), "group_id" => fallback($group_id, $config->default_group), "joined_at" => fallback($joined_at, datetime())); $trigger->filter($new_values, "before_add_user"); $sql->insert("users", $new_values); $user = new self($sql->latest()); $trigger->call("add_user", $user); return $user; }
public function remove_expired() { foreach ((array) glob($this->caches . "/*/*.html") as $file) { if (time() - filemtime($file) > Config::current()->cache_expire) { @unlink($file); } $dir = dirname($file); if (!count((array) glob($dir . "/*"))) { @rmdir($dir); } } }
private function __construct() { $config = Config::current(); // Setup Default paths: // Controller paths to Scan: self::$paths['controller'][] = APPPATH . 'controllers/'; // Class paths to Scan: self::$paths['class'][] = APPPATH . 'classes/'; // Language paths to Scan: self::$paths['language'][] = APPPATH . 'languages/'; // Page paths to Scan: self::$paths['template'][] = CONTENTPATH . 'templates/' . $config->template . '/'; }
/** * Scan the plugin registry for custom roles, tasks and commands, * and register them as existing. */ function scan() { static $scanned = false; if ($scanned) { return; } $scanned = true; $parser = new XMLParser; $schemapath = Main::getDataPath(); if (!file_exists(Main::getDataPath() . '/channel-1.0.xsd')) { $schemapath = realpath(__DIR__ . '/../../data'); } $roleschema = $schemapath . '/customrole-2.0.xsd'; $taskschema = $schemapath . '/customtask-2.0.xsd'; $commandschema = $schemapath . '/customcommand-2.0.xsd'; try { foreach (Config::current()->channelregistry as $channel) { foreach ($this->listPackages($channel->name) as $package) { $chan = $channel->name; $files = $this->info($package, $chan, 'installedfiles'); // each package may only have 1 role, task or command foreach ($files as $path => $info) { switch ($info['role']) { case 'customrole' : $roleinfo = $parser->parse($path, $roleschema); $roleinfo = $roleinfo['role']; static::makeAutoloader($roleinfo, 'role'); Installer\Role::registerCustomRole($roleinfo); continue 2; case 'customtask' : $taskinfo = $parser->parse($path, $taskschema); $taskinfo = $taskinfo['task']; static::makeAutoloader($taskinfo, 'task'); Task\Common::registerCustomTask($taskinfo); continue 2; case 'customcommand' : $commands = $parser->parse($path, $commandschema); $this->addCommand($commands['commands']['command']); continue 2; } } } } } catch (\Exception $e) { Logger::log(0, 'Unable to add all custom roles/tasks/commands: ' . $e); } }
static function admin_context($context) { $theme = Config::current()->theme; $theme_dir = THEME_DIR . "/"; $file = ltrim(isset($_GET['file']) ? $_GET['file'] : "info.yaml", "/"); $cur_file = $theme_dir . $file; $ext = array("css", "js", "php", "pot", "twig", "yaml"); $context["editor"]["list_all"] = php_file_tree($theme_dir, "?action=theme_editor&file=[link]", $ext); if (isset($cur_file) and is_file($cur_file)) { $context["editor"]["file_name"] = $file; $context["editor"]["file_path"] = $cur_file; $context["editor"]["file_content"] = htmlentities(file_get_contents($cur_file)); } return $context; }
/** * Function: check_update * Checks if the a new version of Chyrp is available. */ public static function check_update() { if (!Config::current()->check_updates) { return; } $xml = self::xml(); $curver = CHYRP_VERSION; foreach ($xml->channel->item as $item) { $newver = $item->version; if (version_compare($curver, $newver, ">=")) { $return = false; } else { $return = _f("<p class='message'>Chyrp v%s is available, you have v%s. <a href='?action=update'>Learn More</a></p>", array($newver, $curver)); break; } } return $return; }
public function __construct($post = null) { $this->config =& Config::current(); if (is_object($post)) { $this->post =& $post; } else { $this->post = $this->query($post); } if (empty($this->post)) { return false; } foreach ($this->post as $key => &$value) { if (is_numeric($value)) { $this->{$key} = (int) $value; } elseif ($key == 'description') { $this->{$key} = $value; } else { $this->{$key} = Helper::entities($value); } } // Format Dates $this->date_raw = $this->date; $this->date_timestamp = strtotime($this->date_raw); $this->date = date($this->config->date_format, $this->date_timestamp); $this->author_name = 'Jay Williams'; // Pull from db, on request? // Format Permalink if ($this->config->permalink == 'slug') { $this->url = $this->config->url . 'post/' . $this->slug; } else { $this->url = $this->config->url . 'post/' . $this->id; } // Add the full url to the image & thumbnail, if it doesn't exist if (substr($this->photo, 0, 7) != 'http://') { $this->photo = $this->config->url . 'content/images/' . $this->photo; } if (substr($this->photo_t, 0, 7) != 'http://') { $this->photo_t = $this->config->url . 'content/images/' . $this->photo_t; } // Everything worked! $this->success = true; }
/** * Function: create * Attempts to create a comment using the passed information. If a Defensio API key is present, it will check it. * * Parameters: * $author - The name of the commenter. * $email - The commenter's email. * $url - The commenter's website. * $body - The comment. * $post - The <Post> they're commenting on. * $type - The type of comment. Optional, used for trackbacks/pingbacks. */ static function create($author, $email, $url, $body, $post, $type = null) { if (!self::user_can($post->id) and !in_array($type, array("trackback", "pingback"))) { return; } $config = Config::current(); $route = Route::current(); $visitor = Visitor::current(); if (!$type) { $status = $post->user_id == $visitor->id ? "approved" : $config->default_comment_status; $type = "comment"; } else { $status = $type; } if (!empty($config->defensio_api_key)) { $comment = array("user-ip" => $_SERVER['REMOTE_ADDR'], "article-date" => when("Y/m/d", $post->created_at), "comment-author" => $author, "comment-type" => $type, "comment-content" => $body, "comment-author-email" => $email, "comment-author-url" => $url, "permalink" => $post->url(), "referrer" => $_SERVER['HTTP_REFERER'], "user-logged-in" => logged_in()); $defensio = new Defensio($config->url, $config->defensio_api_key); list($spam, $spaminess, $signature) = $defensio->auditComment($comment); if ($spam) { self::add($body, $author, $url, $email, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], "spam", $signature, null, null, $post, $visitor->id); error(__("Spam Comment"), __("Your comment has been marked as spam. It will have to be approved before it will show up.", "comments")); } else { $comment = self::add($body, $author, $url, $email, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $status, $signature, null, null, $post, $visitor->id); fallback($_SESSION['comments'], array()); $_SESSION['comments'][] = $comment->id; if (isset($_POST['ajax'])) { exit("{ comment_id: " . $comment->id . ", comment_timestamp: \"" . $comment->created_at . "\" }"); } Flash::notice(__("Comment added."), $post->url() . "#comment_" . $comment->id); } } else { $comment = self::add($body, $author, $url, $email, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $status, "", null, null, $post, $visitor->id); fallback($_SESSION['comments'], array()); $_SESSION['comments'][] = $comment->id; if (isset($_POST['ajax'])) { exit("{ comment_id: " . $comment->id . ", comment_timestamp: \"" . $comment->created_at . "\" }"); } Flash::notice(__("Comment added."), $post->url() . "#comment_" . $comment->id); } }
public function __construct($archive = null, $option = array()) { $this->config =& Config::current(); if (isset($option['per_page'])) { $this->page = (int) $option['per_page']; } else { $this->per_page = (int) $this->config->per_page; } if (isset($option['page'])) { $this->page = (int) $option['page']; } elseif (Uri::get('page')) { $this->page = (int) Uri::get('page'); } if (is_object($archive)) { $this->_posts =& $archive; } else { $this->posts($archive); } if (empty($this->_posts)) { return false; } // Everything worked! $this->success = true; }
public function sidebar() { $config = Config::current(); $wrapper = explode('{feed}', $config->friendfeedr_wrapper); ?> <?php echo $wrapper[0]; ?> <script type="text/javascript" src="http://friendfeed.com/embed/widget/<?php echo $config->friendfeedr_username; ?> ?v=3&num=10&hide_logo=1&hide_comments_likes=1"></script><noscript><a href="http://friendfeed.com/<?php echo $config->friendfeedr_username; ?> "><img alt="View my FriendFeed" style="border:0;" src="http://friendfeed.com/embed/widget/<?php echo $config->friendfeedr_username; ?> ?v=3&num=10&hide_logo=1&hide_comments_likes=1&format=png"/></a></noscript> <?php echo $wrapper[1]; ?> <?php }
private function auth($login, $password, $do = 'add') { if (!Config::current()->enable_xmlrpc) { throw new Exception(__("XML-RPC support is disabled for this site.")); } global $user; if (!User::authenticate($login, $password)) { throw new Exception(__("Login incorrect.")); } else { $user = new User(null, array('where' => array('login' => $login))); } if (!$user->group->can("{$do}_own_post", "{$do}_post", "{$do}_draft", "{$do}_own_draft")) { throw new Exception(_f("You don't have permission to %s posts/drafts.", array($do))); } }
/** * Install a fully downloaded package * * Using \PEAR2\Pyrus\FileTransactions and the PEAR2\Pyrus\Installer\Role* to * group files in appropriate locations, the install() method then passes * on the registration of installation to \PEAR2\Pyrus\Registry. If necessary, * Config will update the install-time snapshots of configuration * @param \PEAR2\Pyrus\Package $package */ function install(PackageInterface $package) { $this->_options = array(); $lastversion = Config::current()->registry->info($package->name, $package->channel, 'version'); $globalreplace = array('attribs' => array('from' => '@' . 'PACKAGE_VERSION@', 'to' => 'version', 'type' => 'package-info')); foreach ($package->installcontents as $file) { $channel = $package->channel; // {{{ assemble the destination paths $roles = Installer\Role::getValidRoles($package->getPackageType()); if (!in_array($file->role, $roles)) { throw new Installer\Exception('Invalid role `' . $file->role . "' for file " . $file->name); } $role = Installer\Role::factory($package->getPackageType(), $file->role); $role->setup($this, $package, $file['attribs'], $file->name); if (!$role->isInstallable()) { continue; } $transact = AtomicFileTransaction::getTransactionObject($role); $info = $role->getRelativeLocation($package, $file, true); $dir = $info[0]; $dest_file = $info[1]; // }}} // pretty much nothing happens if we are only registering the install if (isset($this->_options['register-only'])) { continue; } try { $transact->mkdir($dir, 0755); } catch (AtomicFileTransaction\Exception $e) { throw new Installer\Exception("failed to mkdir {$dir}", $e); } Logger::log(3, "+ mkdir {$dir}"); if ($file->md5sum) { $md5sum = md5_file($package->getFilePath($file->packagedname)); if (strtolower($md5sum) == strtolower($file->md5sum)) { Logger::log(2, "md5sum ok: {$dest_file}"); } else { if (!isset(Main::$options['force'])) { throw new Installer\Exception("bad md5sum for file " . $file->name); } Logger::log(0, "warning : bad md5sum for file " . $file->name); } } else { // installing from package.xml in source control, save the md5 of the current file $file->md5sum = md5_file($package->getFilePath($file->packagedname)); } if (strpos(PHP_OS, 'WIN') === false) { if ($role->isExecutable()) { $mode = ~octdec(Config::current()->umask) & 0777; Logger::log(3, "+ chmod +x {$dest_file}"); } else { $mode = ~octdec(Config::current()->umask) & 0666; } } else { $mode = null; } try { $transact->createOrOpenPath($dest_file, $package->getFileContents($file->packagedname, true), $mode); } catch (AtomicFileTransaction\Exception $e) { throw new Installer\Exception("failed writing to {$dest_file}", $e); } $tasks = $file->tasks; // only add the global replace task if it is not preprocessed if ($package->isNewPackage() && !$package->isPreProcessed()) { if (isset($tasks['tasks:replace'])) { if (isset($tasks['tasks:replace'][0])) { $tasks['tasks:replace'][] = $globalreplace; } else { $tasks['tasks:replace'] = array($tasks['tasks:replace'], $globalreplace); } } else { $tasks['tasks:replace'] = $globalreplace; } } $fp = false; foreach (new Package\Creator\TaskIterator($tasks, $package, Task\Common::INSTALL, $lastversion) as $name => $task) { if (!$fp) { $fp = $transact->openPath($dest_file); } $task->startSession($fp, $dest_file); if (!rewind($fp)) { throw new Installer\Exception('task ' . $name . ' closed the file pointer, invalid task'); } } if ($fp) { fclose($fp); } } }
static function getParanoiaLevel(Config $config = null) { if (isset(self::$paranoid)) { return self::$paranoid; } if (null === $config) { $config = Config::current(); } return $config->paranoia; }
ini_set('display_errors', true); ob_start(); if (version_compare(PHP_VERSION, "5.3.0", "<")) { exit("Chyrp requires PHP 5.3.0 or greater. Installation cannot continue."); } require_once INCLUDES_DIR . "/helpers.php"; require_once INCLUDES_DIR . "/lib/gettext/gettext.php"; require_once INCLUDES_DIR . "/lib/gettext/streams.php"; require_once INCLUDES_DIR . "/lib/YAML.php"; require_once INCLUDES_DIR . "/lib/PasswordHash.php"; require_once INCLUDES_DIR . "/class/Config.php"; require_once INCLUDES_DIR . "/class/SQL.php"; require_once INCLUDES_DIR . "/class/Model.php"; require_once INCLUDES_DIR . "/model/User.php"; # Prepare the Config interface. $config = Config::current(); # Atlantic/Reykjavik is 0 offset. Set it so the timezones() function is # always accurate, even if the server has its own timezone settings. $default_timezone = oneof(ini_get("date.timezone"), "Atlantic/Reykjavik"); set_timezone($default_timezone); # Sanitize all input depending on magic_quotes_gpc's enabled status. sanitize_input($_GET); sanitize_input($_POST); sanitize_input($_COOKIE); sanitize_input($_REQUEST); $protocol = (!empty($_SERVER['HTTPS']) and $_SERVER['HTTPS'] !== "off" or $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = $protocol . $_SERVER['HTTP_HOST'] . str_replace("/install.php", "", $_SERVER['REQUEST_URI']); $index = parse_url($url, PHP_URL_PATH) ? "/" . trim(parse_url($url, PHP_URL_PATH), "/") . "/" : "/"; $htaccess = "<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase {$index}\nRewriteCond %{REQUEST_FILENAME} !-f\n" . "RewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^.+\$ index.php [L]\n</IfModule>"; $path = preg_quote($index, "/"); $htaccess_has_chyrp = (file_exists(MAIN_DIR . "/.htaccess") and preg_match("/<IfModule mod_rewrite\\.c>\n([\\s]*)RewriteEngine On\n([\\s]*)RewriteBase {$path}\n" . "([\\s]*)RewriteCond %\\{REQUEST_FILENAME\\} !-f\n([\\s]*)RewriteCond %\\{REQUEST_FILENAME\\}" . " !-d\n([\\s]*)RewriteRule \\^\\.\\+\\\$ index\\.php \\[L\\]\n([\\s]*)<\\/IfModule>/", file_get_contents(MAIN_DIR . "/.htaccess")));
/** * Build an extension from source. Runs "phpize" in the source * directory, and compiles there. * * @param \PEAR2\Pyrus\PackageInterface $pkg package object * * @param mixed $callback callback function used to report output, * see PEAR_Builder::_runCommand for details * * @return array an array of associative arrays with built files, * format: * array( array( 'file' => '/path/to/ext.so', * 'php_api' => YYYYMMDD, * 'zend_mod_api' => YYYYMMDD, * 'zend_ext_api' => YYYYMMDD ), * ... ) * * @access public * * @see PEAR_Builder::_runCommand */ function build(Registry\Package\Base $pkg, $callback = null) { $config = Config::current(); if (preg_match('/(\\/|\\\\|^)([^\\/\\\\]+)?php(.+)?$/', $config->php_bin, $matches)) { if (isset($matches[2]) && strlen($matches[2]) && trim($matches[2]) != trim($config->php_prefix)) { $this->log(0, 'WARNING: php_bin ' . $config->php_bin . ' appears to have a prefix ' . $matches[2] . ', but' . ' config variable php_prefix does not match'); } if (isset($matches[3]) && strlen($matches[3]) && trim($matches[3]) != trim($config->php_suffix)) { $this->log(0, 'WARNING: php_bin ' . $config->php_bin . ' appears to have a suffix ' . $matches[3] . ', but' . ' config variable php_suffix does not match'); } } $this->current_callback = $callback; if ($pkg->isNewPackage()) { $dir = $config->src_dir . DIRECTORY_SEPARATOR . $pkg->channel . DIRECTORY_SEPARATOR . $pkg->name; } else { $dir = $config->src_dir . DIRECTORY_SEPARATOR . $pkg->name; } $this->buildDirectory = $dir; $old_cwd = getcwd(); if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) { throw new PECLBuild\Exception('could not chdir to package directory ' . $dir); } if (!is_writable($dir)) { throw new PECLBuild\Exception('cannot build in package directory ' . $dir . ', directory not writable'); } $path = $config->bin_dir; if ($env_path = getenv('PATH')) { $path .= ':' . $env_path; } $this->log(0, "cleaning build directory $dir"); $this->_runCommand($config->php_prefix . "phpize" . $config->php_suffix . ' --clean', null, array('PATH' => $path)); $this->log(0, "building in $dir"); if (!$this->_runCommand($config->php_prefix . "phpize" . $config->php_suffix, null, /*array($this, 'phpizeCallback'),*/ array('PATH' => $path))) { throw new PECLBuild\Exception('phpize failed - if running phpize manually from ' . $dir . ' works, please open a bug for pyrus with details'); } // {{{ start of interactive part $configure_command = "$dir/configure" . " --with-php-config=" . $config->php_prefix . "php-config" . $config->php_suffix; if (count($pkg->installrelease->configureoption)) { foreach ($pkg->installrelease->configureoption as $o) { list($r) = $this->ui->ask($o->prompt, array(), $o->default); if (substr($o->name, 0, 5) == 'with-' && ($r == 'yes' || $r == 'autodetect')) { $configure_command .= ' --' . $o->name; } else { $configure_command .= ' --' . $o->name . '=' . trim($r); } } } // }}} end of interactive part $inst_dir = $dir . '/.install'; $this->log(1, "building in $dir"); if (!file_exists($inst_dir) && !mkdir($inst_dir, 0755, true) || !is_dir($inst_dir)) { throw new PECLBuild\Exception('could not create temporary install dir: ' . $inst_dir); } if (getenv('MAKE')) { $make_command = getenv('MAKE'); } else { $make_command = 'make'; } $to_run = array( $configure_command, $make_command, "$make_command INSTALL_ROOT=\"$inst_dir\" install", ); if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) { throw new PECLBuild\Exception('could not chdir to ' . $dir); } $env = $_ENV; // this next line is modified by the installer at packaging time if ('@PEAR-VER@' == '@'.'PEAR-VER@') { // we're running from svn $env['PHP_PEAR_VERSION'] = '2.0.0a1'; } else { $env['PHP_PEAR_VERSION'] = '@PEAR-VER@'; } foreach ($to_run as $cmd) { try { if (!$this->_runCommand($cmd, $callback, $env)) { throw new PECLBuild\Exception("`$cmd' failed"); } } catch (\Exception $e) { chdir($old_cwd); throw $e; } } $this->listInstalledStuff($inst_dir); if (!file_exists('modules') || !is_dir('modules')) { chdir($old_cwd); throw new PECLBuild\Exception("no `modules' directory found"); } $built_files = array(); $prefix = exec($config->php_prefix . "php-config" . $config->php_suffix . " --prefix"); $built_files = $this->harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $inst_dir); chdir($old_cwd); return $built_files; }
/** * Function: display * Renders the page. * * Parameters: * $action - The template file to display, in (theme dir)/pages. * $context - Context for the template. * $title - The title for the page. Defaults to a camlelization of the action, e.g. foo_bar -> Foo Bar. */ public function display($action, $context = array(), $title = "") { $this->displayed = true; fallback($title, camelize($action, true)); $this->context = array_merge($context, $this->context); $trigger = Trigger::current(); $trigger->filter($this->context, array("admin_context", "admin_context_" . str_replace("/", "_", $action))); # Are there any extension-added pages? foreach (array("write" => array(), "manage" => array("import", "export"), "settings" => array(), "extend" => array("modules", "feathers", "themes")) as $main_nav => $val) { ${$main_nav} = $val; $trigger->filter(${$main_nav}, $main_nav . "_pages"); } $visitor = Visitor::current(); $route = Route::current(); $this->context["theme"] = Theme::current(); $this->context["flash"] = Flash::current(); $this->context["trigger"] = $trigger; $this->context["title"] = $title; $this->context["site"] = Config::current(); $this->context["visitor"] = $visitor; $this->context["logged_in"] = logged_in(); $this->context["route"] = $route; $this->context["hide_admin"] = isset($_SESSION["hide_admin"]); $this->context["now"] = time(); $this->context["version"] = CHYRP_VERSION; $this->context["debug"] = DEBUG; $this->context["feathers"] = Feathers::$instances; $this->context["modules"] = Modules::$instances; $this->context["admin_theme"] = $this->admin_theme; $this->context["theme_url"] = Config::current()->chyrp_url . "/admin/themes/" . $this->admin_theme; $this->context["POST"] = $_POST; $this->context["GET"] = $_GET; $this->context["navigation"] = array(); $show = array("write" => array($visitor->group->can("add_draft", "add_post", "add_page")), "manage" => array($visitor->group->can("view_own_draft", "view_draft", "edit_own_draft", "edit_own_post", "edit_post", "delete_own_draft", "delete_own_post", "delete_post", "add_page", "edit_page", "delete_page", "add_user", "edit_user", "delete_user", "add_group", "edit_group", "delete_group")), "settings" => array($visitor->group->can("change_settings")), "extend" => array($visitor->group->can("toggle_extensions"))); foreach ($show as $name => &$arr) { $trigger->filter($arr, $name . "_nav_show"); } $this->context["navigation"]["write"] = array("title" => __("Write"), "show" => in_array(true, $show["write"]), "selected" => in_array($action, $write) or match("/^write_/", $action)); $this->context["navigation"]["manage"] = array("title" => __("Manage"), "show" => in_array(true, $show["manage"]), "selected" => in_array($action, $manage) or match(array("/^manage_/", "/^edit_/", "/^delete_/", "/^new_/"), $action)); $this->context["navigation"]["settings"] = array("title" => __("Settings"), "show" => in_array(true, $show["settings"]), "selected" => in_array($action, $settings) or match("/_settings\$/", $action)); $this->context["navigation"]["extend"] = array("title" => __("Extend"), "show" => in_array(true, $show["extend"]), "selected" => in_array($action, $extend)); $this->subnav_context($route->action); $trigger->filter($this->context["selected"], "nav_selected"); $this->context["sql_debug"] = SQL::current()->debug; $file = MAIN_DIR . "/admin/themes/%s/pages/" . $action . ".twig"; $template = file_exists(sprintf($file, $this->admin_theme)) ? sprintf($file, $this->admin_theme) : sprintf($file, "default"); $config = Config::current(); if (!file_exists($template)) { foreach (array(MODULES_DIR => $config->enabled_modules, FEATHERS_DIR => $config->enabled_feathers) as $path => $try) { foreach ($try as $extension) { if (file_exists($path . "/" . $extension . "/pages/admin/" . $action . ".twig")) { $template = $path . "/" . $extension . "/pages/admin/" . $action . ".twig"; } } } if (!file_exists($template)) { error(__("Template Missing"), _f("Couldn't load template: <code>%s</code>", array($template))); } } # Try the theme first try { $this->theme->getTemplate($template)->display($this->context); } catch (Exception $t) { # Fallback to the default try { $this->default->getTemplate($template)->display($this->context); } catch (Exception $e) { $prettify = preg_replace("/([^:]+): (.+)/", "\\1: <code>\\2</code>", $e->getMessage()); $trace = debug_backtrace(); $twig = array("file" => $e->filename, "line" => $e->lineno); array_unshift($trace, $twig); error(__("Error"), $prettify, $trace); } } }
public function main_index($main) { $ids = array(); # this mammoth query allows searching for posts on the main page in 1 query $record = SQL::current()->query("SELECT __posts.id FROM __posts\n LEFT JOIN __post_attributes\n ON (__posts.id = __post_attributes.post_id\n AND __post_attributes.name = 'category_id')\n LEFT JOIN __categorize\n ON (__post_attributes.value = __categorize.id\n AND __post_attributes.name = 'category_id')\n WHERE (__categorize.show_on_home = 1\n OR __post_attributes.value IS NULL\n OR __post_attributes.value = 0)\n GROUP BY __posts.id\n "); foreach ($record->fetchAll() as $entry) { $ids[] = $entry['id']; } if (empty($ids)) { return false; } $posts = new Paginator(Post::find(array("placeholders" => true, "where" => array("id" => $ids))), Config::current()->posts_per_page); if (empty($posts)) { return false; } $main->display(array("pages/index"), array("posts" => $posts)); return true; }
/** * Function: delete_link * Outputs a delete link for the post, if the <User.can> delete_[model]. * * Parameters: * $text - The text to show for the link. * $before - If the link can be shown, show this before it. * $after - If the link can be shown, show this after it. * $classes - Extra CSS classes for the link, space-delimited. */ public function delete_link($text = null, $before = null, $after = null, $classes = "") { if (!$this->deletable()) { return false; } fallback($text, __("Delete")); $name = strtolower(get_class($this)); echo $before . '<a href="' . Config::current()->chyrp_url . '/admin/?action=delete_' . $name . '&id=' . $this->id . '" title="Delete" class="' . ($classes ? $classes . " " : '') . $name . '_delete_link delete_link" id="' . $name . '_delete_' . $this->id . '">' . $text . '</a>' . $after; }
/** * Function: edit_link * Outputs an edit link for the model, if the visitor's <Group.can> edit_[model]. * * Parameters: * $text - The text to show for the link. * $before - If the link can be shown, show this before it. * $after - If the link can be shown, show this after it. * $classes - Extra CSS classes for the link, space-delimited. */ public function edit_link($text = null, $before = null, $after = null, $classes = "") { if (!$this->editable()) { return false; } fallback($text, __("Edit")); $name = strtolower(get_class($this)); if (@Feathers::$instances[$this->feather]->disable_ajax_edit) { $classes = empty($classes) ? "no_ajax" : $classes . " no_ajax"; } echo $before . '<a href="' . Config::current()->chyrp_url . '/admin/?action=edit_' . $name . '&id=' . $this->id . '" title="Edit" class="' . ($classes ? $classes . " " : '') . $name . '_edit_link edit_link" id="' . $name . '_edit_' . $this->id . '">' . $text . '</a>' . $after; }
<?php if (defined('AJAX') and AJAX or isset($_POST['ajax'])) { foreach ($backtrace as $trace) { $body .= "\n" . _f("%s on line %d", array($trace["file"], fallback($trace["line"], 0))); } exit($body . "HEY_JAVASCRIPT_THIS_IS_AN_ERROR_JUST_SO_YOU_KNOW"); } $jquery = is_callable(array("Config", "current")) ? Config::current()->url . "/includes/lib/gz.php?file=jquery.js" : "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"; Route::current(MainController::current()); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Chyrp: <?php echo $title; ?> </title> <script src="<?php echo $jquery; ?> " type="text/javascript" charset="utf-8"></script> <style type="text/css"> html, body, ul, ol, li, h1, h2, h3, h4, h5, h6, form, fieldset, a, p { margin: 0; padding: 0; border: 0;
function php_file_tree_dir($directory, $return_link, $extensions = array(), $first_call = true) { # Recursive function called by php_file_tree() to list directories/files # Get and sort directories/files if (function_exists("scandir")) { $file = scandir($directory); } else { $file = php4_scandir($directory); } natcasesort($file); # Make directories first $files = $dirs = array(); foreach ($file as $this_file) { if (is_dir("{$directory}/{$this_file}")) { $dirs[] = $this_file; } else { $files[] = $this_file; } } #unset($dirs[$key = array_search('images', $dirs)]); $file = array_merge($dirs, $files); # Filter unwanted extensions if (!empty($extensions)) { foreach (array_keys($file) as $key) { if (!is_dir("{$directory}/{$file[$key]}")) { $ext = substr($file[$key], strrpos($file[$key], ".") + 1); if (!in_array($ext, $extensions)) { unset($file[$key]); } } } } $theme_file_tree = ""; if (count($file) > 2) { # Use 2 instead of 0 to account for . and .. "directories" $theme_file_tree = "<ul"; if ($first_call) { $theme_file_tree .= " class=\"theme-file-tree\""; $first_call = false; } $theme_file_tree .= ">"; foreach ($file as $this_file) { if ($this_file != "." && $this_file != "..") { if (is_dir("{$directory}/{$this_file}")) { # Directory $theme_file_tree .= "<li class=\"pft-dir\"><a href=\"#\">" . htmlspecialchars($this_file) . "</a>"; $theme_file_tree .= php_file_tree_dir("{$directory}/{$this_file}", $return_link, $extensions, false); $theme_file_tree .= "</li>"; } else { # File - Get extension (prepend 'ext-' to prevent invalid classes from extensions that begin with numbers) # $ext = "ext-" . substr($this_file, strrpos($this_file, ".") + 1); $theme = Config::current()->theme; $len = strlen($theme); $dir = substr(stristr($directory, $theme . "/"), $len); $link = str_replace("[link]", "{$dir}/" . urlencode($this_file), $return_link); $theme_file_tree .= "<li class=\"pft-file\"><em><a href=\"{$link}\">" . htmlspecialchars($this_file) . "</a></em></li>"; } } } $theme_file_tree .= "</ul>"; } return $theme_file_tree; }
/** * Function: display * Display the page. * * If "posts" is in the context and the visitor requested a feed, they will be served. * * Parameters: * $file - The theme file to display. * $context - The context for the file. * $title - The title for the page. */ public function display($file, $context = array(), $title = "") { if (is_array($file)) { for ($i = 0; $i < count($file); $i++) { $check = ($file[$i][0] == "/" or preg_match("/[a-zA-Z]:\\\\/", $file[$i])) ? $file[$i] : THEME_DIR . "/" . $file[$i]; if (file_exists($check . ".twig") or $i + 1 == count($file)) { return $this->display($file[$i], $context, $title); } } } $this->displayed = true; $route = Route::current(); $trigger = Trigger::current(); # Serve feeds. if ($this->feed) { if ($trigger->exists($route->action . "_feed")) { return $trigger->call($route->action . "_feed", $context); } if (isset($context["posts"])) { return $this->feed($context["posts"]); } } $this->context = array_merge($context, $this->context); $visitor = Visitor::current(); $config = Config::current(); $theme = Theme::current(); $theme->title = $title; $this->context["theme"] = $theme; $this->context["flash"] = Flash::current(); $this->context["trigger"] = $trigger; $this->context["modules"] = Modules::$instances; $this->context["feathers"] = Feathers::$instances; $this->context["title"] = $title; $this->context["site"] = $config; $this->context["visitor"] = $visitor; $this->context["route"] = Route::current(); $this->context["hide_admin"] = isset($_COOKIE["hide_admin"]); $this->context["version"] = CHYRP_VERSION; $this->context["now"] = time(); $this->context["debug"] = DEBUG; $this->context["POST"] = $_POST; $this->context["GET"] = $_GET; $this->context["sql_queries"] =& SQL::current()->queries; $this->context["visitor"]->logged_in = logged_in(); $this->context["enabled_modules"] = array(); foreach ($config->enabled_modules as $module) { $this->context["enabled_modules"][$module] = true; } $context["enabled_feathers"] = array(); foreach ($config->enabled_feathers as $feather) { $this->context["enabled_feathers"][$feather] = true; } $this->context["sql_debug"] =& SQL::current()->debug; $trigger->filter($this->context, array("main_context", "main_context_" . str_replace("/", "_", $file))); $file = ($file[0] == "/" or preg_match("/[a-zA-Z]:\\\\/", $file)) ? $file : THEME_DIR . "/" . $file; if (!file_exists($file . ".twig")) { error(__("Template Missing"), _f("Couldn't load template: <code>%s</code>", array($file . ".twig"))); } try { return $this->twig->getTemplate($file . ".twig")->display($this->context); } catch (Exception $e) { $prettify = preg_replace("/([^:]+): (.+)/", "\\1: <code>\\2</code>", $e->getMessage()); $trace = debug_backtrace(); $twig = array("file" => $e->filename, "line" => $e->lineno); array_unshift($trace, $twig); error(__("Error"), $prettify, $trace); } }
/** * Function: init_extensions * Initialize all Modules and Feathers. */ function init_extensions() { $config = Config::current(); # Instantiate all Modules. foreach ($config->enabled_modules as $index => $module) { if (!file_exists(MODULES_DIR . "/" . $module . "/" . $module . ".php")) { unset($config->enabled_modules[$index]); continue; } if (file_exists(MODULES_DIR . "/" . $module . "/locale/" . $config->locale . ".mo")) { load_translator($module, MODULES_DIR . "/" . $module . "/locale/" . $config->locale . ".mo"); } require MODULES_DIR . "/" . $module . "/" . $module . ".php"; $camelized = camelize($module); if (!class_exists($camelized)) { continue; } Modules::$instances[$module] = new $camelized(); Modules::$instances[$module]->safename = $module; foreach (YAML::load(MODULES_DIR . "/" . $module . "/info.yaml") as $key => $val) { Modules::$instances[$module]->{$key} = is_string($val) ? __($val, $module) : $val; } } # Instantiate all Feathers. foreach ($config->enabled_feathers as $index => $feather) { if (!file_exists(FEATHERS_DIR . "/" . $feather . "/" . $feather . ".php")) { unset($config->enabled_feathers[$index]); continue; } if (file_exists(FEATHERS_DIR . "/" . $feather . "/locale/" . $config->locale . ".mo")) { load_translator($feather, FEATHERS_DIR . "/" . $feather . "/locale/" . $config->locale . ".mo"); } require FEATHERS_DIR . "/" . $feather . "/" . $feather . ".php"; $camelized = camelize($feather); if (!class_exists($camelized)) { continue; } Feathers::$instances[$feather] = new $camelized(); Feathers::$instances[$feather]->safename = $feather; foreach (YAML::load(FEATHERS_DIR . "/" . $feather . "/info.yaml") as $key => $val) { Feathers::$instances[$feather]->{$key} = is_string($val) ? __($val, $feather) : $val; } } # Initialize all modules. foreach (Feathers::$instances as $feather) { if (method_exists($feather, "__init")) { $feather->__init(); } } foreach (Modules::$instances as $module) { if (method_exists($module, "__init")) { $module->__init(); } } }
/** * Gets the mail from the inbox * Reads all the messages there, and adds posts based on them. Then it deletes the entire mailbox. */ function getMail() { $config = Config::current(); if (time() - 60 * $config->emailblog_minutes >= $config->emailblog_mail_checked) { $hostname = '{' . $config->emailblog_server . '}INBOX'; # this isn't working well on localhost $username = $config->emailblog_address; $password = $config->emailblog_pass; $subjpass = $config->emailblog_subjpass; $inbox = imap_open($hostname, $username, $password) or exit("Cannot connect to Gmail: " . imap_last_error()); $emails = imap_search($inbox, 'SUBJECT "' . $subjpass . '"'); if ($emails) { rsort($emails); foreach ($emails as $email_number) { $message = imap_body($inbox, $email_number); $overview = imap_headerinfo($inbox, $email_number); imap_delete($inbox, $email_number); $title = htmlspecialchars($overview->Subject); $title = preg_replace($subjpass, "", $title); $clean = strtolower($title); $body = htmlspecialchars($message); # The subject of the email is used as the post title # the content of the email is used as the body # not sure about compatibility with images or audio feathers Post::add(array("title" => $title, "body" => $message), $clean, Post::check_url($clean), "text"); } } # close the connection imap_close($inbox, CL_EXPUNGE); $config->set("emailblog_mail_checked", time()); } }