public function executeUpdate(sfWebRequest $request)
 {
     if ($this->getUser()->hasCredential('admin')) {
         $this->a_event = $this->getRoute()->getObject();
     } else {
         $this->a_event = Doctrine::getTable('aEvent')->findOneEditable($request->getParameter('id'), $this->getUser()->getGuardUser()->getId());
     }
     $this->forward404Unless($this->a_event);
     $this->form = $this->configuration->getForm($this->a_event);
     if ($request->isXmlHttpRequest()) {
         $this->setLayout(false);
         $response = array();
         $this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
         if ($this->form->isValid()) {
             $this->a_event = $this->form->save();
             //We need to recreate the form to handle the fact that it is not possible to change the value of a sfFormField
             $this->form = $this->configuration->getForm($this->a_event);
             $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $this->a_event)));
         }
         $response['errors'] = $this->form->getErrorSchema()->getErrors();
         aPageTable::queryWithTitles()->addWhere('page_id = ?', $this->a_event['page_id'])->execute();
         $response['aBlogPost'] = $this->a_event->toArray();
         $response['aBlogPost']['title'] = html_entity_decode($response['aBlogPost']['title'], ENT_COMPAT, 'UTF-8');
         $response['modified'] = $this->a_event->getLastModified();
         $response['time'] = aDate::time($this->a_event['updated_at']);
         //Any additional messages can go here
         $output = json_encode($response);
         $this->getResponse()->setHttpHeader("X-JSON", '(' . $output . ')');
         return sfView::HEADER_ONLY;
     } else {
         $this->processForm($request, $this->form);
     }
     $this->setTemplate('edit');
 }
 public function setup()
 {
     parent::setup();
     $this->setWidget('start_date', new aWidgetFormJQueryDate(array('image' => '/apostrophePlugin/images/a-icon-datepicker.png')));
     $this->setValidator('start_date', new sfValidatorDate(array('required' => true)));
     $this->setWidget('start_time', new aWidgetFormJQueryTime(array(), array('twenty-four-hour' => false, 'minutes-increment' => 30)));
     $this->setValidator('start_time', new sfValidatorTime(array('required' => false)));
     $this->setWidget('end_date', new aWidgetFormJQueryDate(array('image' => '/apostrophePlugin/images/a-icon-datepicker.png')));
     $this->setValidator('end_date', new sfValidatorDate(array('required' => true)));
     $this->setWidget('end_time', new aWidgetFormJQueryTime(array(), array('twenty-four-hour' => false, 'minutes-increment' => 30)));
     $this->setValidator('end_time', new sfValidatorTime(array('required' => false)));
     $this->setWidget('location', new sfWidgetFormTextarea());
     $this->setValidator('location', new sfValidatorString(array('required' => false)));
     $this->getWidgetSchema()->setDefault('start_date', date('Y/m/d'));
     $this->getWidgetSchema()->setDefault('end_date', date('Y/m/d'));
     $this->setWidget('all_day', new sfWidgetFormInputCheckbox(array('label' => 'All Day')));
     $this->setValidator('all_day', new sfValidatorBoolean());
     $start = strtotime(aDate::mysql($this->object->start_date));
     $end = strtotime(aDate::mysql($this->object->end_date));
     if (is_null($this->object->start_time) && is_null($this->object->end_time)) {
         $this->getWidgetSchema()->setDefault('all_day', true);
     }
     $this->widgetSchema->setNameFormat('a_blog_item[%s]');
     $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'validateEndDate'))));
 }
 protected function execute($args = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     // So we can play with app.yml settings from the application
     $context = sfContext::createInstance($this->configuration);
     $admin = Doctrine::getTable('sfGuardUser')->findOneByUsername('admin');
     for ($i = 0; $i < $options['amount']; $i++) {
         echo "Creating event " . ($i + 1) . " of " . $options['amount'] . "...\n";
         $post = new aEvent();
         $post->author_id = $admin->id;
         $post->status = 'published';
         $post->start_date = aDate::mysql(strtotime($i + 1 . ' days'));
         $post->start_time = date('H:i:s', rand(0, time()));
         $post->end_date = aDate::mysql(strtotime($i + rand(1, 14) . ' days'));
         $post->end_time = date('H:i:s', rand(0, time()));
         $post->excerpt = '';
         $post->location = "1168 E. Passyunk Avenue\nPhiladelphia PA 19147";
         $post->published_at = aDate::mysql(strtotime('-' . ($i + 1) . ' days'));
         $title = implode(' ', $this->getWords(mt_rand(5, 10), $options));
         $body = implode(' ', $this->getWords(mt_rand(20, 100), $options));
         $post->setTitle($title);
         $post->save();
         $slot = $post->Page->createSlot('aRichText');
         $slot->value = $body;
         $slot->save();
         $post->Page->newAreaVersion('blog-body', 'update', array('permid' => 1, 'slot' => $slot));
     }
 }
