Exemple #1
0
 public static function addLanguageForm(Curry_Backend $backend, $user = null)
 {
     if (!$user) {
         $user = User::getUser();
     }
     $languages = LanguageQuery::create()->useUserLanguageQuery()->filterByUser($user)->endUse()->find()->toKeyValue('Langcode', 'Name');
     if (!count($languages)) {
         throw new Exception('You do not have access to any languages.');
     }
     $langcode = null;
     if (isset($_GET['langcode'])) {
         $langcode = $_GET['langcode'];
     }
     if (!array_key_exists($langcode, $languages)) {
         $langcode = null;
     }
     if ($langcode === null) {
         $langcode = array_keys($languages);
         $langcode = array_shift($langcode);
     }
     if (empty($_GET['action'])) {
         header('cache-control: no-store');
         // dont store state as this may cause problem with the form below
         $backend->addMainContent(self::getLanguageForm($languages, $langcode));
     }
     return $langcode;
 }
Exemple #2
0
 public function render(Curry_Backend $backend, array $params)
 {
     $item = $this->getSelection($params);
     if (!isset($item)) {
         throw new Exception('No item to delete');
     }
     $name = method_exists($item, '__toString') ? '`' . htmlspecialchars((string) $item) . '`' : 'this item';
     if (isPost() && $_POST['do_delete']) {
         $pk = $item->getPrimaryKey();
         $item->delete();
         // Trigger update event
         $backend->createModelUpdateEvent($this->modelClass, $pk, 'update');
         if ($item instanceof Curry_ISearchable) {
             Curry_Backend_Indexer::removeItem($item);
         }
         $backend->addMainContent('<p>' . $name . ' has been deleted.</p>');
     } else {
         $backend->addMainContent('<form method="post" action="' . url('', $params) . '">' . '<input type="hidden" name="do_delete" value="1" />' . '<p>Do you really want to delete ' . $name . '?</p>' . '<button type="submit" class="btn btn-danger">Delete</button>' . '</form>');
     }
 }
Exemple #3
0
 public function render(Curry_Backend $backend, array $params)
 {
     $modelClass = $this->modelForm->getModelClass();
     $item = $this->getSelection($params);
     if (!isset($item)) {
         $item = new $modelClass();
         $relatedItem = $this->getParentSelection($params);
         if ($relatedItem) {
             $relations = PropelQuery::from($modelClass)->getTableMap()->getRelations();
             foreach ($relations as $relation) {
                 if ($relation->getRightTable()->getPhpName() == get_class($relatedItem) && in_array($relation->getType(), array(RelationMap::MANY_TO_ONE))) {
                     $item->{'set' . $relation->getName()}($relatedItem);
                 }
             }
         }
     }
     $form = clone $this->modelForm;
     $form->setOptions(array('method' => 'post', 'action' => (string) url('', $params)));
     $buttons = array('save');
     $form->addElement('submit', 'save', array('label' => 'Save'));
     if (!$item->isNew() && $this->parentView instanceof Curry_ModelView_List && $this->parentView->hasAction('delete')) {
         $form->addElement('submit', 'delete', array('label' => 'Delete', 'class' => 'btn btn-danger', 'onclick' => "return confirm('Do you really want to delete this item? This cannot be undone.');"));
         $buttons[] = 'delete';
     }
     $form->addDisplayGroup($buttons, 'save_group', array('class' => 'horizontal-group'));
     $form->fillForm($item);
     if (isPost() && $form->isValid($_POST)) {
         if ($form->delete && $form->delete->isChecked()) {
             $backend->createModelUpdateEvent($modelClass, $item->getPrimaryKey(), 'delete');
             $item->delete();
             if ($item instanceof Curry_ISearchable) {
                 Curry_Backend_Indexer::removeItem($item);
             }
             $backend->addMainContent('<p>The item has been deleted.</p>');
             return;
         }
         $form->fillModel($item);
         $this->triggerCallback($this->preSave, $item, $form);
         $item->save();
         $this->triggerCallback($this->postSave, $item, $form);
         $form->fillForm($item);
         $backend->createModelUpdateEvent($modelClass, $item->getPrimaryKey(), 'update');
         if ($item instanceof Curry_ISearchable) {
             Curry_Backend_Indexer::updateItem($item);
         }
         if (isAjax()) {
             return '';
         }
     }
     $this->triggerCallback($this->preRender, $item, $form);
     $backend->addMainContent($form);
 }
