/** * Get a list of all available modules. * * @return array */ public static function getModuleList() { if (self::$modules) { return self::$modules; } // find all backend directories $dirs = glob(Curry_Util::path(Curry_Core::$config->curry->projectPath, 'include', '*', 'Module'), GLOB_ONLYDIR); if (!$dirs) { $dirs = array(); } $dirs[] = Curry_Util::path(Curry_Core::$config->curry->basePath, 'include', 'Curry', 'Module'); // find all php files in the directories self::$modules = array(); foreach ($dirs as $dir) { $it = new Curry_FileFilterIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)), '/\\.php$/'); foreach ($it as $file) { $path = realpath($file->getPathname()); $pos = strrpos($path, DIRECTORY_SEPARATOR . "include" . DIRECTORY_SEPARATOR); if ($pos !== FALSE) { $className = str_replace(DIRECTORY_SEPARATOR, '_', substr($path, $pos + 9, -4)); self::$modules[$className] = $className; } } } ksort(self::$modules); return self::$modules; }
public function render(Curry_Backend $backend, array $params) { $view = $this->view ? $this->view : $this->parentView; if (!$view instanceof Curry_ModelView_List) { throw new Exception('Expected view to be of type Curry_ModelView_List, got ' . get_class($view)); } $view = clone $view; // Send response headers to the browser $filename = $this->filename ? $this->filename : $view->getOption('title') . ".csv"; header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename=' . Curry_String::escapeQuotedString($filename)); $fp = fopen('php://output', 'w'); // Print column headers $headers = array(); foreach ($view->getOption('columns') as $name => $opts) { // TODO: should we really ignore display/escape option? $view->addColumn($name, array('display' => null, 'escape' => false)); $headers[] = $opts['label']; } if ($this->includeHeaders) { Curry_Util::fputcsv($fp, $headers); } // Print rows $page = 0; $maxPerPage = 100; $view->setOptions(array('maxPerPage' => $maxPerPage)); do { $results = $view->getJson(array('p' => ++$page)); foreach ($results['rows'] as $row) { Curry_Util::fputcsv($fp, $row); } } while (count($results['rows']) == $maxPerPage); fclose($fp); exit; }
/** {@inheritdoc} */ public function showMain() { $this->addMainMenu(); $configFile = Curry_Core::$config->curry->configPath; if (!$configFile) { $this->addMessage("Configuration file not set.", self::MSG_ERROR); } else { if (!is_writable($configFile)) { $this->addMessage("Configuration file doesn't seem to be writable.", self::MSG_ERROR); } } $config = new Zend_Config($configFile ? require $configFile : array(), true); $defaultConfig = Curry_Core::getDefaultConfiguration(); $form = new Curry_Form(array('action' => url('', array("module", "view")), 'method' => 'post')); $themes = array(); $backendPath = Curry_Util::path(true, Curry_Core::$config->curry->wwwPath, 'shared', 'backend'); if ($backendPath) { foreach (new DirectoryIterator($backendPath) as $entry) { $name = $entry->getFilename(); if (!$entry->isDot() && $entry->isDir() && $name !== 'common') { $themes[$name] = $name; } } } $activeTheme = isset($config->curry->backend->theme) ? $config->curry->backend->theme : false; if ($activeTheme && !array_key_exists($activeTheme, $themes)) { $themes[$activeTheme] = $activeTheme; } $pages = PagePeer::getSelect(); // General $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'General', 'elements' => array('name' => array('text', array('label' => 'Name', 'required' => true, 'value' => isset($config->curry->name) ? $config->curry->name : '', 'description' => 'Name of site, shown in backend header and page title by default.', 'placeholder' => $defaultConfig->curry->name)), 'baseUrl' => array('text', array('label' => 'Base URL', 'value' => isset($config->curry->baseUrl) ? $config->curry->baseUrl : '', 'description' => 'The URL to use when creating absolute URLs. This should end with a slash, and may include a path.', 'placeholder' => $defaultConfig->curry->baseUrl)), 'adminEmail' => array('text', array('label' => 'Admin email', 'value' => isset($config->curry->adminEmail) ? $config->curry->adminEmail : '')), 'divertOutMailToAdmin' => array('checkbox', array('label' => 'Divert outgoing email to adminEmail', 'value' => isset($config->curry->divertOutMailToAdmin) ? $config->curry->divertOutMailToAdmin : '', 'description' => 'All outgoing Curry_Mail will be diverted to adminEmail.')), 'developmentMode' => array('checkbox', array('label' => 'Development mode', 'value' => isset($config->curry->developmentMode) ? $config->curry->developmentMode : '')), 'forceDomain' => array('checkbox', array('label' => 'Force domain', 'value' => isset($config->curry->forceDomain) ? $config->curry->forceDomain : '', 'description' => 'If the domain of the requested URL doesn\'t match the domain set by Base URL, the user will be redirected to the correct domain.')), 'fallbackLanguage' => array('select', array('label' => 'Fallback Language', 'multiOptions' => array('' => '[ None ]') + LanguageQuery::create()->find()->toKeyValue('PrimaryKey', 'Name'), 'value' => isset($config->curry->fallbackLanguage) ? $config->curry->fallbackLanguage : '', 'description' => 'The language used when no language has been specified for the rendered page. Also the language used in backend context.'))))), 'general'); // Backend $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Backend', 'class' => 'advanced', 'elements' => array('theme' => array('select', array('label' => 'Theme', 'multiOptions' => array('' => '[ Default ]') + $themes, 'value' => isset($config->curry->backend->theme) ? $config->curry->backend->theme : '', 'description' => 'Theme for the administrative back-end.')), 'logotype' => array('filebrowser', array('label' => 'Backend Logotype', 'value' => isset($config->curry->backend->logotype) ? $config->curry->backend->logotype : '', 'description' => 'Path to the backend logotype. The height of this image should be 100px.')), 'templatePage' => array('select', array('label' => 'Template page', 'multiOptions' => array('' => '[ None ]') + $pages, 'value' => isset($config->curry->backend->templatePage) ? $config->curry->backend->templatePage : '', 'description' => 'The page containing page templates (i.e. pages to be used as base pages). When creating new pages or editing a page using the Content tab, only this page and pages below will be shown as base pages.')), 'defaultEditor' => array('text', array('label' => 'Default HTML editor', 'value' => isset($config->curry->defaultEditor) ? $config->curry->defaultEditor : '', 'description' => 'The default WYSIWYG editor to use with the article module.', 'placeholder' => $defaultConfig->curry->defaultEditor)), 'autoBackup' => array('text', array('label' => 'Automatic database backup', 'value' => isset($config->curry->autoBackup) ? $config->curry->autoBackup : '', 'placeholder' => $defaultConfig->curry->autoBackup, 'description' => 'Specifies the number of seconds since last backup to create automatic database backups when logged in to the backend.')), 'revisioning' => array('checkbox', array('label' => 'Revisioning', 'value' => isset($config->curry->revisioning) ? $config->curry->revisioning : '', 'description' => 'When enabled, a new working revision will automatically be created when you create a page. You will also be warned when editing a published page revision')), 'autoPublish' => array('checkbox', array('label' => 'Auto Publish', 'value' => isset($config->curry->autoPublish) ? $config->curry->autoPublish : '', 'description' => 'When enabled, a check will be made on every request to check if there are any pages that should be published (using publish date).')), 'noauth' => array('checkbox', array('label' => 'Disable Backend Authorization', 'value' => isset($config->curry->backend->noauth) ? $config->curry->backend->noauth : '', 'description' => 'This will completely disable authorization for the backend.')), 'autoUpdateIndex' => array('checkbox', array('label' => 'Auto Update Search Index', 'value' => isset($config->curry->autoUpdateIndex) ? $config->curry->autoUpdateIndex : '', 'description' => 'Automatically update (rebuild) search index when changing page content.'))))), 'backend'); // Live edit $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Live edit', 'class' => 'advanced', 'elements' => array('liveEdit' => array('checkbox', array('label' => 'Enable Live Edit', 'value' => isset($config->curry->liveEdit) ? $config->curry->liveEdit : $defaultConfig->curry->liveEdit, 'description' => 'Enables editing of content directly in the front-end.')), 'placeholderExclude' => array('textarea', array('label' => 'Excluded placeholders', 'value' => isset($config->curry->backend->placeholderExclude) ? join(PHP_EOL, $config->curry->backend->placeholderExclude->toArray()) : '', 'description' => 'Prevent placeholders from showing up in live edit mode. Use newlines to separate placeholders.', 'rows' => 5))))), 'liveEdit'); // Error pages $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Error pages', 'class' => 'advanced', 'elements' => array('notFound' => array('select', array('label' => 'Page not found (404)', 'multiOptions' => array('' => '[ None ]') + $pages, 'value' => isset($config->curry->errorPage->notFound) ? $config->curry->errorPage->notFound : '')), 'unauthorized' => array('select', array('label' => 'Unauthorized (401)', 'multiOptions' => array('' => '[ None ]') + $pages, 'value' => isset($config->curry->errorPage->unauthorized) ? $config->curry->errorPage->unauthorized : '')), 'error' => array('select', array('label' => 'Internal server error (500)', 'multiOptions' => array('' => '[ None ]') + $pages, 'value' => isset($config->curry->errorPage->error) ? $config->curry->errorPage->error : ''))))), 'errorPage'); // Maintenance $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Maintenance', 'class' => 'advanced', 'elements' => array('enabled' => array('checkbox', array('label' => 'Enabled', 'required' => true, 'value' => isset($config->curry->maintenance->enabled) ? $config->curry->maintenance->enabled : '', 'description' => 'When maintenance is enabled, users will not be able to access the pages. Only a page (specified below) will be shown. If no page is specified, the message will be shown.')), 'page' => array('select', array('label' => 'Page to show', 'multiOptions' => array('' => '[ None ]') + $pages, 'value' => isset($config->curry->maintenance->page) ? $config->curry->maintenance->page : '')), 'message' => array('textarea', array('label' => 'Message', 'value' => isset($config->curry->maintenance->message) ? $config->curry->maintenance->message : '', 'rows' => 6, 'cols' => 40))))), 'maintenance'); // Mail $testEmailUrl = url('', array('module', 'view' => 'TestEmail')); $dlgOpts = array('width' => 600, 'minHeight' => 150); $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Mail', 'class' => 'advanced', 'elements' => array('method' => array('select', array('label' => 'Transport', 'multiOptions' => array('' => '[ Default ]', 'smtp' => 'SMTP', 'sendmail' => 'PHP mail() function, ie sendmail.'), 'value' => isset($config->curry->mail->method) ? $config->curry->mail->method : '')), 'host' => array('text', array('label' => 'Host', 'value' => isset($config->curry->mail->host) ? $config->curry->mail->host : '')), 'port' => array('text', array('label' => 'Port', 'value' => isset($config->curry->mail->options->port) ? $config->curry->mail->options->port : '')), 'auth' => array('select', array('label' => 'Auth', 'multiOptions' => array('' => '[ Default ]', 'plain' => 'plain', 'login' => 'login', 'cram-md5' => 'cram-md5'), 'value' => isset($config->curry->mail->options->auth) ? $config->curry->mail->options->auth : '')), 'username' => array('text', array('label' => 'Username', 'value' => isset($config->curry->mail->options->username) ? $config->curry->mail->options->username : '')), 'password' => array('password', array('label' => 'Password')), 'ssl' => array('select', array('label' => 'SSL', 'multiOptions' => array('' => 'Disabled', 'ssl' => 'SSL', 'tls' => 'TLS'), 'value' => isset($config->curry->mail->options->ssl) ? $config->curry->mail->options->ssl : '')), 'mailTest' => array('rawHtml', array('value' => '<a href="' . $testEmailUrl . '" class="btn dialog" data-dialog="' . htmlspecialchars(json_encode($dlgOpts)) . '">Test email</a>'))))), 'mail'); // Paths $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Paths', 'class' => 'advanced', 'elements' => array('basePath' => array('text', array('label' => 'Base path', 'value' => isset($config->curry->basePath) ? $config->curry->basePath : '', 'placeholder' => $defaultConfig->curry->basePath)), 'projectPath' => array('text', array('label' => 'Project Path', 'value' => isset($config->curry->projectPath) ? $config->curry->projectPath : '', 'placeholder' => $defaultConfig->curry->projectPath)), 'wwwPath' => array('text', array('label' => 'WWW path', 'value' => isset($config->curry->wwwPath) ? $config->curry->wwwPath : '', 'placeholder' => $defaultConfig->curry->wwwPath)), 'vendorPath' => array('text', array('label' => 'Vendor path', 'value' => isset($config->curry->vendorPath) ? $config->curry->vendorPath : '', 'placeholder' => $defaultConfig->curry->vendorPath))))), 'paths'); // Encoding $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Encoding', 'class' => 'advanced', 'elements' => array('internal' => array('text', array('label' => 'Internal Encoding', 'value' => isset($config->curry->internalEncoding) ? $config->curry->internalEncoding : '', 'description' => 'The internal encoding for PHP.', 'placeholder' => $defaultConfig->curry->internalEncoding)), 'output' => array('text', array('label' => 'Output Encoding', 'value' => isset($config->curry->outputEncoding) ? $config->curry->outputEncoding : '', 'description' => 'The default output encoding for pages.', 'placeholder' => $defaultConfig->curry->outputEncoding))))), 'encoding'); // Misc $form->addSubForm(new Curry_Form_SubForm(array('legend' => 'Misc', 'class' => 'advanced', 'elements' => array('error_notification' => array('checkbox', array('label' => 'Error notification', 'value' => isset($config->curry->errorNotification) ? $config->curry->errorNotification : '', 'description' => 'If enabled, an attempt to send error-logs to the admin email will be performed when an error occur.')), 'log_propel' => array('checkbox', array('label' => 'Propel Logging', 'value' => isset($config->curry->propel->logging) ? $config->curry->propel->logging : '', 'description' => 'Database queries and other debug information will be logged to the selected logging facility.')), 'debug_propel' => array('checkbox', array('label' => 'Debug Propel', 'value' => isset($config->curry->propel->debug) ? $config->curry->propel->debug : '', 'description' => 'Enables query counting but doesn\'t log queries.')), 'log' => array('select', array('label' => 'Logging', 'multiOptions' => array('' => '[ Other ]', 'none' => 'Disable logging', 'firebug' => 'Firebug'), 'value' => isset($config->curry->log->method) ? $config->curry->log->method : '')), 'update_translations' => array('checkbox', array('label' => 'Update Language strings', 'value' => isset($config->curry->updateTranslationStrings) ? $config->curry->updateTranslationStrings : '', 'description' => 'Add strings as they are used and record last used timestamp'))))), 'misc'); $form->addElement('submit', 'save', array('label' => 'Save', 'disabled' => $configFile ? null : 'disabled')); if (isPost() && $form->isValid($_POST)) { $this->saveSettings($config, $form->getValues()); } $this->addMainContent($form); }
/** * Save url to file and return cached path. * * @param string $url * @param bool $forceUpdate * @return string */ protected static function getCachedFile($url, $forceUpdate = false) { $packagesPath = Curry_Util::path(Curry_Core::$config->curry->projectPath, 'data', 'cache', 'packages'); if (!file_exists($packagesPath)) { mkdir($packagesPath, 0777, true); } $target = Curry_Util::path($packagesPath, sha1($url)); if ($forceUpdate || !file_exists($target)) { file_put_contents($target, file_get_contents($url)); } return $target; }
/** * Create new folder view. */ public function showNewFolder() { $form = $this->getNewForm(); if (isPost() && $form->isValid($_POST)) { $values = $form->getValues(); $target = Curry_Util::path($this->root, $values['location'], $values['name']); mkdir($target); self::redirect(url('', array('module', 'view' => 'Main'))); } else { $this->addMainContent($form); } }
/** * Get minified CSS path. * * @param array $files * @return string */ public function getMinifyCss($files) { $basedir = 'cache/'; $target = $basedir . sha1(serialize($files)) . '.css'; // create basedir if it doesnt exist if (!is_dir($basedir)) { @mkdir($basedir, 0777, true); } // if minified file already exists, make sure it's up to date if (file_exists($target)) { $data = self::readMinificationHeader($target); if (self::getLastModified($data['files']) == $data['modified']) { trace_notice('Using cached css minification file'); return $target . '?' . $data['modified']; } trace_notice('Updating css minification file'); } // Combine files (and process imports) $imports = array(); $content = ""; foreach ($files as $file) { $processor = new CssProcessor($file['source']); $relative = Curry_Util::getRelativePath($basedir, dirname($file['source'])); $content .= $processor->getContent($file['media'], $relative); $imports = array_merge($imports, $processor->getImportedFiles()); } // Minify $source = new Minify_Source(array('id' => $target, 'content' => $content, 'contentType' => Minify::TYPE_CSS)); $content = Minify::combine(array($source)); // Add header $header = array('files' => $imports, 'modified' => self::getLastModified($imports)); $content = "/* " . json_encode($header) . " */\n" . $content; // Write content file_put_contents($target, $content); return $target . '?' . $header['modified']; }
/** * Get a list of all backend modules. * * @return array */ public static function getBackendList() { if (self::$backendList) { return self::$backendList; } // find all backend directories $dirs = glob(Curry_Util::path(Curry_Core::$config->curry->projectPath, 'include', '*', 'Backend'), GLOB_ONLYDIR); if (!$dirs) { $dirs = array(); } $dirs[] = Curry_Util::path(Curry_Core::$config->curry->basePath, 'include', 'Curry', 'Backend'); // find all php files in the directories self::$backendList = array(); foreach ($dirs as $dir) { $it = new Curry_FileFilterIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)), '/\\.php$/'); foreach ($it as $file) { $path = realpath($file->getPathname()); $pos = strrpos($path, DIRECTORY_SEPARATOR . "include" . DIRECTORY_SEPARATOR); if ($pos !== FALSE) { $pi = pathinfo($path); $className = str_replace(DIRECTORY_SEPARATOR, '_', substr($path, $pos + 9, -4)); if (class_exists($className, true)) { $r = new ReflectionClass($className); if (is_subclass_of($className, 'Curry_Backend') && !$r->isAbstract()) { self::$backendList[$className] = $pi['filename']; } } } } } ksort(self::$backendList); return self::$backendList; }
/** * Restore page from serialized object. * * @param Page $page * @param array $pageData * @param array $pageMap */ public static function restorePage(Page $page, array $pageData, array $pageMap) { unset($pageData['id']); unset($pageData['uid']); unset($pageData['name']); unset($pageData['url']); if ($pageData['redirect_page']) { $page->setRedirectPage(self::findPageByMap($pageData['redirect_page'], $pageMap)); } $page->fromArray($pageData, BasePeer::TYPE_FIELDNAME); $page->save(); if (!$pageData['revision']) { return; } // Create new revision $pr = new PageRevision(); $pr->setPage($page); $pr->setBasePage(self::findPageByMap($pageData['revision']['base_page'], $pageMap)); $pr->fromArray($pageData['revision'], BasePeer::TYPE_FIELDNAME); $pr->setDescription('Copied'); $page->setWorkingPageRevision($pr); $page->save(); // Add module data... $order = array(); $parentPages = Curry_Array::objectsToArray($page->getWorkingPageRevision()->getInheritanceChain(true), null, 'getPageId'); $inheritedModules = $pr->getModules(); foreach ($pageData['revision']['modules'] as $module) { $pm = null; if (!$module['is_inherited']) { $pm = PageModuleQuery::create()->findOneByUid($module['uid']); if ($pm && !in_array($pm->getPageId(), $parentPages)) { // Page module exists, but is not in our "inheritance chain" // Give the module a new unique-id, and create the module here $pm->setUid(Curry_Util::getUniqueId()); $pm->save(); $pm = null; } } else { // find inherited module foreach ($inheritedModules as $inheritedModule) { if ($inheritedModule->getUid() == $module['uid']) { $pm = $inheritedModule; break; } } } if (!$pm) { $pm = new PageModule(); $pm->setPage($page); $pm->fromArray($module, BasePeer::TYPE_FIELDNAME); } if (!$module['is_inherited']) { $rm = new RevisionModule(); $rm->setPageModule($pm); $rm->setPageRevision($pr); } foreach ($module['datas'] as $moduleData) { $md = new ModuleData(); $md->setPageModule($pm); $md->setPageRevision($pr); $md->fromArray($moduleData, BasePeer::TYPE_FIELDNAME); } $order[] = $pm->getUid(); } $pr->save(); $modules = Curry_Array::objectsToArray($pr->getModules(), 'getUid'); if (array_keys($modules) !== $order) { foreach ($order as $uid) { $module = $modules[$uid]; $sortorder = new ModuleSortorder(); $sortorder->setPageModule($module); $sortorder->setPageRevision($pr); $sortorder->insertAtBottom(); $sortorder->save(); } } $page->setActivePageRevision($pr); $page->save(); }
/** * Get file details. * * @param array $selected * @return array */ public function getFileInfo($selected) { if (count($selected) == 1) { try { $path = $selected[0]; $physical = self::virtualToPhysical($path); $public = self::physicalToPublic($physical); if (!is_file($physical)) { return null; } $owner = fileowner($physical); if (function_exists('posix_getpwuid')) { $owner = posix_getpwuid($owner); $owner = '<span title="' . $owner['uid'] . '">' . htmlspecialchars($owner['name']) . '</span>'; } $group = filegroup($physical); if (function_exists('posix_getgrgid')) { $group = posix_getgrgid($group); $group = '<span title="' . $group['gid'] . '">' . htmlspecialchars($group['name']) . '</span>'; } $fi = array('Name' => '<h2>' . basename($physical) . '</h2>', 'Preview' => '', 'Size' => '<strong>Size: </strong>' . Curry_Util::humanReadableBytes(filesize($physical)), 'Writable' => '<strong>Writable: </strong>' . (self::isWritable($physical) ? 'Yes' : 'No'), 'Permissions' => '<strong>Permissions: </strong>' . Curry_Util::getFilePermissions($physical), 'Owner' => '<strong>Owner: </strong>' . $owner . ' / ' . $group); switch (strtolower(pathinfo($physical, PATHINFO_EXTENSION))) { case 'jpg': case 'gif': case 'png': case 'bmp': $image = getimagesize($physical); $fi['Preview'] = '<img src="' . $public . '?' . filemtime($physical) . '" alt="" class="preview" />'; if ($image[0] > 240 || $image[1] > 240) { $fi['Preview'] = '<a href="' . $public . '?' . filemtime($physical) . '" target="_blank" class="fullscreen-preview" title="Click to toggle fullscreen">' . $fi['Preview'] . '</a>'; } $fi['Dimensions'] = '<strong>Dimension: </strong>' . $image[0] . 'x' . $image[1]; if (self::isPhysicalWritable($physical)) { $fi['Actions'] = '<a href="' . url('', array('module', 'view' => 'PixlrEdit', 'image' => $public)) . '" class="dialog" onclick="$(this).data(\'dialog\').width = $(window).width() - 20; $(this).data(\'dialog\').height = $(window).height() - 20;" data-dialog=\'{"width":"90%","height":600,"resizable":false,"draggable":false}\'>Edit with Pixlr</a>'; } break; case 'ogg': case 'ogv': case 'mp4': case 'webm': $fi['Preview'] = '<video src="' . $public . '" class="preview" controls />'; break; case 'mp3': case 'oga': case 'wav': $fi['Preview'] = '<audio src="' . $public . '" class="preview" controls />'; break; case 'swf': $size = getimagesize($physical); $flash = Curry_Flash::embed(Curry_Flash::SWFOBJECT_STATIC, $public, $size[0], $size[1], '9.0.0', array()); $fi['Preview'] = $flash['html']; break; } return $fi; } catch (Exception $e) { trace_error($e->getMessage()); } } else { $totalSize = 0; foreach ($selected as $s) { $physical = self::virtualToPhysical($s); $totalSize += filesize($physical); } return array('Name' => '<h2>' . count($selected) . ' files</h2>', 'Size' => '<strong>Size: </strong>' . Curry_Util::humanReadableBytes($totalSize)); } return null; }
/** * Open the lucene search index and return it. * * @param bool $forceCreation * @return Zend_Search_Lucene_Interface */ public static function getSearchIndex($forceCreation = false) { if (!self::$index || $forceCreation) { if (self::$index) { self::$index->commit(); self::$index = null; } Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num_CaseInsensitive()); Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding(self::$config->curry->internalEncoding); $path = Curry_Util::path(self::$config->curry->projectPath, 'data', 'searchindex'); self::$index = $forceCreation ? Zend_Search_Lucene::create($path) : Zend_Search_Lucene::open($path); } return self::$index; }
protected static function createFilebrowserAccess($userOrRole, $name, $path, $write = true) { $fba = new FilebrowserAccess(); $fba->setName($name); if ($userOrRole instanceof User) { $fba->setUser($userOrRole); } else { if ($userOrRole instanceof UserRole) { $fba->setUserRole($userOrRole); } } $fba->setPath($path); $fba->setWrite($write); @mkdir(Curry_Util::path(Curry_Core::$config->curry->wwwPath, $path), 0777, true); return $fba; }
/** * Restore database. */ public function showRestore() { $this->showMainMenu(); $tables = array(); $selectedTables = array(); $disabledTables = array(); foreach (Curry_Propel::getModels() as $package => $classes) { $tables[$package] = array(); foreach ($classes as $table) { $tables[$package][$table] = $table; if (method_exists($table, 'save')) { $selectedTables[] = $table; } else { $disabledTables[] = $table; } } } $files = array('' => '-- Select file --', 'upload' => '[ Upload from computer ]', 'remote' => '[ From remote server ]'); $path = Curry_Backend_DatabaseHelper::createBackupName('*.txt'); foreach (array_reverse(glob($path)) as $file) { $files[$file] = basename($file) . ' (' . Curry_Util::humanReadableBytes(filesize($file)) . ')'; } $form = new Curry_Form(array('action' => url('', array("module", "view", "page_id")), 'method' => 'post', 'enctype' => 'multipart/form-data', 'elements' => array('tables' => array('multiselect', array('label' => 'Tables', 'multiOptions' => $tables, 'value' => $selectedTables, 'disable' => $disabledTables, 'size' => 15)), 'file' => array('select', array('label' => 'From file', 'multiOptions' => $files, 'class' => 'trigger-change', 'onchange' => "\$('#uploadfile-label').next().andSelf()[this.value == 'upload'?'show':'hide']();" . "\$('#remote-label').next().andSelf()[this.value == 'remote'?'show':'hide']();")), 'uploadfile' => array('file', array('label' => 'Upload file', 'valueDisabled' => true)), 'remote' => array('text', array('label' => 'Remote')), 'max_execution_time' => array('text', array('label' => 'Max execution time', 'value' => '', 'description' => 'Input time in seconds to allow interruption if the time taken to restore would exceed the maximum execution time.'))))); $form->addElement('submit', 'Go'); if (isPost() && $form->isValid($_POST)) { if ($form->file->getValue() == 'upload') { if (!$form->uploadfile->isUploaded()) { throw new Exception('No file was uploaded.'); } $fileinfo = $form->uploadfile->getFileInfo(); Curry_Backend_DatabaseHelper::restoreFromFile($fileinfo['uploadfile']['tmp_name'], $form->tables->getValue(), 0, 0, $this); } else { if ($form->file->getValue() == 'remote') { if (!$form->remote->getValue()) { throw new Exception('No remote URL set'); } $url = url($form->remote->getValue()); $post = array('login_username' => $url->getUser(), 'login_password' => $url->getPassword(), 'tables' => '*', 'name' => 'db.txt', 'type' => 'local'); $url->setUser(null)->setPassword(null)->setPath('/admin.php')->add(array('module' => 'Curry_Backend_Database', 'view' => 'Backup')); $context = stream_context_create(array('http' => array('method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query($post)))); $fp = fopen($url, 'r', false, $context); Curry_Backend_DatabaseHelper::restoreFromFile($fp, $form->tables->getValue(), 0, 0, $this); fclose($fp); } else { if ($form->file->getValue()) { Curry_Backend_DatabaseHelper::restoreFromFile($form->file->getValue(), $form->tables->getValue(), (int) $form->max_execution_time->getValue(), 0, $this); } } } } $this->addMainContent($form); }
/** * Save new module. * * @todo Set module position. * * @param PageRevision $pageRevision * @param array $values * @return PageModule */ public static function saveNewModule(PageRevision $pageRevision, array $values) { $pageModule = new PageModule(); $pageModule->setUid(Curry_Util::getUniqueId()); $pageModule->setPageId($pageRevision->getPageId()); if (ctype_digit($values['module_class'])) { $module = ModuleQuery::create()->findPk($values['module_class']); $pageModule->setModuleClass($module->getModuleClass()); $pageModule->setName($values['name']); $pageModule->setTarget($values['target']); $pageModule->setContentVisibility($module->getContentVisibility()); $pageModule->setSearchVisibility($module->getSearchVisibility()); $template = $module->getTemplate(); } else { $template = null; if ($values['template'] == 'new' && $values['template_name']) { $className = $values['module_class']; $predefinedTemplates = call_user_func(array($className, 'getPredefinedTemplates')); $root = Curry_Core::$config->curry->template->root; $template = $values['template_name']; $templateFile = $root . DIRECTORY_SEPARATOR . $template; if (!file_exists($templateFile)) { $dir = dirname($templateFile); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $code = $predefinedTemplates[$values['predefined_template']]; file_put_contents($templateFile, (string) $code); } } else { if ($values['template']) { $template = $values['template']; } } $target = ''; if (!empty($values['target'])) { $target = $values['target']; } else { if (!empty($values['target_name'])) { $target = $values['target_name']; } } if (empty($target)) { throw new Exception('Module target not set'); } $pageModule = new PageModule(); $pageModule->setUid(Curry_Util::getUniqueId()); $pageModule->setPageId($pageRevision->getPageId()); $pageModule->setModuleClass($values['module_class']); $pageModule->setName($values['name']); $pageModule->setTarget($target); $pageModule->setContentVisibility($values['content_visibility']); $pageModule->setSearchVisibility($values['search_visibility']); } $pageModule->save(); $revisionModule = new RevisionModule(); $revisionModule->setPageModule($pageModule); $revisionModule->setPageRevision($pageRevision); $revisionModule->save(); $moduleData = new ModuleData(); $moduleData->setPageRevision($pageRevision); $moduleData->setPageModule($pageModule); $moduleData->setEnabled(true); $moduleData->setTemplate($template); $moduleData->save(); // create default data $wrapper = new Curry_PageModuleWrapper($pageModule, $pageRevision, null); $wrapper->createData(); return $pageModule; }
/** * Upload file. * @param array $params * @return array */ public function actionUpload($params) { if (!isset($_FILES['file'])) { throw new Exception('No file to upload.'); } $result = array('status' => 1, 'overwrite' => array(), 'uploaded_virtual' => array(), 'uploaded_public' => array()); $virtualPath = $params['path']; if ($params['public'] == 'true') { $virtualPath = self::publicToVirtual($virtualPath); } $targetPath = self::virtualToPhysical($virtualPath); if (!self::isPhysicalWritable($targetPath)) { throw new Exception('Access denied'); } if (is_file($targetPath)) { $virtualPath = dirname($virtualPath); $targetPath = dirname($targetPath); } elseif (is_dir($targetPath)) { $relPath = self::absoluteToRelativePath($targetPath) . '/'; $o = ManagedfileQuery::create()->findOneByFilepath($relPath); if ($o && !$o->isWritable()) { return array('status' => 0, 'error' => 'You do not have write permissions on the directory: ' . $relPath); } } $overwrite = array(); foreach ((array) $_FILES['file']['error'] as $key => $error) { if ($error) { throw new Exception('Upload error: ' . Curry_Util::uploadCodeToMessage($error)); } $name = self::filterFilename($_FILES['file']['name'][$key]); $source = $_FILES['file']['tmp_name'][$key]; $target = $targetPath . '/' . $name; if (file_exists($target)) { $targetHash = sha1_file($target); $sourceHash = sha1_file($source); if ($targetHash !== $sourceHash) { $result['overwrite'][] = $name; $result['status'] = 0; $overwrite[$name] = array('target' => $target, 'temp' => $sourceHash); $target = Curry_Core::$config->curry->tempPath . DIRECTORY_SEPARATOR . $sourceHash; move_uploaded_file($source, $target); continue; } } else { move_uploaded_file($source, $target); } // check whether uploaded file matches a record whose Deleted status is TRUE and change status. ManagedfileQuery::create()->filterByFilepath(self::absoluteToRelativePath($target))->update(array('Deleted' => false)); $result['uploaded_virtual'][] = $virtualPath . '/' . $name; $result['uploaded_public'][] = self::physicalToPublic($target); } $ses = new Zend_Session_Namespace(__CLASS__); $ses->uploadOverwrite = $overwrite; return $result; }
/** * Insert module and return generated content. * * @param Curry_PageModuleWrapper $pageModuleWrapper * @return string */ protected function insertModule(Curry_PageModuleWrapper $pageModuleWrapper) { Curry_Core::log(($pageModuleWrapper->getEnabled() ? 'Inserting' : 'Skipping') . ' module "' . $pageModuleWrapper->getName() . '" of type "' . $pageModuleWrapper->getClassName() . '" with target "' . $pageModuleWrapper->getTarget() . '"'); if (!$pageModuleWrapper->getEnabled()) { return ""; } $cached = false; $devMode = Curry_Core::$config->curry->developmentMode; if ($devMode) { $time = microtime(true); $sqlQueries = Curry_Propel::getQueryCount(); $userTime = Curry_Util::getCpuTime('u'); $systemTime = Curry_Util::getCpuTime('s'); $memoryUsage = memory_get_usage(true); } $this->moduleCache = array(); $module = $pageModuleWrapper->createObject(); $module->setPageGenerator($this); $cp = $module->getCacheProperties(); $cacheName = $this->getModuleCacheName($pageModuleWrapper, $module); // try to use cached content if ($cp !== null && ($cache = Curry_Core::$cache->load($cacheName)) !== false) { $cached = true; $this->insertCachedModule($cache); $content = $cache['content']; } else { $template = null; if ($pageModuleWrapper->getTemplate()) { $template = Curry_Twig_Template::loadTemplate($pageModuleWrapper->getTemplate()); } else { if ($module->getDefaultTemplate()) { $template = Curry_Twig_Template::loadTemplateString($module->getDefaultTemplate()); } } if ($template && $template->getEnvironment()) { $twig = $template->getEnvironment(); $twig->addGlobal('module', array('Id' => $pageModuleWrapper->getPageModuleId(), 'ClassName' => $pageModuleWrapper->getClassName(), 'Name' => $pageModuleWrapper->getName(), 'ModuleDataId' => $pageModuleWrapper->getModuleDataId(), 'Target' => $pageModuleWrapper->getTarget())); } $content = (string) $module->showFront($template); if ($cp !== null) { $this->moduleCache['content'] = $content; $this->saveModuleCache($cacheName, $cp->getLifetime()); } } if ($devMode) { $time = microtime(true) - $time; $userTime = Curry_Util::getCpuTime('u') - $userTime; $systemTime = Curry_Util::getCpuTime('s') - $systemTime; $memoryUsage = memory_get_usage(true) - $memoryUsage; $sqlQueries = $sqlQueries !== null ? Curry_Propel::getQueryCount() - $sqlQueries : null; $cpuLimit = Curry_Core::$config->curry->debug->moduleCpuLimit; $timeLimit = Curry_Core::$config->curry->debug->moduleTimeLimit; $memoryLimit = Curry_Core::$config->curry->debug->moduleMemoryLimit; $sqlLimit = Curry_Core::$config->curry->debug->moduleSqlLimit; if ($userTime + $systemTime > $cpuLimit || $time > $timeLimit) { trace_warning('Module generation time exceeded limit'); } if ($memoryUsage > $memoryLimit) { trace_warning('Module memory usage exceeded limit'); } if ($sqlQueries > $sqlLimit) { trace_warning('Module sql query count exceeded limit'); } // add module debug info $this->moduleDebugInfo[] = array($pageModuleWrapper->getName(), $pageModuleWrapper->getClassName(), $pageModuleWrapper->getTemplate(), $pageModuleWrapper->getTarget(), $cached, round($time * 1000.0), round(($userTime + $systemTime) * 1000.0), Curry_Util::humanReadableBytes($memoryUsage), Curry_Util::humanReadableBytes(memory_get_peak_usage(true)), $sqlQueries !== null ? $sqlQueries : 'n/a'); } return $content; }
/** * Show package grid json. */ public function showJson() { $entries = array(); foreach (Curry_PackageManager::getPackages() as $packageInfo) { $packageInfo = array_shift($packageInfo); $installedPackage = PackageQuery::create()->findPk($packageInfo['name']); $hasUpgrade = $installedPackage ? version_compare($installedPackage->getVersion(), $packageInfo['version']) < 0 : false; $icon = '<img src="shared/images/icons/' . ($hasUpgrade ? 'package_go' : 'package') . '.png" alt="" title="' . ($hasUpgrade ? 'You can upgrade this package' : 'This package is up to date') . '" /> '; $entries[] = array('id' => $packageInfo['name'], 'cell' => array($icon, $packageInfo['name'], $installedPackage ? $installedPackage->getVersion() : 'Not installed', $packageInfo['version'], isset($packageInfo['filesize']) ? Curry_Util::humanReadableBytes($packageInfo['filesize']) : 'n/a', $packageInfo['summary'])); } $this->returnJson(array('page' => 1, 'total' => count($entries), 'rows' => $entries)); }
/** * Get the twig environment used with the backend. * * @return Twig_Environment */ public function getTwig() { if (!$this->twig) { $path = Curry_Util::path('shared', 'backend'); $backendPath = Curry_Util::path(true, Curry_Core::$config->curry->wwwPath, $path); if (!$backendPath) { $backendPath = Curry_Util::path(true, Curry_Core::$config->curry->basePath, $path); } if (!$backendPath) { throw new Exception('Backend path (shared/backend) not found.'); } $templatePaths = array(Curry_Util::path($backendPath, Curry_Core::$config->curry->backend->theme, 'templates'), Curry_Util::path($backendPath, 'common', 'templates')); $templatePaths = array_filter($templatePaths, 'is_dir'); $options = array('debug' => true, 'trim_blocks' => true, 'base_template_class' => 'Curry_Twig_Template'); $loader = new Twig_Loader_Filesystem($templatePaths); $twig = new Twig_Environment($loader, $options); $twig->addFunction('url', new Twig_Function_Function('url')); $twig->addFunction('L', new Twig_Function_Function('L')); $twig->addFilter('rewrite', new Twig_Filter_Function('Curry_String::getRewriteString')); $twig->addFilter('attr', new Twig_Filter_Function('Curry_Html::createAttributes')); $this->twig = $twig; } return $this->twig; }