Esempio n. 1
0
 /**
  *
  * THIS METHOD WILL NOT WORK RELIABLY UNLESS THE ROUTING CACHE IS TURNED **OFF**.
  *
  * The routing cache defaults to off in new Symfony 1.3 and 1.4 projects because
  * it has found to hurt performance in most cases, sometimes quite severely. We do 
  * not currently enable it on any of our projects.
  * 
  * The routing cache does not take the desired engine page into account, so it will
  * return URLs targeting the wrong page. If you must use the routing cache,
  * design your projects to avoid the use of multiple engine pages for the
  * same engine module.
  *
  * This method sets a specific target engine page for any url_for, link_to, etc. 
  * calls invoking an engine route. If you have only one instance of a given engine 
  * in your site, you don't need to call this method. A link generated within that 
  * engine page will target the same engine page, and a link generated from anywhere 
  * else will target the first engine page for that engine module name found in 
  * the database. If you have more than one engine page for the same engine module 
  * name, and you care which one the link points to, call this method to specify 
  * that page. 
  *
  * A stack of target engine pages is maintained for each engine module name.
  * This allows you to push a new engine page at the top of a partial or component
  * that potentially targets a different engine page than the template that
  * invoked it, and then pop that engine page at the end to ensure that any links
  * generated later in the calling template still target the original engine page.
  *
  * You can pass a page object or, for convenience, a page slug. The latter is useful
  * when targeting an engine page that is guaranteed to exist, such as /admin/media
  *
  * @param  aPage $page|string $page The target engine page for engine routes, or a page slug
  *
  */
 public static function pushTargetEnginePage($page)
 {
     if (!(is_object($page) && $page instanceof aPage)) {
         $page = aPageTable::retrieveBySlug($page);
     }
     self::$targetEnginePages[$page->engine][] = $page;
 }
Esempio n. 2
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();
 }
 /**
  * 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';
 }
Esempio n. 6
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'));
 }
Esempio n. 7
0
 public function getAccordionInfo($livingOnly = true, $depth = null)
 {
     // As far as I can tell there is no super-elegant, single-query way to do this
     // without fetching a lot of extra pages. So do a peer fetch at each level.
     // First build an array of arrays listing the peers at each level
     // If you have enabled children of archived ancestors and you don't
     // want the ancestors to show up, you probably shouldn't be using
     // an accordion contro. in the first place
     $ancestors = $this->getAncestorsInfo();
     $result = array();
     // Ancestor levels
     foreach ($ancestors as $ancestor) {
         $lineage[] = $ancestor['id'];
         if ($ancestor['level'] == 0) {
             $result[] = array($ancestor);
         } else {
             // TODO: this is inefficient, come up with a way to call getPeerInfo for an
             // alternate ID without fetching that entire page
             $result[] = aPageTable::retrieveBySlug($ancestor['slug'])->getPeerInfo($livingOnly);
         }
     }
     // Current page peers level
     $result[] = $this->getPeerInfo($livingOnly);
     $lineage[] = $this->id;
     // Current page children level
     $result[] = $this->getChildrenInfo($livingOnly);
     // Now fix it up to be a properly nested array like that
     // returned by getTreeInfo(). On each pass take a reference
     // to the child that will own the children of the next pass
     $accordion = $result[0][0];
     $current =& $accordion;
     for ($i = 0; $i < count($result) - 1; $i++) {
         $current['children'] = $result[$i + 1];
         if ($i + 1 < count($lineage)) {
             // We've already started returning the kids as a flat array so
             // we need to scan for it unfortunately. This entire method could
             // use more attention to performance
             foreach ($current['children'] as &$child) {
                 if ($child['id'] == $lineage[$i + 1]) {
                     $current =& $child;
                     break;
                 }
             }
         }
     }
     // Don't return the home page itself, start with the tabs.
     // This is consistent with getTreeInfo() which should simplify implementations.
     // It's easy to add the home page in at a higher level if desired.
     return $accordion['children'];
 }
Esempio n. 8
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)));
    ?>
Esempio n. 9
0
 /**
  * Accordion nav
  * Always starts with the children of the root and comes down to the level of this page's children,
  * listing peers of this page's ancestors at every level. That is:
  * Home
  * One
  * 1a
  * 1b
  * 1bx  <-- the current page
  * 1bxA
  * ibxB
  * 1c
  * Two
  * You can now specify the root slug, which defaults to the home page.
  * Note that children of Two, 1a, and 1c are NOT returned. Only the siblings of
  * the current page's ancestors, the current page and its siblings, and the immediate
  * children of the current page are returned. For a full tree use getTreeInfo().
  * The livingOnly flag is present for bc only and is ignored, we get what the current user can see
  * @param mixed $livingOnly
  * @param mixed $depth
  * @param mixed $root
  * @return mixed
  */
 public function getAccordionInfo($livingOnly = true, $depth = null, $root = '/')
 {
     // As far as I can tell there is no super-elegant, single-query way to do this
     // without fetching a lot of extra pages. So do a peer fetch at each level.
     // First build an array of arrays listing the peers at each level
     // If you have enabled children of archived ancestors and you don't
     // want the ancestors to show up, you probably shouldn't be using
     // an accordion contro. in the first place
     // We need all of the ancestors to build an accordion successfully, in particular
     // since we often want a hidden parent to be the root. Give more thought to whether
     // we can do this just for the root
     $ancestors = aPageTable::getAncestorsInfo(array('info' => $this->getInfo(), 'ignore_permissions' => true));
     // Dump ancestors we don't care about
     $found = false;
     for ($i = 0; $i < count($ancestors); $i++) {
         if ($ancestors[$i]['slug'] === $root) {
             $rootLevel = $ancestors[$i]['level'];
             $ancestors = array_slice($ancestors, $i);
             $found = true;
             break;
         }
     }
     if (!$found) {
         // Active page is not a descendant of the root. Just return the children of the root.
         // This makes the accordion more useful when you are not yet under its root
         // I don't have a handy way to do this without cache issues in the table class yet so...
         // This is not a proper info structure but it will work for this job
         $rootInfo = Doctrine::getTable('aPage')->createQuery('p')->where('slug = ?', array($root))->execute(array(), Doctrine::HYDRATE_ARRAY);
         if (!count($rootInfo)) {
             throw new sfException("Root page of accordion does not exist!");
         }
         $rootInfo = $rootInfo[0];
         return aPageTable::getChildrenInfo(array('info' => $rootInfo));
     }
     $result = array();
     foreach ($ancestors as $ancestor) {
         if ($ancestor['level'] > $rootLevel && $livingOnly && $ancestor['archived']) {
             continue;
         }
         $lineage[] = $ancestor['id'];
         if ($ancestor['level'] == $rootLevel) {
             $result[] = array($ancestor);
         } else {
             // TODO: this is inefficient, come up with a way to call getPeerInfo for an
             // alternate ID without fetching that entire page
             $peers = aPageTable::retrieveBySlug($ancestor['slug'])->getPeerInfo($livingOnly);
             $result[] = $peers;
         }
     }
     // Current page peers level
     $result[] = $this->getPeerInfo($livingOnly);
     $lineage[] = $this->id;
     // Current page children level
     $result[] = $this->getChildrenInfo($livingOnly);
     // Now fix it up to be a properly nested array like that
     // returned by getTreeInfo(). On each pass take a reference
     // to the child that will own the children of the next pass
     $accordion = $result[0][0];
     $current =& $accordion;
     for ($i = 0; $i < count($result) - 1; $i++) {
         $current['children'] = $result[$i + 1];
         if ($i + 1 < count($lineage)) {
             // We've already started returning the kids as a flat array so
             // we need to scan for it unfortunately. This entire method could
             // use more attention to performance
             foreach ($current['children'] as &$child) {
                 if ($child['id'] == $lineage[$i + 1]) {
                     $current =& $child;
                     break;
                 }
             }
         }
     }
     // Don't return the home page itself, start with the tabs.
     // This is consistent with getTreeInfo() which should simplify implementations.
     // It's easy to add the home page in at a higher level if desired.
     return $accordion['children'];
 }