Exemple #4
0
 /**
  * Constructor.
  */
 public function __construct()
 {
     parent::__construct();
     // Override and increase max execution time if set
     $timeLimit = ini_get('max_execution_time');
     if ($timeLimit && $timeLimit < 250) {
         @set_time_limit(250);
     }
     Propel::disableInstancePooling();
     Propel::setLogger(null);
     // make sure all classes are included
     foreach (Curry_Propel::getModels() as $classes) {
         foreach ($classes as $clazz) {
             class_exists($clazz . 'Peer', true);
         }
     }
 }
Exemple #5
0
 /**
  * Create an automatic backup of the database.
  */
 public function doAutoBackup()
 {
     $autoBackup = Curry_Core::$config->curry->autoBackup;
     if ($autoBackup) {
         $filename = Curry_Backend_DatabaseHelper::createBackupName("backup_%Y-%m-%d_%H-%M-%S_autobackup.txt");
         $lastModified = 0;
         foreach (new DirectoryIterator(dirname($filename)) as $entry) {
             if ($entry->isFile()) {
                 $lastModified = max($lastModified, $entry->getMTime());
             }
         }
         if (time() - $lastModified >= $autoBackup && !file_exists($filename)) {
             $status = Curry_Backend_DatabaseHelper::dumpDatabase($filename);
             if ($this->backend) {
                 if ($status) {
                     $this->backend->addMessage('An automatic backup of the database has been created successfully.', Curry_Backend::MSG_SUCCESS);
                 } else {
                     $this->backend->addMessage('There was an error when trying to create the automatic backup of the database.', Curry_Backend::MSG_ERROR);
                 }
             }
         }
     }
 }
Exemple #6
0
 public function showRoles()
 {
     if (!$this->hasPermission(self::PERMISSION_ROLES)) {
         throw new Exception('You dont have permission to access this view.');
     }
     $this->addMenu();
     $user = User::getUser();
     $backendModules = Curry_Backend::getBackendList();
     $disable = array();
     $backend = array("*" => "All");
     if (!$user->hasAccess('*')) {
         $disable[] = '*';
     }
     foreach ($backendModules as $backendClass => $backendName) {
         $backend[$backendClass] = $backendName;
         $permissions = method_exists($backendClass, 'getPermissions') ? call_user_func(array($backendClass, 'getPermissions')) : array();
         foreach ($permissions as $permission) {
             $backend[$backendClass . "/" . $permission] = Curry_Core::SELECT_TREE_PREFIX . $permission;
             if (!$user->hasAccess($backendClass . "/" . $permission)) {
                 $disable[] = $backendClass . "/" . $permission;
             }
         }
         if (!$user->hasAccess($backendClass)) {
             $disable[] = $backendClass;
         }
     }
     $content = array();
     $contentAccess = array("*" => "All") + Curry_Module::getModuleList();
     $allContentAccess = $user->hasAccess('Curry_Backend_Content/*');
     foreach ($contentAccess as $k => $v) {
         $content['Curry_Backend_Content/' . $k] = $v;
         if (!$allContentAccess && !$user->hasAccess('Curry_Backend_Content/' . $k)) {
             $disable[] = 'Curry_Backend_Content/' . $k;
         }
     }
     $form = new Curry_ModelView_Form('UserRole', array('elements' => array('backend' => array('multiselect', array('label' => 'Backend access', 'multiOptions' => $backend, 'size' => 10, 'order' => 1, 'disable' => $disable, 'validators' => array(array('InArray', true, array(array_diff(array_keys($backend), $disable)))))), 'content' => array('multiselect', array('label' => 'Content access', 'multiOptions' => $content, 'size' => 10, 'order' => 2, 'disable' => $disable, 'validators' => array(array('InArray', true, array(array_diff(array_keys($content), $disable))))))), 'onFillForm' => function (UserRole $role, $form) {
         $access = UserRoleAccessQuery::create()->filterByUserRole($role)->select('Module')->find()->getArrayCopy();
         $form->backend->setValue($access);
         $form->content->setValue($access);
     }, 'onFillModel' => function (UserRole $role, $form, $values) {
         $access = array_merge((array) $values['backend'], (array) $values['content']);
         $collection = new PropelObjectCollection();
         $collection->setModel('UserRoleAccess');
         foreach ($access as $a) {
             $ura = new UserRoleAccess();
             $ura->setModule($a);
             $collection->append($ura);
         }
         $role->setUserRoleAccesss($collection);
     }));
     $q = UserRoleQuery::create();
     $list = new Curry_ModelView_List($q, array('modelForm' => $form));
     $list->addAction('file_permissions', array('action' => $this->getFileAccessList(), 'class' => 'inline', 'single' => true));
     $list->show($this);
 }