Esempio n. 4
0
 /**
  * 
  * Inserts a page from info array and updates the array with new fields
  * @param Array $info
  * @param string $title
  * @param int $parentId
  * @return array
  */
 public function insertPage(&$info, $title, $parentId)
 {
     if (isset($info['id'])) {
         throw new sfException("fastSavePage doesn't know how to handle an existing page");
     }
     if (substr($info['slug'], 0, 1) !== '/') {
         // Virtual pages must not be in the page tree!
         list($lft, $rgt, $level) = array(null, null, null);
     } else {
         // This page needs to be the last child of its parent
         if (is_null($parentId)) {
             list($lft, $rgt, $level) = array(0, 1, -1);
         } else {
             $result = $this->query('SELECT lft, rgt, level FROM a_page WHERE id = :id', array('id' => $parentId));
             list($lft, $rgt, $level) = array($result[0]['lft'], $result[0]['rgt'], $result[0]['level']);
         }
     }
     $this->query('UPDATE a_page SET rgt = rgt + 2 WHERE lft <= :lft AND rgt >= :rgt', array('lft' => $lft, 'rgt' => $rgt));
     $info['lft'] = $rgt;
     $info['rgt'] = $rgt + 1;
     $info['level'] = $level + 1;
     if (!isset($info['view_is_secure'])) {
         $info['view_is_secure'] = false;
     }
     if (!isset($info['archived']) || !$info['archived']) {
         $info['archived'] = false;
         if (!isset($info['published_at'])) {
             $info['published_at'] = aDate::mysql();
         }
     } else {
         // Can't be null
         $info['published_at'] = aDate::mysql();
     }
     if (!isset($info['engine'])) {
         $info['engine'] = null;
     }
     if (!isset($info['admin'])) {
         $info['admin'] = false;
     }
     if (!isset($info['template'])) {
         $info['template'] = 'default';
     }
     $this->query('INSERT INTO a_page (created_at, updated_at, slug, template, view_is_secure, archived, published_at, lft, rgt, level, engine, admin) VALUES (NOW(), NOW(), :slug, :template, :view_is_secure, :archived, :published_at, :lft, :rgt, :level, :engine, :admin)', $info);
     $info['id'] = $this->lastInsertId();
     $this->insertArea($info['id'], 'title', array(array('type' => 'aText', 'value' => $title)));
     return $info;
 }
Esempio n. 5
0
 public function addCategory($name, $blog_id, $type = 'posts')
 {
     $category = current($this->sql->query("SELECT * FROM a_category where name = :name", array('name' => $name)));
     if ($category) {
         $category_id = $category['id'];
     } else {
         $s = "INSERT INTO a_category (name, created_at, updated_at, slug) ";
         $s .= "VALUES (:name, :created_at, :updated_at, :slug)";
         $params = array('name' => $name, 'created_at' => aDate::mysql(), 'updated_at' => aDate::mysql(), 'slug' => aTools::slugify($name));
         $this->sql->query($s, $params);
         $category_id = $this->sql->lastInsertId();
     }
     $s = 'INSERT INTO a_blog_item_to_category (blog_item_id, category_id) VALUES(:blog_item_id, :category_id) ON DUPLICATE KEY UPDATE blog_item_id=blog_item_id';
     $parms = array('blog_item_id' => $blog_id, 'category_id' => $category_id);
     $this->sql->query($s, $parms);
     return $category_id;
 }
