Ejemplo n.º 1
0
 /**
  * DOCUMENT ME
  * @param mixed $arguments
  * @param mixed $options
  */
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     // PDO connection not so useful, get the doctrine one
     $conn = Doctrine_Manager::connection();
     if ($options['table'] === 'aPage') {
         $q = Doctrine::getTable('aLuceneUpdate')->createQuery('u');
     } else {
         $q = Doctrine::getTable($options['table'])->createQuery('o')->where('o.lucene_dirty IS TRUE');
     }
     if ($options['limit'] !== false) {
         $q->limit($options['limit'] + 0);
     }
     $updates = $q->execute();
     $i = 0;
     foreach ($updates as $update) {
         $i++;
         if ($options['table'] === 'aPage') {
             $page = aPageTable::retrieveByIdWithSlots($update->page_id, $update->culture);
             // Careful, pages die
             if ($page) {
                 $page->updateLuceneIndex();
             }
             $update->delete();
         } else {
             // The actual object
             $update->updateLuceneIndex();
             $update->lucene_dirty = false;
             $update->save();
         }
     }
 }
Ejemplo n.º 2
0
 protected function execute($arguments = array(), $options = array())
 {
     // We need a proper environment. This also gives us superadmin privileges
     aTaskTools::signinAsTaskUser($this->createConfiguration($options['application'], $options['env']), $options['connection']);
     aTaskTools::setCliHost();
     // Get all of the current pages with their slots. For efficiency this normally does not return slots
     // that are not the current version
     if ($options['allversions']) {
         // All versions case is a simpler query since we want to look at every slot
         $slots = Doctrine::getTable('aSlot')->findAll();
         foreach ($slots as $slot) {
             $slot->refreshSlot();
         }
     } else {
         // All cultures
         $pages = aPageTable::queryWithSlots(false, 'all')->execute();
         foreach ($pages as $page) {
             foreach ($page->Areas as $area) {
                 foreach ($area->AreaVersions as $areaVersion) {
                     foreach ($areaVersion->AreaVersionSlots as $areaVersionSlot) {
                         $areaVersionSlot->Slot->refreshSlot();
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 3
0
 public static function preExecute($actions)
 {
     $request = $actions->getRequest();
     // Figure out where we are all over again, because there seems to be no clean way
     // to get the same controller-free URL that the routing engine gets. TODO:
     // ask Fabien how we can do that.
     $uri = $actions->getRequest()->getUri();
     $uriPrefix = $actions->getRequest()->getUriPrefix();
     $uri = substr($uri, strlen($uriPrefix));
     if (preg_match("/^\\/[^\\/]+\\.php(.*)\$/", $uri, $matches)) {
         $uri = $matches[1];
     }
     // This will quickly fetch a result that was already cached when we
     // ran through the routing table (unless we hit the routing table cache,
     // in which case we're looking it up for the first time, also OK)
     $page = aPageTable::getMatchingEnginePage($uri, $remainder);
     if (!$page) {
         throw new sfException('Attempt to access engine action without a page');
     }
     $page = aPageTable::retrieveByIdWithSlots($page->id);
     // We want to do these things the same way executeShow would
     aTools::validatePageAccess($actions, $page);
     aTools::setPageEnvironment($actions, $page);
     // Convenient access to the current page for the subclass
     $actions->page = $page;
 }
 public function executeIndex(sfWebRequest $request)
 {
     if (!aPageTable::getFirstEnginePage('aBlog')) {
         $this->setTemplate('engineWarning');
     }
     parent::executeIndex($request);
     aBlogItemTable::populatePages($this->pager->getResults());
 }
Ejemplo n.º 5
0
 public static function getGlobalButtons()
 {
     $mediaEnginePage = aPageTable::retrieveBySlug('/admin/media');
     // Only if we have suitable credentials
     $user = sfContext::getInstance()->getUser();
     if ($user->hasCredential('media_admin') || $user->hasCredential('media_upload')) {
         aTools::addGlobalButtons(array(new aGlobalButton('media', 'Media', 'aMedia/index', 'a-media', $mediaEnginePage)));
     }
 }
 public function navSetup()
 {
     $this->root = isset($this->root) ? $this->root : '/';
     $this->rootPage = aPageTable::retrieveBySlug($this->root);
     $this->active = !empty($this->active) ? $this->active : $this->root;
     $this->activePage = aPageTable::retrieveBySlug($this->active);
     $this->dragIcon = isset($this->dragIcon) ? $this->dragIcon : false;
     $this->draggable = isset($this->draggable) ? $this->rootPage->userHasPrivilege('edit') : false;
     $this->class = isset($this->class) ? $this->class : 'a-nav-item';
 }
 public function executeTabs()
 {
     $page = aPageTable::retrieveBySlug($this->root);
     $this->root = isset($this->root) ? $this->root : '/';
     $this->active = isset($this->active) ? $this->active : $this->root;
     $this->options = array('depth' => isset($this->depth) ? $this->depth : 1);
     $this->depth = $this->options['depth'];
     $this->draggable = isset($this->draggable) ? $page->userHasPrivilege('edit') : false;
     $this->dragIcon = isset($this->dragIcon) ? $this->dragIcon : false;
     $this->navigation = new aNavigationTabs($this->root, $this->active, $this->options);
     $this->nav = $this->navigation->getNav();
 }
Ejemplo n.º 8
0
 /**
  * Poor man's multiple inheritance. This allows us to subclass an existing
  * actions class in order to create an engine version of it. See aEngineActions
  * for the call to add to your own preExecute method
  * @param mixed $actions
  */
 public static function preExecute($actions)
 {
     $request = $actions->getRequest();
     // Figure out where we are all over again, because there seems to be no clean way
     // to get the same controller-free URL that the routing engine gets. TODO:
     // ask Fabien how we can do that.
     $uri = urldecode($actions->getRequest()->getUri());
     $rr = preg_quote(sfContext::getInstance()->getRequest()->getRelativeUrlRoot(), '/');
     if (preg_match("/^(?:https?:\\/\\/[^\\/]+)?{$rr}(?:\\/[^\\/]+\\.php)?(.*)\$/", $uri, $matches)) {
         $uri = $matches[1];
     } else {
         throw new sfException("Unable to parse engine URL {$uri}");
     }
     // This will quickly fetch a result that was already cached when we
     // ran through the routing table (unless we hit the routing table cache,
     // in which case we're looking it up for the first time, also OK)
     $page = aPageTable::getMatchingEnginePageInfo($uri, $remainder);
     if (!$page) {
         throw new sfException('Attempt to access engine action without a page');
     }
     $page = aPageTable::retrieveByIdWithSlots($page['id']);
     // We want to do these things the same way executeShow would
     aTools::validatePageAccess($actions, $page);
     aTools::setPageEnvironment($actions, $page);
     // Convenient access to the current page for the subclass
     $actions->page = $page;
     // If your engine supports allowing the user to choose from several page types
     // to distinguish different ways of using your engine, then you'll need to
     // return the template name from your show and index actions (and perhaps
     // others as appropriate). You can pull that information straight from
     // $this->page->template, or you can take advantage of $this->pageTemplate which
     // is ready to return as the result of an action (default has been changed
     // to Success, other values have their first letter capitalized)
     $templates = aTools::getTemplates();
     // originalTemplate is what's in the template field of the page, except that
     // nulls and empty strings from pre-1.5 Apostrophe have been converted to 'default'
     // for consistency
     $actions->originalTemplate = $page->template;
     if (!strlen($actions->originalTemplate)) {
         // Compatibility with 1.4 templates and reasonable Symfony expectations
         $actions->originalTemplate = 'default';
     }
     // pageTemplate is suitable to return from an action. 'default' becomes 'Success'
     // (the Symfony standard for a "normal" template's suffix) and other values have
     // their first letter capitalized
     if ($actions->originalTemplate === 'default') {
         $actions->pageTemplate = 'Success';
     } else {
         $actions->pageTemplate = ucfirst($actions->originalTemplate);
     }
 }
Ejemplo n.º 9
0
 public function initializeTree()
 {
     if (!isset(self::$tree)) {
         $root = aPageTable::retrieveBySlugWithTitles('/');
         $rootInfo['id'] = $root['id'];
         $rootInfo['lft'] = $root['lft'];
         $rootInfo['rgt'] = $root['rgt'];
         $rootInfo['title'] = $root['title'];
         $rootInfo['slug'] = $root['slug'];
         $tree = $root->getTreeInfo(false);
         $rootInfo['children'] = $tree;
         self::$tree = array($rootInfo);
         self::createHashTable(self::$tree, $rootInfo);
     }
 }
Ejemplo n.º 10
0
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     // PDO connection not so useful, get the doctrine one
     $conn = Doctrine_Manager::connection();
     $updates = $conn->getTable("aLuceneUpdate")->findAll();
     foreach ($updates as $update) {
         $page = aPageTable::retrieveByIdWithSlots($update->page_id, $update->culture);
         // Careful, pages die
         if ($page) {
             $page->updateLuceneIndex();
         }
         $update->delete();
     }
 }
Ejemplo n.º 11
0
 /**
  * DOCUMENT ME
  */
 public function navSetup()
 {
     if (is_object($this->root) && $this->root instanceof aPage) {
         $this->rootPage = $this->root;
     } else {
         $this->root = isset($this->root) ? $this->root : '/';
         $this->rootPage = aPageTable::retrieveBySlug($this->root);
     }
     if (is_object($this->active) && $this->active instanceof aPage) {
         $this->activePage = $this->active;
         $this->active = $this->active->slug;
     } else {
         $this->active = !empty($this->active) ? $this->active : $this->root;
         $this->activePage = aPageTable::retrieveBySlug($this->active);
     }
     $this->dragIcon = isset($this->dragIcon) ? $this->dragIcon : false;
     $this->draggable = isset($this->draggable) ? $this->rootPage->userHasPrivilege('edit') : false;
     $this->class = isset($this->class) ? $this->class : 'a-nav-item';
 }
Ejemplo n.º 12
0
<div class="a-no-items">
<?php 
// We need to retrieve the page if we are not at /admin/error404
$page = aPageTable::retrieveBySlug('/admin/error-a-media');
?>
	
<?php 
$page ? $slots = $page->getArea('body') : ($slots = array());
?>

<?php 
// If there are no slots, show some default text
if (!count($slots)) {
    ?>
	<h3>
		<?php 
    echo a_('Oops! You don\'t have anything in your media library.');
    ?>
<br/>
		<?php 
    echo a_('Do you want to <a href="#upload-images" class="a-add-media-toggle">add some media?</a>');
    ?>
	</h3>
<?php 
}
?>

<?php 
// Only display this area if there is content in it OR if the user is logged-in & admin.
// Note: The sandbox pages.yml fixtures pre-populate an 'en' RichText slot with the media message.
if (count($slots) || $sf_user->hasCredential('admin')) {
Ejemplo n.º 13
0
 public static function globalSetup($options)
 {
     if (isset($options['global']) && $options['global']) {
         if (!isset($options['slug'])) {
             $options['slug'] = 'global';
         }
     }
     if (isset($options['slug'])) {
         $page = self::getCurrentPage();
         if ($page) {
             if ($page->slug === $options['slug']) {
                 // Nothing to do. This can happen if, for instance, a template used on all pages
                 // including the chemistry home page fetches a footer from the chemistry home page
                 return;
             }
         }
         $slug = $options['slug'];
         self::$savedCurrentPage = self::getCurrentPage();
         // Caching the global page speeds up pages with two or more global slots
         if (isset(self::$globalCache[$slug])) {
             $global = self::$globalCache[$slug];
         } else {
             $global = aPageTable::retrieveBySlugWithSlots($slug);
             if (!$global) {
                 $global = new aPage();
                 $global->slug = $slug;
                 $global->save();
             }
             self::$globalCache[$slug] = $global;
         }
         self::setCurrentPage($global);
         self::$global = true;
     }
 }
Ejemplo n.º 14
0
 public static function treeSlotOn($slot)
 {
     $query = aPageTable::queryWithSlot($slot);
     self::$treeObject = Doctrine::getTable('aPage')->getTree();
     // I'm not crazy about how I have to set the base query and then
     // reset it, instead of simply passing it to getChildren. A
     // Doctrine oddity
     self::$treeObject->setBaseQuery($query);
 }
Ejemplo n.º 15
0
 /**
  * DOCUMENT ME
  * @param mixed $arguments
  * @param mixed $options
  */
 protected function execute($arguments = array(), $options = array())
 {
     // We need a basic context so we can notify events
     $context = sfContext::createInstance($this->configuration);
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     $postTasks = array();
     echo "\nApostrophe Database Migration Task\n  \nThis task will make any necessary database schema changes to bring your \nMySQL database up to date with the current release of Apostrophe and any additional\nApostrophe plugins that you have installed. For other databases see the source code \nor run './symfony doctrine:build-sql' to obtain the SQL commands you may need.\n  \nBACK UP YOUR DATABASE BEFORE YOU RUN THIS TASK. It works fine in our tests, \nbut why take chances with your data?\n\n";
     if (!$options['force']) {
         if (!$this->askConfirmation("Are you sure you are ready to migrate your project? [y/N]", 'QUESTION_LARGE', false)) {
             die("Operation CANCELLED. No changes made.\n");
         }
     }
     $this->migrate = new aMigrate(Doctrine_Manager::connection()->getDbh());
     // If I needed to I could look for the constraint definition like this.
     // But since we added these in the same migration I don't have to. Keep this
     // comment around as sooner or later we'll probably need to check for this
     // kind of thing
     //
     // $createTable = $data[0]['Create Table'];
     // if (!preg_match('/CONSTRAINT `a_redirect_page_id_a_page_id`/', $createTable))
     // {
     //
     // }
     if (!$this->migrate->tableExists('a_redirect')) {
         $this->migrate->sql(array("CREATE TABLE IF NOT EXISTS a_redirect (id INT AUTO_INCREMENT, page_id INT, slug VARCHAR(255) UNIQUE, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, INDEX slugindex_idx (slug), INDEX page_id_idx (page_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB;", "ALTER TABLE a_redirect ADD CONSTRAINT a_redirect_page_id_a_page_id FOREIGN KEY (page_id) REFERENCES a_page(id) ON DELETE CASCADE;"));
     }
     if (!$this->migrate->columnExists('a_media_item', 'lucene_dirty')) {
         $this->migrate->sql(array("ALTER TABLE a_media_item ADD COLUMN lucene_dirty BOOLEAN DEFAULT false;"));
     }
     if (!$this->migrate->getCommandsRun()) {
         echo "Your database is already up to date.\n\n";
     } else {
         echo $this->migrate->getCommandsRun() . " SQL commands were run.\n\n";
     }
     if (!$this->migrate->tableExists('a_group_access')) {
         // They don't have a group access table yet. In theory, they don't have an editor permission
         // to grant to groups yet either. However that is a likely name for them to invent on their
         // own, so make sure we don't panic if there is already a permission called eidtor
         $this->migrate->sql(array('CREATE TABLE a_group_access (id BIGINT AUTO_INCREMENT, page_id INT, privilege VARCHAR(100), group_id INT, INDEX pageindex_idx (page_id), INDEX group_id_idx (group_id), PRIMARY KEY(id)) ENGINE = INNODB;', 'ALTER TABLE a_group_access ADD CONSTRAINT a_group_access_page_id_a_page_id FOREIGN KEY (page_id) REFERENCES a_page(id) ON DELETE CASCADE;', 'ALTER TABLE a_group_access ADD CONSTRAINT a_group_access_group_id_sf_guard_group_id FOREIGN KEY (group_id) REFERENCES sf_guard_group(id) ON DELETE CASCADE;', 'INSERT INTO sf_guard_permission (name, description) VALUES ("editor", "For groups that will be granted editing privileges at some point in the site") ON DUPLICATE KEY UPDATE id = id;'));
     }
     $viewLocked = sfConfig::get('app_a_view_locked_sufficient_credentials', 'view_locked');
     // If they haven't customized it make sure it exists. Some pkContextCMS sites might not have it
     if ($viewLocked === 'view_locked') {
         $permission = Doctrine::getTable('sfGuardPermission')->findOneByName($viewLocked);
         if (!$permission) {
             $permission = new sfGuardPermission();
             $permission->setName('view_locked');
             $permission->save();
             $groups = array('editor', 'admin');
             foreach ($groups as $group) {
                 $g = Doctrine::getTable('sfGuardGroup')->findOneByName($group);
                 if ($g) {
                     $pg = new sfGuardGroupPermission();
                     $pg->setGroupId($g->id);
                     $pg->setPermissionId($permission->id);
                     $pg->save();
                 }
             }
         }
     }
     if (!$this->migrate->tableExists('a_category') || !$this->migrate->tableExists('a_category_group')) {
         $this->migrate->sql(array("CREATE TABLE IF NOT EXISTS a_category (id INT AUTO_INCREMENT, name VARCHAR(255) UNIQUE, description TEXT, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, slug VARCHAR(255), UNIQUE INDEX a_category_sluggable_idx (slug), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB;", "CREATE TABLE IF NOT EXISTS a_category_group (category_id INT, group_id INT, PRIMARY KEY(category_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB;", "CREATE TABLE IF NOT EXISTS a_category_user (category_id INT, user_id INT, PRIMARY KEY(category_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB;", "CREATE TABLE `a_page_to_category` (\n          `page_id` INT NOT NULL DEFAULT '0',\n          `category_id` INT NOT NULL DEFAULT '0',\n          PRIMARY KEY (`page_id`,`category_id`),\n          KEY `a_page_to_category_category_id_a_category_id` (`category_id`),\n          CONSTRAINT `a_page_to_category_category_id_a_category_id` FOREIGN KEY (`category_id`) REFERENCES `a_category` (`id`) ON DELETE CASCADE,\n          CONSTRAINT `a_page_to_category_page_id_a_page_id` FOREIGN KEY (`page_id`) REFERENCES `a_page` (`id`) ON DELETE CASCADE\n        ) ENGINE=InnoDB DEFAULT CHARSET=utf8", "CREATE TABLE IF NOT EXISTS `a_media_item_to_category` (\n          `media_item_id` INT NOT NULL DEFAULT '0',\n          `category_id` INT NOT NULL DEFAULT '0',\n          PRIMARY KEY (`media_item_id`,`category_id`),\n          KEY `a_media_item_to_category_category_id_a_category_id` (`category_id`)\n        ) ENGINE=InnoDB DEFAULT CHARSET=utf8"));
         // These constraints might already be present, be tolerant
         $constraints = array("ALTER TABLE a_media_item_to_category ADD CONSTRAINT `a_media_item_to_category_category_id_a_category_id` FOREIGN KEY (`category_id`) REFERENCES `a_category` (`id`) ON DELETE CASCADE", "ALTER TABLE a_media_item_to_category ADD CONSTRAINT `a_media_item_to_category_media_item_id_a_media_item_id` FOREIGN KEY (`media_item_id`) REFERENCES `a_media_item` (`id`) ON DELETE CASCADE", "ALTER TABLE a_category_group ADD CONSTRAINT a_category_group_group_id_sf_guard_group_id FOREIGN KEY (group_id) REFERENCES sf_guard_group(id) ON DELETE CASCADE;", "ALTER TABLE a_category_group ADD CONSTRAINT a_category_group_category_id_a_category_id FOREIGN KEY (category_id) REFERENCES a_category(id) ON DELETE CASCADE;", "ALTER TABLE a_category_user ADD CONSTRAINT a_category_user_user_id_sf_guard_user_id FOREIGN KEY (user_id) REFERENCES sf_guard_user(id) ON DELETE CASCADE;", "ALTER TABLE a_category_user ADD CONSTRAINT a_category_user_category_id_a_category_id FOREIGN KEY (category_id) REFERENCES a_category(id) ON DELETE CASCADE;");
         foreach ($constraints as $c) {
             try {
                 $this->migrate->sql(array($c));
             } catch (Exception $e) {
                 echo "Error creating constraint, most likely already exists, which is OK {$c}\n";
             }
         }
         if ($this->migrate->tableExists('a_media_category')) {
             $oldCategories = $this->migrate->query('SELECT * FROM a_media_category');
         } else {
             $oldCategories = array();
         }
         $newCategories = $this->migrate->query('SELECT * FROM a_category');
         $nc = array();
         foreach ($newCategories as $newCategory) {
             $nc[$newCategory['slug']] = $newCategory;
         }
         $oldIdToNewId = array();
         echo "Migrating media categories to Apostrophe categories...\n";
         foreach ($oldCategories as $category) {
             if (isset($nc[$category['slug']])) {
                 $oldIdToNewId[$category['id']] = $nc[$category['slug']]['id'];
             } else {
                 $this->migrate->query('INSERT INTO a_category (name, description, slug) VALUES (:name, :description, :slug)', $category);
                 $oldIdToNewId[$category['id']] = $this->migrate->lastInsertId();
             }
         }
         echo "Migrating from aMediaItemCategory to aMediaItemToCategory...\n";
         $oldMappings = $this->migrate->query('SELECT * FROM a_media_item_category');
         foreach ($oldMappings as $info) {
             $info['category_id'] = $oldIdToNewId[$info['media_category_id']];
             $this->migrate->query('INSERT INTO a_media_item_to_category (media_item_id, category_id) VALUES (:media_item_id, :category_id)', $info);
         }
     }
     if (!$this->migrate->tableExists('a_embed_media_account')) {
         $this->migrate->sql(array('CREATE TABLE a_embed_media_account (id INT AUTO_INCREMENT, service VARCHAR(100) NOT NULL, username VARCHAR(100) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB;'));
     }
     if (!$this->migrate->columnExists('a_page', 'edit_admin_lock')) {
         $this->migrate->sql(array('ALTER TABLE a_page ADD COLUMN edit_admin_lock TINYINT(1) DEFAULT "0"', 'ALTER TABLE a_page ADD COLUMN view_admin_lock TINYINT(1) DEFAULT "0"'));
         $options = array('application' => $options['application'], 'env' => $options['env'], 'connection' => $options['connection']);
         $postTasks[] = array('task' => new apostropheCascadeEditPermissionsTask($this->dispatcher, $this->formatter), 'arguments' => array(), 'options' => $options);
     }
     if (!$this->migrate->columnExists('a_page', 'view_guest')) {
         $this->migrate->sql(array('ALTER TABLE a_page ADD COLUMN view_guest TINYINT(1) DEFAULT "1"'));
         $options = array('application' => $options['application'], 'env' => $options['env'], 'connection' => $options['connection']);
         $postTasks[] = array('task' => new apostropheCascadeEditPermissionsTask($this->dispatcher, $this->formatter), 'arguments' => array(), 'options' => $options);
     }
     // Migrate all IDs to BIGINT (the default in Doctrine 1.2) for compatibility with the
     // new version of sfDoctrineGuardPlugin. NOTE: we continue to use INT in create table
     // statements BEFORE this point because we need to set up relations with what they already
     // have - this call will clean that up
     $this->migrate->upgradeIds();
     // Upgrade all charsets to UTF-8 otherwise we can't store a lot of what comes back from embed services
     $this->migrate->upgradeCharsets();
     // We can add these constraints now that we have IDs of the right size
     if (!$this->migrate->constraintExists('a_media_item_to_category', 'a_media_item_to_category_category_id_a_category_id')) {
         $this->migrate->sql(array('ALTER TABLE a_media_item_to_category MODIFY COLUMN category_id BIGINT', 'ALTER TABLE a_media_item_to_category MODIFY COLUMN media_item_id BIGINT', "ALTER TABLE a_media_item_to_category ADD CONSTRAINT `a_media_item_to_category_category_id_a_category_id` FOREIGN KEY (`category_id`) REFERENCES `a_category` (`id`) ON DELETE CASCADE", "ALTER TABLE a_media_item_to_category ADD CONSTRAINT `a_media_item_to_category_media_item_id_a_media_item_id` FOREIGN KEY (`media_item_id`) REFERENCES `a_media_item` (`id`) ON DELETE CASCADE"));
     }
     // sfDoctrineGuardPlugin 5.0.x requires this
     if (!$this->migrate->columnExists('sf_guard_user', 'email_address')) {
         $this->migrate->sql(array('ALTER TABLE sf_guard_user ADD COLUMN first_name varchar(255) DEFAULT NULL', 'ALTER TABLE sf_guard_user ADD COLUMN last_name varchar(255) DEFAULT NULL', 'ALTER TABLE sf_guard_user ADD COLUMN email_address varchar(255) DEFAULT \'\''));
         // Email addresses are mandatory and can't be null. We can't start guessing whether
         // you have them in some other table or not. So the best we can do is stub in
         // the username for uniqueness for now
         $this->migrate->sql(array('UPDATE sf_guard_user SET email_address = concat(username, \'@notavalidaddress\')', 'ALTER TABLE sf_guard_user ADD UNIQUE KEY `email_address` (`email_address`);'));
     }
     if (!$this->migrate->tableExists('sf_guard_forgot_password')) {
         $this->migrate->sql(array('
     CREATE TABLE `sf_guard_forgot_password` (
       `id` bigint(20) NOT NULL AUTO_INCREMENT,
       `user_id` bigint(20) NOT NULL,
       `unique_key` varchar(255) DEFAULT NULL,
       `expires_at` datetime NOT NULL,
       `created_at` datetime NOT NULL,
       `updated_at` datetime NOT NULL,
       PRIMARY KEY (`id`),
       KEY `user_id_idx` (`user_id`),
       CONSTRAINT `sf_guard_forgot_password_user_id_sf_guard_user_id` FOREIGN KEY (`user_id`) REFERENCES `sf_guard_user` (`id`) ON DELETE CASCADE
     ) ENGINE=InnoDB DEFAULT CHARSET=utf8'));
     }
     if (!$this->migrate->columnExists('a_page', 'published_at')) {
         $this->migrate->sql(array('ALTER TABLE a_page ADD COLUMN published_at DATETIME DEFAULT NULL', 'UPDATE a_page SET published_at = created_at WHERE published_at IS NULL'));
     }
     // Remove any orphaned media items created by insufficiently carefully written embed services,
     // these can break the media repository
     $this->migrate->sql(array('DELETE FROM a_media_item WHERE type="video" AND embed IS NULL AND service_url IS NULL'));
     // Rename any tags with slashes in them to avoid breaking routes in Symfony
     $this->migrate->sql(array('UPDATE tag SET name = replace(name, "/", "-")'));
     // A chance to make plugin- and project-specific additions to the schema before Doctrine queries fail to see them
     sfContext::getInstance()->getEventDispatcher()->notify(new sfEvent($this->migrate, "a.migrateSchemaAdditions"));
     $mediaEnginePage = Doctrine::getTable('aPage')->createQuery('p')->where('p.admin IS TRUE AND p.engine = "aMedia"')->fetchOne();
     if (!$mediaEnginePage) {
         $mediaEnginePage = new aPage();
         $root = aPageTable::retrieveBySlug('/');
         $mediaEnginePage->getNode()->insertAsFirstChildOf($root);
     }
     $mediaEnginePage->slug = '/admin/media';
     $mediaEnginePage->engine = 'aMedia';
     $mediaEnginePage->setAdmin(true);
     $mediaEnginePage->setPublishedAt(aDate::mysql());
     $new = $mediaEnginePage->isNew();
     $mediaEnginePage->save();
     if ($new) {
         $mediaEnginePage->setTitle('Media');
     }
     echo "Ensured there is an admin media engine\n";
     echo "Finished updating tables.\n";
     if (count($postTasks)) {
         echo "Invoking post-migration tasks...\n";
         foreach ($postTasks as $taskInfo) {
             $taskInfo['task']->run($taskInfo['arguments'], $taskInfo['options']);
         }
     }
     echo "Done!\n";
 }
Ejemplo n.º 16
0
 /**
  * DOCUMENT ME
  * @param sfWebRequest $request
  */
 public function executeReorganize(sfWebRequest $request)
 {
     // Reorganizing the tree = escaping your page-specific security limitations.
     // So only full CMS admins can do it.
     $this->flunkUnless($this->getUser()->hasCredential('cms_admin'));
     $root = aPageTable::retrieveBySlug('/');
     $this->forward404Unless($root);
     $this->treeData = $root->getTreeJSONReady(false);
     // setTitle takes care of escaping things
     $this->getResponse()->setTitle(aTools::getOptionI18n('title_prefix') . 'Reorganize' . aTools::getOptionI18n('title_suffix'));
 }
Ejemplo n.º 17
0
 public function getParent($with = false)
 {
     if ($this->parentCache === false) {
         aPageTable::treeTitlesOn();
         $this->parentCache = $this->getNode()->getParent();
         aPageTable::treeTitlesOff();
     }
     return $this->parentCache;
 }
Ejemplo n.º 18
0
 /**
  * DOCUMENT ME
  * @return mixed
  */
 protected function editSave()
 {
     $this->slot->save();
     $this->page->newAreaVersion($this->name, $this->newSlot ? 'add' : 'update', array('permid' => $this->permid, 'slot' => $this->slot, 'top' => sfConfig::get('app_a_new_slots_top', true)));
     // Refetch the page to reflect these changes before we
     // rerender the slot
     aTools::setCurrentPage(aPageTable::retrieveByIdWithSlots($this->page->id));
     if ($this->getRequestParameter('noajax')) {
         return $this->redirectToPage();
     } else {
         return $this->editAjax(false);
     }
 }
Ejemplo n.º 19
0
 /**
  * Prepends the current CMS page to the URL.
  *
  * @param  string $url The URL so far obtained from parent::generate
  * @param  Boolean $absolute  Whether to generate an absolute URL
  *
  * @return string The generated URL
  */
 public static function addPageToUrl(sfRoute $route, $url, $absolute)
 {
     $slug = aRouteTools::getContextEngineSlug($route);
     if (!$slug) {
         $defaults = $route->getDefaults();
         $page = aPageTable::getFirstEnginePage($defaults['module']);
         if (!$page) {
             $slug = null;
         } else {
             $slug = $page->slug;
         }
     }
     if (!$slug) {
         throw new sfException('Attempt to generate aRoute URL for module ' . $defaults['module'] . ' with no matching engine page on the site');
     }
     // A route URL of / for an engine route maps to the page itself, without a trailing /
     if ($url === '/') {
         $url = '';
     }
     // Ditto for / followed by a query string (missed this before)
     if (substr($url, 0, 2) === '/?') {
         $url = substr($url, 1);
     }
     $pageUrl = aTools::urlForPage($slug, $absolute);
     $rr = preg_quote(sfContext::getInstance()->getRequest()->getRelativeUrlRoot(), '/');
     // Strip controller off so it doesn't duplicate the controller in the
     // URL we just generated. Also strip off sf_relative_root if any.
     // We could use the slug directly, but that would
     // break if the CMS were not mounted at the root on a particular site.
     // Take care to function properly in the presence of an absolute URL
     if (preg_match("/^(?:https?:\\/\\/[^\\/]+)?{$rr}(?:\\/[^\\/]+\\.php)?(.*)\$/", $pageUrl, $matches)) {
         $pageUrl = $matches[1];
     }
     // Fix double / at beginning when engine is at root of site (think "just a blog")
     $finalUrl = $pageUrl . $url;
     $finalUrl = preg_replace('|^//|', '/', $finalUrl);
     return $finalUrl;
 }
 public function queryWithPages($query = null)
 {
     if (is_null($query)) {
         $query = $this->createQuery();
     }
     $query->leftJoin($query->getRootAlias() . '.Page p');
     $query = aPageTable::queryWithSlots(false, null, $query);
     return $query;
 }
Ejemplo n.º 21
0
 /**
  * DOCUMENT ME
  * @param mixed $options
  */
 public static function globalSetup($options)
 {
     if (isset($options['global']) && $options['global']) {
         if (!isset($options['slug'])) {
             $options['slug'] = 'global';
         }
     }
     if (isset($options['slug'])) {
         // Note that we push onto the stack even if the page specified is the same page
         // we're looking at. This doesn't hurt because of caching, and it allows us
         // to keep the stack count properly
         $slug = $options['slug'];
         aTools::$pageStack[] = aTools::getCurrentPage();
         // Caching the global page speeds up pages with two or more global slots
         if (isset(aTools::$globalCache[$slug])) {
             $global = aTools::$globalCache[$slug];
         } else {
             $global = aPageTable::retrieveBySlugWithSlots($slug);
             if (!$global) {
                 $global = new aPage();
                 $global->slug = $slug;
                 $global->save();
             }
             aTools::$globalCache[$slug] = $global;
         }
         aTools::setCurrentPage($global);
         aTools::$global = true;
     }
 }
 protected function editAjax($editorOpen)
 {
     // Refetch the page to reflect these changes before we
     // rerender the slot
     aTools::setCurrentPage(aPageTable::retrieveByIdWithSlots($this->page->id));
     // Symfony 1.2 can return partials rather than templates...
     // which gets us out of the "we need a template from some other
     // module" bind
     $variant = $this->slot->getEffectiveVariant($this->options);
     return $this->renderPartial("a/ajaxUpdateSlot", array("name" => $this->name, "type" => $this->type, "permid" => $this->permid, "options" => $this->options, "editorOpen" => $editorOpen, "pageid" => $this->page->id, "variant" => $variant, "validationData" => $this->validationData));
 }
Ejemplo n.º 23
0
<?php

slot('body_class');
?>
a-error404<?php 
end_slot();
use_helper('a');
?>

<?php 
$page = aPageTable::retrieveBySlug('/admin/error404');
?>
	
<?php 
$page ? $slots = $page->getArea('body') : ($slots = array());
?>

<?php 
// If there are no slots, show some default text
if (!count($slots)) {
    ?>
	<h2><?php 
    echo a_('Error 404 &mdash; The page you are looking for could not be found.');
    ?>
</h2>
	<?php 
    $search = trim(aTools::slugify(str_replace($sf_request->getUriPrefix(), '', $sf_request->getUri()), false, false, ' '));
    ?>
	<h3><?php 
    echo link_to(a_('Try searching for %SEARCH%.', array('%SEARCH%' => $search)), 'a/search?' . http_build_query(array('q' => $search)));
    ?>
 public static function filterForEngine($options)
 {
     // This method filters the virtual pages, tags and categories associated with a particular engine based on
     // specified criteria such as tag, category, publication date, etc.
     // Strategy: do Lucene queries and direct SQL queries that will get us all the info about relevant categories,
     // tags and virtual pages. Then turn that into a select distinct query for each of those things. The resulting
     // information is sufficient to populate the filters sidebar with options that are still relevant given the
     // other criteria in effect, and also to fetch the result pages (you'll want to do that with a LIMIT and an IN
     // query looking at the first n IDs returned by this method).
     // The options array looks like this. Note that all of these are optional and if each is unspecified or empty
     // no restriction is made on that particular basis. 'categoryIds' is used to limit to the categories associated
     // with the engine page, while 'categorySlug' is used to limit to a category specified by the user as a
     // filter. The 'q' option is Lucene search.
     // array(
     //   'q' => 'gromit',
     //   'categoryIds' => array(1, 3, 5),
     //   'categorySlug' => 'cheese',
     //   'tag' => 'wensleydale',
     //   'slugStem' => '@a_event_search_redirect',
     //   'year' => 2010, # Optional, if present only 2010 is shown
     //   'month' => 12, # Optional, if present only Dec. 2010 is shown
     //   'day' => 15, # Optional, if present only Dec. 15th 2010 is shown
     //   'byEventDateRange' => true, # For events only, joins with a_blog_item to get the range
     //   'byPublishedAt' => true, # For blog posts or pages
     // The returned value looks like this:
     // array(
     //   'categoriesInfo' => array('slug' => 'cheese', 'name' => 'Cheese'),
     //   'tagNames' => array('wensleydale'),
     //   'pageIds' => array(10, 15, 20, 25)
     $alphaSort = isset($options['alphaSort']) && $options['alphaSort'];
     if (isset($options['q']) && strlen($options['q'])) {
         $q = $options['q'];
         $key = strtolower(trim($q));
         $key = preg_replace('/\\s+/', ' ', $key);
         $replacements = sfConfig::get('app_a_search_refinements', array());
         if (isset($replacements[$key])) {
             $q = $replacements[$key];
         }
         if (isset($options['slugStem'])) {
             $q = "({$q}) AND slug:" . $options['slugStem'];
         }
         try {
             $values = aZendSearch::searchLuceneWithValues(Doctrine::getTable('aPage'), $q, aTools::getUserCulture());
         } catch (Exception $e) {
             // Lucene search error. TODO: display it nicely if they are always safe things to display. For now: just don't crash
             $values = array();
         }
         $now = date('YmdHis');
         $pageIds = array();
         foreach ($values as $value) {
             // Regardless of the above if it ain't published yet we can't see it.
             // We filter on that in the Doctrine query too but take advantage of
             // this chance to preempt a little work
             if ($value->published_at > $now) {
                 continue;
             }
             // 1.5: the names under which we store columns in Zend Lucene have changed to
             // avoid conflict with also indexing them
             $info = unserialize($value->info_stored);
             if (!aPageTable::checkPrivilege('view', $info)) {
                 continue;
             }
             $pageIds[] = $info['id'];
         }
     }
     $mysql = new aMysql();
     if (isset($options['slugStem'])) {
         $params['slug_pattern'] = $options['slugStem'] . '%';
     }
     // Select the relevant virtual pages for this engine
     $q = 'from a_page p ';
     // If alpha sort is present we need title slots
     if ($alphaSort) {
         if (!isset($options['culture'])) {
             $options['culture'] = aTools::getUserCulture();
         }
         $culture = $options['culture'];
         $q .= "\n        LEFT JOIN a_area a ON a.page_id = p.id AND a.name = 'title' AND a.culture = :culture\n        LEFT JOIN a_area_version v ON v.area_id = a.id AND a.latest_version = v.version \n        LEFT JOIN a_area_version_slot avs ON avs.area_version_id = v.id\n        LEFT JOIN a_slot s ON s.id = avs.slot_id ";
         $params['culture'] = $culture;
     }
     // Merge in categories. A left join unless we are restricted to certain categories
     $hasCategoryIds = isset($options['categoryIds']) && count($options['categoryIds']);
     $hasCategorySlug = isset($options['categorySlug']) && strlen($options['categorySlug']);
     $restrictedByCategory = $hasCategoryIds || $hasCategorySlug;
     if ($restrictedByCategory) {
         $cjoin = 'inner join';
     } else {
         $cjoin = 'left join';
     }
     $q .= $cjoin . ' a_page_to_category ptc on ptc.page_id = p.id ' . $cjoin . ' a_category c on ptc.category_id = c.id ';
     // The engine page is locked down to these categories. If none are specified it is not
     // locked down by category
     if ($hasCategoryIds) {
         $q .= "and c.id in :category_ids ";
         $params['category_ids'] = $options['categoryIds'];
     }
     // Bring in tags...
     $hasTag = isset($options['tag']) && strlen($options['tag']);
     if ($hasTag) {
         $q .= 'inner join ';
     } else {
         $q .= 'left join ';
     }
     $q .= 'tagging ti on ti.taggable_id = p.id and ti.taggable_model = "aPage" left join tag t on ti.tag_id = t.id ';
     // Get ready to filter posts or events chronologically
     $year = sprintf("%04d", isset($options['year']) ? $options['year'] : 0);
     $month = sprintf("%02d", isset($options['month']) ? $options['month'] : 0);
     $day = sprintf("%02d", isset($options['day']) ? $options['day'] : 0);
     $startYear = $year;
     $endYear = $year;
     if ($year > 0) {
         if ($month == 0) {
             // Do not mess up the two digit strings please
             $startMonth = '01';
             $startDay = '01';
             $endMonth = '12';
             $endDay = '31';
         } else {
             $startMonth = $month;
             $endMonth = $month;
             if ($day == 0) {
                 // Do not mess up the two digit strings please
                 $startDay = '01';
                 $endDay = '31';
             } else {
                 $startDay = $day;
                 $endDay = $day;
             }
         }
     } else {
         // For posts "today and forward" is not a relevant concept (and a separate clause
         // already makes sure we don't see unpublished stuff). For events we'll override
         // the start date below
         $startYear = '0000';
         $startMonth = '01';
         $startDay = '01';
         $endYear = '9999';
         $endMonth = '12';
         $endDay = '31';
     }
     $events = isset($options['byEventDateRange']) && $options['byEventDateRange'];
     if ($events && $startYear === '0000') {
         list($startYear, $startMonth, $startDay) = preg_split('/-/', date('Y-m-d'));
     }
     if ($events) {
         // The event's start and end dates are part of the blog item table
         $q .= ' inner join a_blog_item bi on bi.page_id = p.id ';
         $q .= "and bi.start_date <= :end_date ";
         $params['end_date'] = "{$endYear}-{$endMonth}-{$endDay}";
         $q .= "and bi.end_date >= :start_date ";
         $params['start_date'] = "{$startYear}-{$startMonth}-{$startDay}";
     }
     // Criteria for the pages themselves
     $q .= 'where p.slug like :slug_pattern ';
     // We often filter posts (not events) by a range of publication dates
     if (isset($options['byPublishedAt']) && $options['byPublishedAt']) {
         $q .= "and p.published_at <= :p_end_date ";
         $params['p_end_date'] = "{$endYear}-{$endMonth}-{$endDay}";
         $q .= "and p.published_at >= :p_start_date ";
         $params['p_start_date'] = "{$startYear}-{$startMonth}-{$startDay}";
     }
     // In no case do we show unpublished material
     $q .= 'and p.published_at <= NOW() and (p.archived IS NULL or p.archived IS FALSE) ';
     // ... But only those matching the Lucene search that already gave us specific IDs.
     // NOTE: if pageIds is not null and is empty, NOTHING should be returned
     // (someone searched for something that doesn't appear in the system)
     if (isset($pageIds)) {
         if (count($pageIds)) {
             $q .= 'and p.id in :pageIds ';
             $params['pageIds'] = $pageIds;
         } else {
             $q .= 'and 0 <> 0 ';
         }
     }
     if ($alphaSort) {
         $pagesOrderBy = 's.value asc';
     } elseif ($events) {
         $pagesOrderBy = 'bi.start_date asc, bi.start_time asc';
     } else {
         // Oops: blog presentation is typically descending, not ascending
         $pagesOrderBy = 'p.published_at desc';
     }
     // Separate queries, but quite fast because we're not bogged down in Doctrineland
     $c_q = $q;
     $t_q = $q;
     $p_q = $q;
     // We are filtering by this specific category
     if ($hasCategorySlug) {
         // Limit tags and pages by this specific category, but don't limit
         // categories by it, otherwise we can't present a choice of categories
         // meeting the other criteria
         $t_q .= "and c.slug = :category_slug ";
         $p_q .= "and c.slug = :category_slug ";
         $params['category_slug'] = $options['categorySlug'];
     }
     if ($hasTag) {
         // Limit pages and categories by this specific tag, but don't limit
         // tags by it, otherwise we can't present a choice of tags
         // meeting the other criteria
         $p_q .= 'and t.name = :tag_name ';
         $c_q .= 'and t.name = :tag_name ';
         $params['tag_name'] = $options['tag'];
     }
     // In the cases where we are looking for categories or tags, be sure to
     // discard the null rows from the LEFT JOINs. This is simpler than
     // determining when to switch them to INNER JOINs
     $result = array('categoriesInfo' => $mysql->query('select distinct c.slug, c.name ' . $c_q . 'and c.slug is not null order by c.name', $params), 'tagsByName' => $mysql->query('select t.name, count(distinct p.id) as t_count ' . $t_q . 'and t.name is not null group by t.name order by t.name', $params), 'tagsByPopularity' => $mysql->query('select t.name, count(distinct p.id) as t_count ' . $t_q . 'and t.name is not null group by t.name order by t_count desc limit 10', $params), 'pageIds' => $mysql->queryScalar('select distinct p.id ' . $p_q . ' order by ' . $pagesOrderBy, $params));
     return $result;
 }
 public static function titleSearch($search, $slugPrefix)
 {
     $q = aPageTable::queryWithTitles();
     $q->addWhere('p.slug LIKE ?', array("{$slugPrefix}%"));
     $q->addWhere('s.value LIKE ?', array('%' . $search . '%'));
     $q->addWhere('p.archived IS FALSE');
     $virtualPages = $q->execute(array(), Doctrine::HYDRATE_ARRAY);
     $ids = array();
     foreach ($virtualPages as $page) {
         if (preg_match("/^{$slugPrefix}\\?id=(\\d+)\$/", $page['slug'], $matches)) {
             $ids[] = $matches[1];
         }
     }
     if (!count($ids)) {
         return array();
     } else {
         return Doctrine::getTable('aBlogItem')->createQuery('e')->whereIn('e.id', $ids)->execute(array(), Doctrine::HYDRATE_ARRAY);
     }
 }
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     // We need to use PDO here because Doctrine is more than a little confused when
     // we've renamed the codebase but not the tables
     echo "Renaming tables in database\n";
     $tables = array('pk_context_cms_slot' => 'a_slot', 'pk_context_cms_area_version_slot' => 'a_area_version_slot', 'pk_context_cms_area_version' => 'a_area_version', 'pk_context_cms_area' => 'a_area', 'pk_context_cms_page' => 'a_page', 'pk_blog_category' => 'a_blog_category', 'pk_blog_event_version' => 'a_blog_event_version', 'pk_blog_item' => 'a_blog_item', 'pk_blog_item_version' => 'a_blog_item_version', 'pk_blog_post_version' => 'a_blog_post_version', 'pk_context_cms_access' => 'a_access', 'pk_context_cms_lucene_update' => 'a_lucene_update', 'pk_media_item' => 'a_media_item');
     $conn = Doctrine_Manager::connection()->getDbh();
     foreach ($tables as $old => $new) {
         try {
             echo "before\n";
             $conn->query("RENAME TABLE {$old} TO {$new}");
             echo "after\n";
         } catch (Exception $e) {
             echo "Rename of {$old} failed, that's normal if you don't use that table's plugin or you have run this script before.\n";
         }
     }
     echo "Renaming slots and engines in database\n";
     try {
         $conn->query('UPDATE a_slot SET type = REPLACE(type, "pkContextCMS", "a")');
     } catch (Exception $e) {
         echo "Warning: unable to reset slot types in a_slot table\n";
     }
     try {
         $conn->query('UPDATE a_page SET engine = REPLACE(engine, "pk", "a")');
     } catch (Exception $e) {
         echo "Warning: unable to rename engines in a_page table\n";
     }
     try {
         $conn->query('ALTER TABLE a_page ADD admin tinyint(1)');
     } catch (Exception $e) {
         echo "Warning: unable to add admin column to a_page table\n";
     }
     try {
         $conn->query('ALTER TABLE a_slot ADD variant varchar(100)');
     } catch (Exception $e) {
         echo "Warning: unable to add variant column to a_slot table\n";
     }
     try {
         $conn->query("CREATE TABLE `a_slot_media_item` (\n        `media_item_id` int(11) NOT NULL DEFAULT '0',\n        `slot_id` int(11) NOT NULL DEFAULT '0',\n        PRIMARY KEY (`media_item_id`,`slot_id`),\n        KEY `a_slot_media_item_slot_id_a_slot_id` (`slot_id`),\n        CONSTRAINT `a_slot_media_item_media_item_id_a_media_item_id` FOREIGN KEY (`media_item_id`) REFERENCES `a_media_item` (`id`) ON DELETE CASCADE,\n        CONSTRAINT `a_slot_media_item_slot_id_a_slot_id` FOREIGN KEY (`slot_id`) REFERENCES `a_slot` (`id`) ON DELETE CASCADE\n      ) ENGINE=InnoDB DEFAULT CHARSET=latin1;");
     } catch (Exception $e) {
         echo "Warning: couldn't create a_slot_media_item table\n";
     }
     echo "Migrating media slots\n";
     $count = 0;
     $mediaSlots = Doctrine::getTable('aSlot')->createQuery('s')->whereIn('s.type', array('aImage', 'aPDF', 'aButton', 'aSlideshow', 'aVideo'))->execute();
     $total = count($mediaSlots);
     foreach ($mediaSlots as $mediaSlot) {
         $count++;
         echo "Migrating slot {$count} of {$total}\n";
         if ($mediaSlot->type === 'aSlideshow') {
             $items = $mediaSlot->getArrayValue();
             if (isset($items[0]) && isset($items[0]->id)) {
                 $order = array();
                 foreach ($items as $item) {
                     // aArray::getids has trouble with StdClass objects for some reason
                     $order[] = $item->id;
                 }
                 $mediaSlot->unlink('MediaItems');
                 $mediaSlot->link('MediaItems', $order);
                 $mediaSlot->setArrayValue(array('order' => $order));
                 $mediaSlot->save();
             }
         } else {
             if (strlen($mediaSlot->value)) {
                 $item = unserialize($mediaSlot->value);
                 if (isset($item->id)) {
                     $mediaSlot->unlink('MediaItems');
                     $mediaSlot->link('MediaItems', array($item->id));
                     $mediaSlot->setValue(null);
                     $mediaSlot->save();
                 }
             }
         }
     }
     try {
         $conn->query("CREATE TABLE `a_media_category` (\n        `id` int(11) NOT NULL AUTO_INCREMENT,\n        `name` varchar(255) DEFAULT NULL,\n        `description` text,\n        `created_at` datetime NOT NULL,\n        `updated_at` datetime NOT NULL,\n        `slug` varchar(255) DEFAULT NULL,\n        PRIMARY KEY (`id`),\n        UNIQUE KEY `name` (`name`)\n      ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1");
     } catch (Exception $e) {
         echo "Warning: couldn't create a_media_category table\n";
     }
     try {
         $conn->query("CREATE TABLE `a_media_item_category` (\n        `media_item_id` int(11) NOT NULL DEFAULT '0',\n        `media_category_id` int(11) NOT NULL DEFAULT '0',\n        PRIMARY KEY (`media_item_id`,`media_category_id`),\n        KEY `a_media_item_category_media_category_id_a_media_category_id` (`media_category_id`),\n        CONSTRAINT `a_media_item_category_media_category_id_a_media_category_id` FOREIGN KEY (`media_category_id`) REFERENCES `a_media_category` (`id`) ON DELETE CASCADE,\n        CONSTRAINT `a_media_item_category_media_item_id_a_media_item_id` FOREIGN KEY (`media_item_id`) REFERENCES `a_media_item` (`id`) ON DELETE CASCADE\n      ) ENGINE=InnoDB DEFAULT CHARSET=latin1");
     } catch (Exception $e) {
         echo "Warning: couldn't create a_media_item_category table\n";
     }
     try {
         $conn->query("CREATE TABLE `a_media_page_category` (\n        `page_id` int(11) NOT NULL DEFAULT '0',\n        `media_category_id` int(11) NOT NULL DEFAULT '0',\n        PRIMARY KEY (`page_id`,`media_category_id`),\n        KEY `a_media_page_category_media_category_id_a_media_category_id` (`media_category_id`),\n        CONSTRAINT `a_media_page_category_media_category_id_a_media_category_id` FOREIGN KEY (`media_category_id`) REFERENCES `a_media_category` (`id`) ON DELETE CASCADE,\n        CONSTRAINT `a_media_page_category_page_id_a_page_id` FOREIGN KEY (`page_id`) REFERENCES `a_page` (`id`) ON DELETE CASCADE\n      ) ENGINE=InnoDB DEFAULT CHARSET=latin1");
     } catch (Exception $e) {
         echo "Warning: couldn't create a_media_page_category table\n";
     }
     echo "Rebuilding search index\n";
     $cmd = "./symfony apostrophe:rebuild-search-index --env=" . $options['env'];
     system($cmd, $result);
     if ($result != 0) {
         die("Unable to rebuild search indexes\n");
     }
     echo "If you have folders in data/pk_writable other than tmp and the zend search indexes \nyou may want to move them to data/a_writable. Due to interactions with svn this is not\nautomatic. In our projects we use svn ignore rules to protect the contents of the\ndata/*_writable folder. This is primarily an issue on servers other than your\ndevelopment machine, where you run this task separately. On your development\nmachine pk_writable is renamed to a_writable automatically.\n";
     // We need to be an admin user so the model layer sees the current user has
     // permissions to do what follows. We can't do this any earlier because
     // the routing table fires up and routes the home page which requires looking
     // at some engine routes, so the a_page table has to be ready
     aTaskTools::signinAsTaskUser($this->createConfiguration($options['application'], $options['env']));
     // Create the admin pages
     $home = aPageTable::retrieveBySlug('/');
     $admin = aPageTable::retrieveBySlug('/admin');
     if (!$admin) {
         $admin = new aPage();
         $admin->setSlug('/admin');
         $admin->setAdmin(true);
         $admin->getNode()->insertAsFirstChildOf($home);
         $admin->setEngine('aAdmin');
         $admin->save();
         // Must save the page BEFORE we call setTitle, which has the side effect of
         // refreshing the page object
         $admin->setTitle('Admin');
     }
     $page = aPageTable::retrieveBySlug('/admin/media');
     if (!$page) {
         $page = new aPage();
         $page->setSlug('/admin/media');
         $page->setAdmin(true);
         $page->getNode()->insertAsLastChildOf($admin);
         $page->setEngine('aMedia');
         $page->save();
         // Must save the page BEFORE we call setTitle, which has the side effect of
         // refreshing the page object
         $page->setTitle('Media');
     }
 }
Ejemplo n.º 27
0
 /**
  * Accepts array('info' => [page info array], all options accepted by getPagesInfo except where)
  * @param mixed $options
  * @return mixed
  */
 public static function getChildrenInfo($options)
 {
     $id = $options['info']['id'];
     if (!isset(aPageTable::$childrenInfo[$id])) {
         $lft = $options['info']['lft'];
         $rgt = $options['info']['rgt'];
         $level = $options['info']['level'] + 1;
         aPageTable::$childrenInfo[$id] = aPageTable::getPagesInfo(array_merge($options, array('where' => '(( p.lft > ' . $lft . ' AND p.rgt < ' . $rgt . ' ) AND (level = ' . $level . '))')));
     }
     return aPageTable::$childrenInfo[$id];
 }
Ejemplo n.º 28
0
<?php

include dirname(__FILE__) . '/../../bootstrap/functional.php';
$b = new aTestFunctional(new aBrowser());
$b->setOptions(array('default-prefix' => '/admin/'));
$b->info('1 - CMS Credentials')->info('  1.1 - Unauthenticated users do not see the CMS controls or the buttons in the toolbar')->getAndCheck('a', 'show', '/')->with('response')->begin()->checkElement('li.a-header-cms', false)->end()->info('  1.2 - An admin user (admin/demo) can see the CMS controls and the buttons in the toolbar')->restart()->login('admin', 'demo');
$user = sfContext::getInstance()->getUser();
$b->info('Username is ' . $user->getGuardUser()->getUsername())->info('Permission is ' . $user->hasCredential('cms_admin'))->getAndCheck('a', 'show', '/');
$page = aPageTable::retrieveBySlug('/');
$b->info('User has edit privilege')->test()->is($page->userHasPrivilege('edit'), true);
$b->with('response')->begin()->checkElement('ul.a-controls', true)->end();
$b->info('User has manage privilege')->test()->is($page->userHasPrivilege('edit'), true);
$b->info('Creating a subpage works properly')->createPage('/', 'Test')->with('request')->begin()->isParameter('slug', 'test')->end();
 public function executeNavigation(sfRequest $request)
 {
     // What page are we starting from?
     // Navigation on non-CMS pages is relative to the home page
     if (!($this->page = aTools::getCurrentPage())) {
         $this->page = aPageTable::retrieveBySlug('/');
     }
     if (!($this->activePage = aPageTable::retrieveBySlug($this->activeSlug))) {
         $this->activePage = $this->page;
     }
     if (!($this->rootPage = aPageTable::retrieveBySlug($this->rootSlug))) {
         $this->rootPage = $this->activePage;
     }
     // We build different page trees depending on the navigation type that was requested
     if (!$this->type) {
         $this->type = 'tree';
     }
     $class = 'aNavigation' . ucfirst($this->type);
     if (!class_exists($class)) {
         throw new sfException(sprintf('Navigation type "%s" does not exist.', $class));
     }
     $this->navigation = new $class($this->rootPage, $this->activePage, $this->options);
     $this->draggable = $this->page->userHasPrivilege('edit');
     // Users can pass class names to the navigation <ul>
     $this->classes = '';
     if (isset($this->options['classes'])) {
         $this->classes .= $this->options['classes'];
     }
     $this->nest = 0;
     // The type of the navigation also is used for styling
     $this->classes .= ' ' . $this->type;
     $this->navigation = $this->navigation->getItems();
     if (count($this->navigation) == 0) {
         return sfView::NONE;
     }
 }
Ejemplo n.º 30
0
 /**
  * Prepends the current CMS page to the URL.
  *
  * @param  string $url The URL so far obtained from parent::generate
  * @param  Boolean $absolute  Whether to generate an absolute URL
  *
  * @return string The generated URL
  */
 public static function addPageToUrl(sfRoute $route, $url, $absolute)
 {
     $defaults = $route->getDefaults();
     $currentPage = aTools::getCurrentPage();
     $engine = $defaults['module'];
     if (isset(self::$targetEnginePages[$engine]) && count(self::$targetEnginePages[$engine])) {
         $page = end(self::$targetEnginePages[$engine]);
     } elseif (!$currentPage || $currentPage->engine !== $defaults['module']) {
         $page = aPageTable::getFirstEnginePage($defaults['module']);
     } else {
         $page = $currentPage;
     }
     if (!$page) {
         throw new sfException('Attempt to generate aRoute URL for module ' . $defaults['module'] . ' with no matching engine page on the site');
     }
     // A route URL of / for an engine route maps to the page itself, without a trailing /
     if ($url === '/') {
         $url = '';
     }
     // Ditto for / followed by a query string (missed this before)
     if (substr($url, 0, 2) === '/?') {
         $url = substr($url, 1);
     }
     $pageUrl = $page->getUrl($absolute);
     // Strip controller off so it doesn't duplicate the controller in the
     // URL we just generated. We could use the slug directly, but that would
     // break if the CMS were not mounted at the root on a particular site.
     // Take care to function properly in the presence of an absolute URL
     if (preg_match("/^(https?:\\/\\/[^\\/]+)?\\/[^\\/]+\\.php(.*)\$/", $pageUrl, $matches)) {
         $pageUrl = $matches[2];
     }
     return $pageUrl . $url;
 }