Exemple #7
0
 /**
  * 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;
 }
Exemple #8
0
 /**
  * Execute actions.
  */
 public function preShow()
 {
     parent::preShow();
     Page::setRevisionType(Page::WORKING_REVISION);
 }
Exemple #9
0
 public function render(Curry_Backend $backend, array $params)
 {
     $backend->addMainContent($this->getHtml($params));
 }
 public function __construct()
 {
     parent::__construct();
     $this->renderMenu();
 }
Exemple #11
0
 /**
  * Constructor
  */
 public function __construct()
 {
     parent::__construct();
     $this->rootPath = Curry_Core::$config->curry->wwwPath . DIRECTORY_SEPARATOR;
 }
Exemple #12
0
 /**
  * Restore database from file.
  * 
  * @todo Fix $maxExecutionTime.
  *
  * @param string|resource $file
  * @param array|null $tables
  * @param float $maxExecutionTime
  * @param int $continueLine
  * @param Curry_Backend|null $backend 
  * @return bool	True on success, false otherwise.
  */
 public static function restoreFromFile($file, $tables = null, $maxExecutionTime = 0, $continueLine = 0, Curry_Backend $backend = null)
 {
     global $CURRY_DATABASE_RESTORE;
     $CURRY_DATABASE_RESTORE = true;
     $fp = is_string($file) ? fopen($file, "r") : $file;
     $t = microtime(true);
     $total = 0;
     $skipped = 0;
     $failed = 0;
     $session = new Zend_Session_Namespace(__CLASS__);
     $con = Propel::getConnection();
     $con->beginTransaction();
     $adapter = Propel::getDB();
     if ($adapter instanceof DBMySQL) {
         $con->exec("SET foreign_key_checks = 0");
     }
     // Read header
     $firstline = stream_get_line($fp, self::MAX_LINE_LENGTH, "\n");
     $header = json_decode($firstline, true);
     if (is_array($header) && isset($header['header'])) {
         $header = $header['header'];
         // Check header version
         $version = isset($header['version']) ? (int) $header['version'] : 0;
         if ($version > self::VERSION) {
             throw new Exception('Unsupported database version. The file you are trying to restore from is from a newer version of currycms.');
         }
         // Check page version
         $pageVersion = isset($header['page-version']) ? (int) $header['page-version'] : 0;
         if ($pageVersion > Page::VERSION) {
             throw new Exception('Unsupported page version. The file you are trying to restore from is from a newer version of currycms.');
         }
         if ($backend) {
             $backend->addMessage("Restoring from " . $header['date']);
         }
         if ($pageVersion !== Page::VERSION) {
             if ($backend) {
                 $backend->addMessage("Migrating data from version {$pageVersion} to " . Page::VERSION, Curry_Backend::MSG_WARNING);
             }
             Page::preMigrate($pageVersion);
         }
     } else {
         throw new Exception('Invalid header');
     }
     // Empty tables
     if ($continueLine == 0) {
         foreach (Curry_Propel::getModels() as $classes) {
             foreach ($classes as $table) {
                 try {
                     if (is_array($tables) && !in_array($table, $tables)) {
                         continue;
                     }
                     if (!method_exists($table, 'delete')) {
                         if ($backend) {
                             $backend->addMessage("Skipping read-only table: {$table}", Curry_Backend::MSG_WARNING);
                         }
                         continue;
                     }
                     $tableName = PropelQuery::from($table)->getTableMap()->getName();
                     // use basePeer to avoid foreign key emulation in Normal peer class
                     BasePeer::doDeleteAll($tableName, $con);
                 } catch (Exception $e) {
                     throw new Exception('Unable to empty table ' . $table . ': ' . $e->getMessage());
                 }
             }
         }
         if ($backend) {
             $backend->addMessage("Cleared tables in " . round(microtime(true) - $t, 2) . "s");
         }
         $t = microtime(true);
     } else {
         $total = $session->total;
         $skipped = $session->skipped;
         $failed = $session->failed;
         if ($backend) {
             $backend->addMessage("Continuing from line {$continueLine}.");
         }
         for ($i = 0; $i < $continueLine; ++$i) {
             stream_get_line($fp, self::MAX_LINE_LENGTH, "\n");
         }
     }
     $currentTable = null;
     $buffer = array();
     while (!feof($fp)) {
         // Read line
         $data = json_decode(stream_get_line($fp, self::MAX_LINE_LENGTH, "\n"), true);
         ++$total;
         if (is_array($data) && isset($data['table'])) {
             if (is_array($tables) && !in_array($data['table'], $tables) || !method_exists($data['table'], 'delete')) {
                 ++$skipped;
                 continue;
             }
             // Verify columns for new table
             if ($data['table'] !== $currentTable && $currentTable !== null && $backend) {
                 $backend->addMessage('Restoring rows for table ' . $data['table']);
                 $columns = Curry_Array::objectsToArray(PropelQuery::from($data['table'])->getTableMap()->getColumns(), null, 'getPhpName');
                 $added = array_diff($columns, array_keys($data['values']));
                 $removed = array_diff(array_keys($data['values']), $columns);
                 if (count($added)) {
                     $backend->addMessage('New column(s): ' . join(', ', $added), Curry_Backend::MSG_WARNING);
                 }
                 if (count($removed)) {
                     $backend->addMessage('Removed column(s): ' . join(', ', $removed), Curry_Backend::MSG_WARNING);
                 }
             }
             // Flush buffer when changing tables
             if ($data['table'] !== $currentTable || count($buffer) >= self::MULTIINSERT_MAXBUFFER) {
                 if ($currentTable !== null && count($buffer)) {
                     Curry_Propel::doMultiInsert($currentTable, $buffer);
                 }
                 $currentTable = $data['table'];
                 $buffer = array();
             }
             // Migrate data
             if ($pageVersion !== Page::VERSION) {
                 if (!Page::migrateData($data['table'], $data['values'], $pageVersion)) {
                     continue;
                 }
             }
             $buffer[] = $data['values'];
         } else {
             if ($backend) {
                 $backend->addMessage('Unable to read data on line ' . $total, Curry_Backend::MSG_ERROR);
             }
             ++$failed;
         }
         // check execution time
         if ($maxExecutionTime && Curry_Core::getExecutionTime() > $maxExecutionTime) {
             if ($currentTable !== null && count($buffer)) {
                 Curry_Propel::doMultiInsert($currentTable, $buffer);
             }
             $session->total = $total;
             $session->skipped = $skipped;
             $session->failed = $failed;
             $params = array('module' => 'Curry_Backend_Database', 'view' => 'ContinueRestore', 'file' => $file, 'tables' => $tables, 'line' => $total, 'max_execution_time' => $maxExecutionTime);
             url('', $params)->redirect(302, true);
         }
     }
     // Flush buffer
     if ($currentTable !== null && count($buffer)) {
         Curry_Propel::doMultiInsert($currentTable, $buffer);
     }
     if ($pageVersion !== Page::VERSION) {
         Page::postMigrate($pageVersion);
     }
     if ($adapter instanceof DBMySQL) {
         $con->exec("SET foreign_key_checks = 1");
     }
     $con->commit();
     $CURRY_DATABASE_RESTORE = false;
     if ($backend) {
         if ($skipped) {
             $backend->addMessage("Skipped {$skipped} rows");
         }
         if ($failed) {
             $backend->addMessage("Failed to add {$failed} rows", Curry_Backend::MSG_ERROR);
         }
         $backend->addMessage("Added " . ($total - $skipped - $failed) . " / {$total} rows in " . round(microtime(true) - $t, 2) . "s", !$failed ? Curry_Backend::MSG_SUCCESS : Curry_Backend::MSG_ERROR);
     }
     if (is_string($file)) {
         fclose($fp);
     }
     return !$failed;
 }