Esempio n. 6
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";
 }
    /**
     * @param  string $name        The element name
     * @param  string $value       The date displayed in this widget (sometimes already an array with hour and minute keys)
     * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
     * @param  array  $errors      An array of errors for the field
     *
     * @return string An HTML tag string
     *
     * @see sfWidgetForm
     */
    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        $prefix = $this->generateId($name);
        $image = '';
        if (false !== $this->getOption('image')) {
            // TODO: clock widget handling
        }
        $hourid = $this->generateId($name . '[hour]');
        $minid = $this->generateId($name . '[minute]');
        $s = '<div class="a-time-wrapper" id="' . $prefix . '-time">';
        $s .= '<span style="display: none">' . parent::render($name, $value, $attributes, $errors) . '</span>';
        $val = '';
        if (is_array($value)) {
            if (strlen($value['hour']) && strlen($value['minute'])) {
                $val = htmlspecialchars(aDate::time(sprintf("%02d:%02d:00", $value['hour'], $value['minute']), false));
            }
        } elseif (strlen($value)) {
            $val = htmlspecialchars(aDate::time($value, false), ENT_QUOTES);
        }
        $s .= "<input type='text' name='a-ignored' id='{$prefix}-ui' value='{$val}' class='" . (isset($attributes['class']) ? $attributes['class'] : '') . "'><img id='{$prefix}-ui-trigger' class='ui-timepicker-trigger' src='/apostrophePlugin/images/a-icon-time.png'/>";
        $s .= <<<EOM
<script>
\$(function() { 
  var hour;
  var min;
  var times = [ ];
  for (thour = 0; (thour < 24); thour++)
  {
    // Starting with 8am makes more sense for typical clients
    var hour = (thour + 8) % 24;
    for (min = 0; (min < 60); min += 30)
    {
      times.push(prettyTime(hour, min));
    }
  }
  \$('#{$prefix}-ui').autocomplete(times, { minChars: 0, selectFirst: false, max: 100 });
  // Double click on focus pops up autocomplete immediately
  \$('#{$prefix}-ui').focus(function() { \$(this).click(); \$(this).click() } ).next().click(function(event){
\t\tevent.preventDefault();
\t\t\$(this).prev().focus();
\t});
  \$('#{$prefix}-ui').blur(function() {
    var val = \$(this).val();
    var components = val.match(/(\\d\\d?)(:\\d\\d)?\\s*(am|pm)?/i);
    if (components)
    {
      var hour = components[1];
      var min = components[2];
      if (min)
      {
        min = min.substr(1);
      }
      if (!min)
      {
        min = '00';
      }
      if (min < 10)
      {
        min = '0' + Math.floor(min);
      }
      var ampm = components[3] ? components[3].toUpperCase() : false;
      if (!ampm)
      {
        if (hour >= 8)
        {
          ampm = 'AM';
        }
        else
        {
          ampm = 'PM';
        }
      }
      var formal = hour + ':' + min + ampm;
      \$(this).val(formal);
      if ((ampm === 'AM') && (hour == 12))
      {
        hour = 0;
      }
      if ((ampm === 'PM') && !(hour == 12))
      {
        // Careful: force numeric
        hour = Math.floor(hour) + 12;
      }
      \$('#{$hourid}').val(hour);
      \$('#{$minid}').val(min);
      // Something to bind to in other places
      \$(this).trigger('aTimeUpdated');
    }
    else
    {
      if (val.length)
      {
        alert("The time must be in hh:mm format, followed by AM or PM. Hint: click on the typeahead suggestions.");
        \$('#{$prefix}-ui').focus();
      }
      else
      {
        // NULL is often a valid value
        \$('#{$hourid}').val('');
        \$('#{$minid}').val('');
      }
    }
  });
  function prettyTime(hour, min)
  {
    var ampm = 'AM';
    phour = hour;
    if (hour >= 12)
    {
      ampm = 'PM';
    }
    if (hour >= 13)
    {
      phour -= 12;
    }
    if (phour == 0)
    {
      phour = 12;
    }
    pmin = min;
    if (min < 10)
    {
      pmin = '0' + Math.floor(min);
    }
    return phour + ':' + pmin + ampm;
  }

\t// General useability stuff that the original date widget was lacking because it was made by robots and not actual human beings
\t\$('#{$prefix}-ui-trigger').attr('title','Set A Time').hover(function(){
\t\t\$(this).fadeTo(0,.5);
\t},function(){
\t\t\$(this).fadeTo(0,1);
\t});
});
</script>
</div>

