* @version 1.1 * @license Whatever */ Plugin::setInfos(array( 'id' => 'layout_loader', 'title' => __('Layout Loader'), 'description' => __('Automatically loads layout files(.php) contained inside the theme folders.'), 'version' => '1.1', 'website' => 'http://staydecent.ca', 'update_url' => 'http://www.wolfcms.org/plugin-versions.xml', 'type' => 'both' )); if ( ! defined('THEMES_ROOT') ) define('THEMES_ROOT', CMS_ROOT.'/public/themes'); /* Find all themes(by folder) but ignore defaults */ function get_theme_dirs( ) { $dirs = array(); $ignore = array('.', '..', 'simple', 'wolf'); if ( $dh = opendir(THEMES_ROOT) ) { while ( false !== ($dir = readdir($dh)) ) { if ( !in_array($dir, $ignore) ) { if ( is_dir(THEMES_ROOT.'/'.$dir) ) $dirs[] = THEMES_ROOT.'/'.$dir; } } closedir($dh); } return $dirs; } /* Find any theme files within found theme folders */ function get_theme_files( $dirs ) { $files = array(); foreach ( $dirs as $dir ) { if ( $dh = opendir($dir) ) { while ( false !== ($file = readdir($dh)) ) { if ( is_file($dir.'/'.$file) && endsWith($file, '.php') ) { $files[] = $dir.'/'.$file; } } } } return $files; } /* Save a new layout. TODO: Add proper error reporting */ function save_layout( $files ) { foreach ( $files as $file ) { $data = array(); $name = substr(str_replace(THEMES_ROOT.'/', '', $file), 0, -4); $data['name'] = str_replace('/', '_', $name); $data['content_type'] = 'text/html'; $data['content'] = file_get_contents($file); $layout = new Layout($data); if ( ! $layout->save() ) { // Maybe we've added it already, attempt to update existing $args = array(); $args['where'] = Layout::tableNameFromClassName('Layout') . ".name = '".$data['name']."'"; $args['limit'] = 1; $obj = Layout::find($args); $id = $obj->id; if ( ! $layout = Layout::findById($id)) { // Balls! Can't save a new one, can't update an existing! if ( DEBUG ) echo "Layout loader was unable to save: “{$name}.php”"; } else { // Good, we are updating an existing layout // But, lets make sure it's in use if ( $layout->isUsed() ) { $layout = Record::findByIdFrom('Layout', $id); $layout->setFromData($data); if ( ! $layout->save()) { if ( DEBUG ) echo "Layout loader was unable to update: “{$name}.php”"; } else { if ( DEBUG ) echo "Layout loader successfully updated: “{$name}.php”"; Observer::notify('layout_after_edit', $layout); } } } } else { if ( DEBUG ) echo "Layout loader successfully saved: “{$name}.php”"; Observer::notify('layout_after_add', $layout); } } } /* Check if were viewing the front-end */ if ( ! defined('CMS_BACKEND') ) { $themes = get_theme_dirs(); $layouts = get_theme_files($themes); save_layout($layouts); }