Esempio n. 10
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();
 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');
     }
 }
 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;
     }
 }
Esempio n. 13
0
 /**
  *
  * THIS METHOD WILL NOT WORK RELIABLY UNLESS THE ROUTING CACHE IS TURNED **OFF**.
  *
  * The routing cache defaults to off in new Symfony 1.3 and 1.4 projects because
  * it has found to hurt performance in most cases, sometimes quite severely. We do 
  * not currently enable it on any of our projects.
  * 
  * The routing cache does not take the desired engine page into account, so it will
  * return URLs targeting the wrong page. If you must use the routing cache,
  * design your projects to avoid the use of multiple engine pages for the
  * same engine module.
  *
  * This method sets a specific target engine page for any url_for, link_to, etc. 
  * calls invoking an engine route. If you have only one instance of a given engine 
  * in your site, you don't need to call this method. A link generated within that 
  * engine page will target the same engine page, and a link generated from anywhere 
  * else will target the first engine page for that engine module name found in 
  * the database. If you have more than one engine page for the same engine module 
  * name, and you care which one the link points to, call this method to specify 
  * that page. 
  *
  * A stack of target engine slugs is maintained for each engine module name.
  * This allows you to push a new engine page at the top of a partial or component
  * that potentially targets a different engine page than the template that
  * invoked it, and then pop that engine page at the end to ensure that any links
  * generated later in the calling template still target the original engine page.
  *
  * You can pass a page object or, for convenience, a page slug. The latter is useful
  * when targeting an engine page that is guaranteed to exist, such as /admin/media
  *
  * @param  aPage $page|string $page The target engine page for engine routes, or a page slug
  *
  */
 public static function pushTargetEnginePage($page, $engine = null)
 {
     if (!(is_object($page) && $page instanceof aPage)) {
         $slug = $page;
         if (is_null($engine)) {
             $page = aPageTable::retrieveBySlug($page);
             $engine = $page->engine;
         }
     } else {
         $slug = $page->slug;
         $engine = $page->engine;
     }
     self::$targetEnginePageSlugs[$engine][] = $slug;
 }
Esempio n. 14
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";
 }
Esempio n. 15
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')) {
Esempio n. 16
0
<?php

use_helper('a');
// This is a copy of apostrophePlugin/modules/a/templates/layout.php
// It also makes a fine site-wide layout, which gives you global slots on non-page templates
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<?php 
// If this page is an admin page we don't want to present normal navigation relative to it.
?>
	<?php 
$page = aTools::getCurrentNonAdminPage();
?>
  <?php 
$root = aPageTable::retrieveBySlug('/');
?>
<head>
	<?php 
include_http_metas();
?>
	<?php 
include_metas();
?>
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<?php 
include_title();
?>
	<?php 
// 1.3 and up don't do this automatically (no common filter)
?>