EOM;
        return $s;
    }
Esempio n. 8
0
<span class="a-media-is-secure"></span><?php 
}
?>
	</h3>
</li>

<li class="a-media-item-description"><?php 
echo $mediaItem->getDescription();
?>
</li>
<li class="a-media-item-dimensions a-media-item-meta"><?php 
echo __('<span>Original Dimensions:</span> %width%x%height%', array('%width%' => $mediaItem->getWidth(), '%height%' => $mediaItem->getHeight()), 'apostrophe');
?>
</li>
<li class="a-media-item-created-at a-media-item-meta"><?php 
echo __('<span>Uploaded:</span> %date%', array('%date%' => aDate::pretty($mediaItem->getCreatedAt())), 'apostrophe');
?>
</li>
<li class="a-media-item-credit a-media-item-meta"><?php 
echo __('<span>Credit:</span> %credit%', array('%credit%' => htmlspecialchars($mediaItem->getCredit())), 'apostrophe');
?>
</li>
<li class="a-media-item-categories a-media-item-meta"><?php 
echo __('<span>Categories:</span> %categories%', array('%categories%' => get_partial('aMedia/showCategories', array('categories' => $mediaItem->getMediaCategories()))), 'apostrophe');
?>
</li>
<li class="a-media-item-tags a-media-item-meta"><?php 
echo __('<span>Tags:</span> %tags%', array('%tags%' => get_partial('aMedia/showTags', array('tags' => $mediaItem->getTags()))), 'apostrophe');
?>
</li>
$options = isset($options) ? $sf_data->getRaw('options') : null;
// Yes, catching exceptions in templates is unusual, but if there is no blog page on
// the site it is not possible to generate some of the links. That can kill the home page,
// so we must address it. Someday it might be better to do less in the template and
// generate the various URLs in component code rather than partial code
try {
    ?>

<h3 class="a-blog-item-title"><?php 
    echo link_to($aBlogPost['title'], 'a_blog_post', $aBlogPost);
    ?>
</h3>

<ul class="a-blog-item-meta">
	<li class="date"><?php 
    echo aDate::long($aBlogPost['published_at']);
    ?>
</li>
	<li class="author"><?php 
    echo __('Posted By:', array(), 'apostrophe');
    ?>
 <?php 
    echo $aBlogPost->getAuthor();
    ?>
</li>   			
</ul>

<?php 
    if ($options['maxImages'] && $aBlogPost->hasMedia()) {
        ?>
	<div class="a-blog-item-media">
            $prevLabel = aDate::pretty($params['prev']['year'] . '-' . $params['prev']['month'] . '-' . $params['prev']['day']);
            ?>
	    <?php 
            $nextLabel = aDate::pretty($params['next']['year'] . '-' . $params['next']['month'] . '-' . $params['next']['day']);
            ?>
	  <?php 
        } elseif ($sf_params->get('month')) {
            ?>
	    <?php 
            $prevLabel = aDate::pretty($params['prev']['year'] . '-' . $params['prev']['month'] . '-01');
            ?>
	    <?php 
            $prevLabel = preg_replace('/\\s+\\d+/', '', $prevLabel);
            ?>
	    <?php 
            $nextLabel = aDate::pretty($params['next']['year'] . '-' . $params['next']['month'] . '-01');
            ?>
	    <?php 
            $nextLabel = preg_replace('/\\s+\\d+/', '', $nextLabel);
            ?>
	  <?php 
        } else {
            ?>
	    <?php 
            $prevLabel = $params['prev']['year'];
            ?>
	    <?php 
            $nextLabel = $params['next']['year'];
            ?>
	  <?php 
        }
 public function configurePublication()
 {
     $choices = array();
     $o = $this->getObject();
     $now = aDate::mysql();
     if ($o->status === 'draft') {
         $choices = array('draft' => 'Draft', 'publish' => 'Publish', 'schedule' => 'Schedule');
         $default = 'draft';
     } elseif ($o->status === 'published' && $o->published_at <= $now) {
         $choices = array('nochange' => 'Published', 'draft' => 'Draft', 'schedule' => 'Schedule');
         $default = 'nochange';
     } elseif ($o->status === 'published' && $o->published_at > $now) {
         $choices = array('schedule' => 'Scheduled', 'publish' => 'Publish', 'draft' => 'Draft');
         $default = 'schedule';
     }
     $this->setWidget('publication', new sfWidgetFormChoice(array('choices' => $choices, 'default' => $default)));
     $this->setValidator('publication', new sfValidatorChoice(array('choices' => array_keys($choices))));
 }
Esempio n. 12
0
    ?>
	<td class="date">
	  <?php 
    // Localize the date. We used to do: "j M Y - g:iA"
    ?>
	  <?php 
    // Avoid a crash in some versions of PHP when date columns
    ?>
	  <?php 
    // are null or all zeroes
    ?>
	  <?php 
    if ($data['created_at'] > '0000-00-00 00:00:00') {
        ?>
		  <?php 
        echo aDate::pretty($data['created_at']) . ' ' . aDate::time($data['created_at']);
        ?>
		<?php 
    }
    ?>
	</td>
	<td class="editor">
		<?php 
    echo $data['author'];
    ?>
	</td>
	<td class="preview">
		<?php 
    echo $data['diff'];
    ?>
	</td>
Esempio n. 13
0
  <li class="a-media-item-description"><?php 
echo $mediaItem->getDescription();
?>
</li>
	<li class="a-media-item-dimensions a-media-item-meta"><span><?php 
echo __('Original Dimensions:', null, 'apostrophe');
?>
</span> <?php 
echo __('%width%x%height%', array('%width%' => $mediaItem->getWidth(), '%height%' => $mediaItem->getHeight()), 'apostrophe');
?>
</li>
  <li class="a-media-item-created-at a-media-item-meta"><span><?php 
echo __('Uploaded:', null, 'apostrophe');
?>
</span> <?php 
echo aDate::pretty($mediaItem->getCreatedAt());
?>
</li>
  <li class="a-media-item-credit a-media-item-meta"><span><?php 
echo __('Credit:', null, 'apostrophe');
?>
</span> <?php 
echo htmlspecialchars($mediaItem->getCredit());
?>
</li>
  <li class="a-media-item-categories a-media-item-meta"><span><?php 
echo __('Categories:', null, 'apostrophe');
?>
</span> <?php 
include_partial('aMedia/showCategories', array('categories' => $mediaItem->getMediaCategories()));
?>
 public function getVcalPublishedAtDateTime()
 {
     $when = aDate::normalize($this->getPublishedAt());
     return gmdate('Ymd\\THis', $when) . 'Z';
 }
?>
</h2>

<ul class="a-blog-item-meta">
  <li class="start-day"><?php 
echo aDate::dayAndTime($aEvent->getStartDate());
?>
</li>
  <li class="start-date"><?php 
echo aDate::dayMonthYear($aEvent->getStartDate());
if ($aEvent->getStartDate() != $aEvent->getEndDate()) {
    ?>
 &mdash;<?php 
}
?>
</li>
	<?php 
if ($aEvent->getStartDate() != $aEvent->getEndDate()) {
    ?>
		<li class="end-day"><?php 
    echo aDate::dayAndTime($aEvent->getEndDate());
    ?>
</li>
	  <li class="end-date"><?php 
    echo aDate::dayMonthYear($aEvent->getEndDate());
    ?>
</li>
	<?php 
}
?>
</ul>
Esempio n. 16
0
</a>
			<?php 
} else {
    ?>
				<?php 
    echo $feedItem->getTitle();
    ?>
			<?php 
}
?>
		</li>
    <?php 
$date = $feedItem->getPubDate();
?>
    <?php 
if ($date) {
    ?>
      <li class="date"><?php 
    echo $dateFormat ? date($dateFormat, $date) : aDate::pretty($date) . ' ' . aDate::time($date);
    ?>
</li>
    <?php 
}
?>
    <li class="description"><?php 
echo auto_link_text(aHtml::simplify($feedItem->getDescription(), $markup, false, isset($attributes) ? $attributes : false, isset($styles) ? $styles : false));
?>
</li>
  </ul>
</li>
 public function getPubdate()
 {
     return aDate::normalize($this->published_at);
     return $this->published_at;
 }
Esempio n. 18
0
 /**
  * DOCUMENT ME
  * @param mixed $values
  */
 public function updateObject($values = null)
 {
     if (is_null($values)) {
         $values = $this->getValues();
     }
     $oldSlug = $this->getObject()->slug;
     if (!isset($values['slug']) && isset($values['realtitle']) && $oldSlug !== '/') {
         // If they can manually edit the title but not the slug, we need to autogenerate and
         // autoupdate the slug so they have reasonable options to avoid collisions
         $oldSlug = $this->getObject()->slug;
         if (!strlen($oldSlug)) {
             // New page, provide a starter slug to replace
             $oldSlug = $this->parent->slug . '/';
         }
         $newSlug = preg_replace('|/[^/]*$|', '/' . aTools::slugify($values['realtitle'], false, false), $oldSlug);
         $suffix = '';
         $n = 0;
         while (true) {
             $values['slug'] = $newSlug . $suffix;
             if ($values['slug'] === $oldSlug) {
                 break;
             }
             $existing = Doctrine::getTable('aPage')->findOneBySlug($values['slug']);
             if (!$existing) {
                 break;
             }
             $suffix = '-' . $n;
             $n++;
         }
         $this->getObject()->slug = $values['slug'];
     }
     // Slashes break routes in most server configs. Do NOT force case of tags.
     $values['tags'] = str_replace('/', '-', isset($values['tags']) ? $values['tags'] : '');
     $object = parent::updateObject($values);
     // Check for cascading operations
     if ($this->getValue('cascade_archived')) {
         $q = Doctrine::getTable('aPage')->createQuery()->update()->where('lft > ? and rgt < ?', array($object->getLft(), $object->getRgt()));
         if ($this->getValue('cascade_archived')) {
             $q->set('archived', '?', $object->getArchived());
         }
         $q->execute();
     }
     if (isset($values['joinedtemplate'])) {
         $template = $values['joinedtemplate'];
         // $templates = aTools::getTemplates();
         list($engine, $etemplate) = preg_split('/:/', $template);
         if ($engine === 'a') {
             $object->engine = null;
         } else {
             $object->engine = $engine;
         }
         $object->template = $etemplate;
     }
     // On manual change of slug, set up a redirect from the old slug,
     // and notify child pages so they can update their slugs if they are
     // not already deliberately different
     if ($object->slug !== $oldSlug) {
         Doctrine::getTable('aRedirect')->update($oldSlug, $object);
         $children = $object->getChildren();
         foreach ($children as $child) {
             $child->updateParentSlug($oldSlug, $object->slug);
         }
     }
     if (isset($object->engine) && !strlen($object->engine)) {
         // Store it as null for plain ol' executeShow page templating
         $object->engine = null;
     }
     // A new page must be added as a child of its parent
     if ($this->parent) {
         $this->getObject()->getNode()->insertAsFirstChildOf($this->parent);
     }
     $jvalues = json_decode($this->getValue('view_groups'), true);
     // Most custom permissions are saved in separate methods called from save()
     // after the object exists. However the "Editors + Guests" group is a special
     // case which really maps to everyone who has the 'view_locked' permission, so
     // we have to scan for it in the list of groups
     foreach ($jvalues as $value) {
         if ($value['id'] === 'editors_and_guests') {
             // Editors + Guests special case
             $object->view_guest = $value['selected'] && $value['selected'] !== 'remove';
         }
     }
     // Check for cascading operations
     if ($this->getValue('cascade_archived')) {
         $q = Doctrine::getTable('aPage')->createQuery()->update()->where('lft > ? and rgt < ?', array($object->getLft(), $object->getRgt()));
         $q->set('archived', '?', $object->getArchived());
         $q->execute();
     }
     if ($values['view_options'] === 'public') {
         $object->view_admin_lock = false;
         $object->view_is_secure = false;
     } elseif ($values['view_options'] === 'login') {
         $object->view_admin_lock = false;
         $object->view_is_secure = true;
     } elseif ($values['view_options'] === 'admin') {
         $object->view_admin_lock = true;
         $object->view_is_secure = true;
     }
     if ($this->getValue('view_options_apply_to_subpages')) {
         $q = Doctrine::getTable('aPage')->createQuery()->update()->where('lft > ? and rgt < ?', array($object->getLft(), $object->getRgt()));
         $q->set('view_admin_lock', '?', $object->view_admin_lock);
         $q->set('view_is_secure', '?', $object->view_is_secure);
         $q->set('view_guest', '?', $object->view_guest);
         $q->execute();
     }
     // We have no UI for scheduling publication yet, so make sure
     // we set the publication date when we save with archived false
     if (!$values['archived']) {
         $object->setPublishedAt(aDate::mysql());
     }
     // Has to be done on shutdown so it comes after the in-memory cache of
     // sfFileCache copies itself back to disk, which otherwise overwrites
     // our attempt to invalidate the routing cache [groan]
     register_shutdown_function(array($this, 'invalidateRoutingCache'));
 }
Esempio n. 19
0
<?php

$startDate = aDate::dayMonthYear($aEvent->getStartDate());
$endDate = aDate::dayMonthYear($aEvent->getEndDate());
$startTime = aDate::time($aEvent->getStartDate());
$endTime = aDate::time($aEvent->getEndDate());
?>

<ul class="a-blog-item-meta">
  <li class="start-date"><?php 
echo $startDate;
?>
</li>
	<?php 
if ($startDate == $endDate) {
    ?>
		<?php 
    if ($startTime != $endTime) {
        ?>
	  <li class="event-time"><?php 
        echo $startTime;
        ?>
 &ndash; <?php 
        echo $endTime;
        ?>
</li>
		<?php 
    }
    ?>
	<?php 
} else {
<?php

if ($sf_params->get('module') != 'aBlogAdmin') {
    ?>
<h3 class="a-blog-item-title">
  <?php 
    echo link_to($a_blog_post->getTitle(), 'a_blog_post', $a_blog_post);
    ?>
</h3>
<ul class="a-blog-item-meta">
  <li class="date"><?php 
    echo aDate::pretty($a_blog_post['published_at']);
    ?>
</li>
  <li class="author"><?php 
    echo __('Posted By:', array(), 'apostrophe_blog');
    ?>
 <?php 
    echo $a_blog_post->getAuthor();
    ?>
</li>   
</ul>
<?php 
}
?>

<?php 
a_area('blog-body', array('edit' => $edit, 'toolbar' => 'basic', 'slug' => $a_blog_post->Page->slug, 'allowed_types' => array('aRichText', 'aSlideshow', 'aVideo', 'aPDF'), 'type_options' => array('aRichText' => array('tool' => 'Main'), 'aSlideshow' => array("width" => 480, "flexHeight" => true, 'resizeType' => 's', 'constraints' => array('minimum-width' => 480)), 'aVideo' => array('width' => 480, 'flexHeight' => true, 'resizeType' => 's'), 'aPDF' => array('width' => 480, 'flexHeight' => true, 'resizeType' => 's'))));
?>

<?php 
	</ul>
	<?php 
    }
    ?>
	<?php 
}
?>


  <h3 class="a-blog-item-title"><?php 
echo link_to($aBlogPost['title'], 'a_blog_post', $aBlogPost);
?>
</h3>
  <ul class="a-blog-item-meta">
		<li class="date"><?php 
echo aDate::pretty($aBlogPost['published_at']);
?>
</li>
  </ul>

	<?php 
if ($options['maxImages'] && $aBlogPost->hasMedia()) {
    ?>
		<div class="a-blog-item-media">
		<?php 
    include_component('aSlideshowSlot', 'slideshow', array('items' => $aBlogPost->getMediaForArea('blog-body', 'image', $options['maxImages']), 'id' => 'a-slideshow-blogitem-' . $aBlogPost['id'], 'options' => $options['slideshowOptions']));
    ?>
		</div>
	<?php 
}
?>