/**
  * @see sfWebRequest
  */
 public function checkCSRFProtection()
 {
     try {
         parent::checkCSRFProtection();
     } catch (sfValidatorErrorSchema $e) {
         // retry checking for using sfForm (just for BC)
         $form = new sfForm();
         $form->bind($form->isCSRFProtected() ? array($form->getCSRFFieldName() => $this->getParameter($form->getCSRFFieldName())) : array());
         if (!$form->isValid()) {
             throw $form->getErrorSchema();
         }
     }
 }
Example #2
0
 public function executeSave($request)
 {
     $member = Doctrine::getTable('Member')->find($request->getParameter('member_id', 0));
     $this->forward404Unless($member);
     $form = new sfForm();
     $token = $request->getParameter($form->getCSRFFieldName());
     $this->forward404Unless($member->getConfig('paint_token') === $token);
     $member->setConfig('paint_is_valid', true);
     $member->setConfig('paint_rawdata', base64_encode(RawSPainter::getPostRawData()));
     $url = $member->getConfig('paint_url');
     exit('URL:' . $url);
 }
 public function checkCSRFProtection()
 {
     $form = new sfForm();
     $form->bind($form->isCSRFProtected() ? array($form->getCSRFFieldName() => $this->getParameter($form->getCSRFFieldName())) : array());
     if (!$form->isValid()) {
         throw $form->getErrorSchema();
     }
 }
Example #4
0
echo __('Delete profile entry');
?>
</h2>
<p><?php 
echo __('Do you want to delete this anyway?');
?>
</p>
<p><?php 
echo __('※All the member\'s data in this entry will be lost.');
?>
</p>
<form action="<?php 
echo url_for('profile/delete?id=' . $profile->getId());
?>
" method="post">
<?php 
$formCSRF = new sfForm();
?>
<input type="hidden" name="<?php 
echo $formCSRF->getCSRFFieldName();
?>
" value="<?php 
echo $formCSRF->getCSRFToken();
?>
" />
<input type="submit" value="<?php 
echo __('Delete');
?>
" />
</form>
Example #5
0
function button_link_to($title, $action, $target = "_self")
{
    $form = new sfForm();
    return sprintf('<form action="%s" method="post" target="%s">' . '<input type="hidden" name="%s" value="%s" />' . '<input type="submit" value="%s" />' . '</form>', url_for($action), $target, $form->getCSRFFieldName(), $form->getCSRFToken(), __($title));
}
 /**
  * for now, CSRF field are removed from functionnal test generation
  * until there is a way to get this value easily
  *
  * @param <type> $vars
  */
 public function fixCSRF(&$vars)
 {
     $name = sfForm::getCSRFFieldName();
     if (isset($vars[$name])) {
         unset($vars[$name]);
     }
     foreach ($vars as $name => $var) {
         if (is_array($var)) {
             $vars[$name] = $this->fixCSRF($var);
         }
     }
     return $vars;
 }
Example #7
0
function _method_javascript_function($method)
{
    $function = "var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'post'; f.action = this.href;";
    if ('post' != strtolower($method)) {
        $function .= "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); ";
        $function .= sprintf("m.setAttribute('name', 'sf_method'); m.setAttribute('value', '%s'); f.appendChild(m);", strtolower($method));
    }
    // CSRF protection
    $form = new sfForm();
    if ($form->isCSRFProtected()) {
        $function .= "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); ";
        $function .= sprintf("m.setAttribute('name', '%s'); m.setAttribute('value', '%s'); f.appendChild(m);", $form->getCSRFFieldName(), $form->getCSRFToken());
    }
    $function .= "f.submit();";
    return $function;
}
Example #8
0
/**
 * Returns the javascript needed for a remote function.
 * Takes the same arguments as 'link_to_remote()'.
 *
 * Example:
 *   <select id="options" onchange="<?php echo remote_function(array('update' => 'options', 'url' => '@update_options')) ?>">
 *     <option value="0">Hello</option>
 *     <option value="1">World</option>
 *   </select>
 */
function jq_remote_function($options)
{
    // Defining elements to update
    if (isset($options['update']) && is_array($options['update'])) {
        // On success, update the element with returned data
        if (isset($options['update']['success'])) {
            $update_success = "#" . $options['update']['success'];
        }
        // On failure, execute a client-side function
        if (isset($options['update']['failure'])) {
            $update_failure = $options['update']['failure'];
        }
    } else {
        if (isset($options['update'])) {
            $update_success = "#" . $options['update'];
        }
    }
    // Update method
    $updateMethod = _update_method(isset($options['position']) ? $options['position'] : '');
    // Callbacks
    if (isset($options['loading'])) {
        $callback_loading = $options['loading'];
    }
    if (isset($options['complete'])) {
        $callback_complete = $options['complete'];
    }
    if (isset($options['success'])) {
        $callback_success = $options['success'];
    }
    $execute = 'false';
    if (isset($options['script']) && $options['script'] == '1') {
        $execute = 'true';
    }
    // Data Type
    if (isset($options['dataType'])) {
        $dataType = $options['dataType'];
    } elseif ($execute) {
        $dataType = 'html';
    } else {
        $dataType = 'text';
    }
    // POST or GET ?
    $method = 'POST';
    if (isset($options['method']) && strtoupper($options['method']) == 'GET') {
        $method = $options['method'];
    }
    // async or sync, async is default
    if (isset($options['type']) && $options['type'] == 'synchronous') {
        $type = 'false';
    }
    // Is it a form submitting
    if (isset($options['form'])) {
        $formData = 'jQuery(this).serialize()';
    } elseif (isset($options['submit'])) {
        $formData = '{\'#' . $options['submit'] . '\'}.serialize()';
    } elseif (isset($options['with'])) {
        $formData = $options['with'];
    } elseif (isset($options['csrf']) && $options['csrf'] == '1') {
        $form = new sfForm();
        if ($form->isCSRFProtected()) {
            $formData = '{' . $form->getCSRFFieldName() . ': \'' . $form->getCSRFToken() . '\'}';
        }
    }
    // build the function
    $function = "jQuery.ajax({";
    $function .= 'type:\'' . $method . '\'';
    $function .= ',dataType:\'' . $dataType . '\'';
    if (isset($type)) {
        $function .= ',async:' . $type;
    }
    if (isset($formData)) {
        $function .= ',data:' . $formData;
    }
    if (isset($update_success) and !isset($callback_success)) {
        $function .= ',success:function(data, textStatus){jQuery(\'' . $update_success . '\').' . $updateMethod . '(data);}';
    }
    if (isset($update_failure)) {
        $function .= ',error:function(XMLHttpRequest, textStatus, errorThrown){' . $update_failure . '}';
    }
    if (isset($callback_loading)) {
        $function .= ',beforeSend:function(XMLHttpRequest){' . $callback_loading . '}';
    }
    if (isset($callback_complete)) {
        $function .= ',complete:function(XMLHttpRequest, textStatus){' . $callback_complete . '}';
    }
    if (isset($callback_success)) {
        $function .= ',success:function(data, textStatus){' . $callback_success . '}';
    }
    $function .= ',url:\'' . url_for($options['url']) . '\'';
    $function .= '})';
    if (isset($options['before'])) {
        $function = $options['before'] . '; ' . $function;
    }
    if (isset($options['after'])) {
        $function = $function . '; ' . $options['after'];
    }
    if (isset($options['condition'])) {
        $function = 'if (' . $options['condition'] . ') { ' . $function . '; }';
    }
    if (isset($options['confirm'])) {
        $function = "if (confirm('" . escape_javascript($options['confirm']) . "')) { {$function}; }";
        if (isset($options['cancel'])) {
            $function = $function . ' else { ' . $options['cancel'] . ' }';
        }
    }
    return $function;
}
Example #9
0
$article->addCSRFProtection(null);
$author->embedForm('company', $company);
$article->embedForm('author', $author);
$v = $article->getValidatorSchema();
$w = $article->getWidgetSchema();
$d = $article->getDefaults();
$f = $article->getEmbeddedForms();
$w->setNameFormat('article[%s]');
$t->ok($v['author'] instanceof sfValidatorPass, '->embedForm() set validator pass');
// ignore parents in comparison
$w['author']['first_name']->setParent(null);
$author_widget_schema['first_name']->setParent(null);
$t->ok($w['author']['first_name'] == $author_widget_schema['first_name'], '->embedForm() embeds the widget schema');
$t->is($d['author']['first_name'], 'Fabien', '->embedForm() merges default values from the embedded form');
$t->is($w['author'][sfForm::getCSRFFieldName()], null, '->embedForm() removes the CSRF token for the embedded form');
$t->ok(!isset($f['author'][sfForm::getCSRFFieldName()]), '->embedForm() removes the CSRF token for the embedded form');
$t->is($w['author']->generateName('first_name'), 'article[author][first_name]', '->embedForm() changes the name format to reflect the embedding');
$t->is($w['author']['company']->generateName('name'), 'article[author][company][name]', '->embedForm() changes the name format to reflect the embedding');
// tests for ticket #56
$t->ok($author->getValidator('company') == $company_validator_schema, '->getValidator() gets a validator schema for an embedded form');
try {
    $author->setValidator('company', new sfValidatorPass());
    $t->fail('"sfForm" Trying to set a validator for an embedded form field throws a LogicException');
} catch (LogicException $e) {
    $t->pass('"sfForm" Trying to set a validator for an embedded form field throws a LogicException');
}
// tests for ticket #4754
$f1 = new TestForm1();
$f2 = new TestForm2();
$f1->embedForm('f2', $f2);
$t->is($f1['f2']['c']->render(), '<textarea rows="4" cols="30" name="f2[c]" id="f2_c"></textarea>', '->embedForm() generates a correct id in embedded form fields');
 /**
  * Calls a request to a uri.
  *
  * @param string $uri          The URI to fetch
  * @param string $method       The request method
  * @param array  $parameters   The Request parameters
  * @param bool   $changeStack  Change the browser history stack?
  *
  * @return sfBrowserBase
  */
 public function call($uri, $method = 'get', $parameters = array(), $changeStack = true)
 {
     // check that the previous call() hasn't returned an uncatched exception
     $this->checkCurrentExceptionIsEmpty();
     $uri = $this->fixUri($uri);
     // add uri to the stack
     if ($changeStack) {
         $this->stack = array_slice($this->stack, 0, $this->stackPosition + 1);
         $this->stack[] = array('uri' => $uri, 'method' => $method, 'parameters' => $parameters);
         $this->stackPosition = count($this->stack) - 1;
     }
     list($path, $queryString) = false !== ($pos = strpos($uri, '?')) ? array(substr($uri, 0, $pos), substr($uri, $pos + 1)) : array($uri, '');
     $queryString = html_entity_decode($queryString);
     // remove anchor
     $path = preg_replace('/#.*/', '', $path);
     // removes all fields from previous request
     $this->fields = array();
     // prepare the request object
     $_SERVER = $this->defaultServerArray;
     $_SERVER['HTTP_HOST'] = $this->hostname;
     $_SERVER['SERVER_NAME'] = $_SERVER['HTTP_HOST'];
     $_SERVER['SERVER_PORT'] = 80;
     $_SERVER['HTTP_USER_AGENT'] = 'PHP5/CLI';
     $_SERVER['REMOTE_ADDR'] = $this->remote;
     $_SERVER['REQUEST_METHOD'] = strtoupper($method);
     $_SERVER['PATH_INFO'] = $path;
     $_SERVER['REQUEST_URI'] = '/uploadFiles.php' . $uri;
     $_SERVER['SCRIPT_NAME'] = '/uploadFiles.php';
     $_SERVER['SCRIPT_FILENAME'] = '/uploadFiles.php';
     $_SERVER['QUERY_STRING'] = $queryString;
     if ($this->stackPosition >= 1) {
         $_SERVER['HTTP_REFERER'] = sprintf('http%s://%s%s', isset($this->defaultServerArray['HTTPS']) ? 's' : '', $this->hostname, $this->stack[$this->stackPosition - 1]['uri']);
     }
     foreach ($this->vars as $key => $value) {
         $_SERVER[strtoupper($key)] = $value;
     }
     foreach ($this->headers as $header => $value) {
         $_SERVER['HTTP_' . strtoupper(str_replace('-', '_', $header))] = $value;
     }
     $this->headers = array();
     // request parameters
     $_GET = $_POST = array();
     if (in_array(strtoupper($method), array('POST', 'DELETE', 'PUT'))) {
         if (isset($parameters['_with_csrf']) && $parameters['_with_csrf']) {
             unset($parameters['_with_csrf']);
             $form = new sfForm();
             $parameters[$form->getCSRFFieldName()] = $form->getCSRFToken();
         }
         $_POST = $parameters;
     }
     if (strtoupper($method) == 'GET') {
         $_GET = $parameters;
     }
     // handle input type="file" fields
     $_FILES = array();
     if (count($this->files)) {
         $_FILES = $this->files;
     }
     $this->files = array();
     parse_str($queryString, $qs);
     if (is_array($qs)) {
         $_GET = array_merge($qs, $_GET);
     }
     // expire cookies
     $cookies = $this->cookieJar;
     foreach ($cookies as $name => $cookie) {
         if ($cookie['expire'] && $cookie['expire'] < time()) {
             unset($this->cookieJar[$name]);
         }
     }
     // restore cookies
     $_COOKIE = array();
     foreach ($this->cookieJar as $name => $cookie) {
         $_COOKIE[$name] = $cookie['value'];
     }
     $this->doCall();
     $response = $this->getResponse();
     // save cookies
     foreach ($response->getCookies() as $name => $cookie) {
         // FIXME: deal with path, secure, ...
         $this->cookieJar[$name] = $cookie;
     }
     // support for the ETag header
     if ($etag = $response->getHttpHeader('Etag')) {
         $this->vars['HTTP_IF_NONE_MATCH'] = $etag;
     } else {
         unset($this->vars['HTTP_IF_NONE_MATCH']);
     }
     // support for the last modified header
     if ($lastModified = $response->getHttpHeader('Last-Modified')) {
         $this->vars['HTTP_IF_MODIFIED_SINCE'] = $lastModified;
     } else {
         unset($this->vars['HTTP_IF_MODIFIED_SINCE']);
     }
     // for HTML/XML content, create a DOM and sfDomCssSelector objects for the response content
     $this->dom = null;
     $this->domCssSelector = null;
     if (preg_match('/(x|ht)ml/i', $response->getContentType(), $matches)) {
         $this->dom = new DomDocument('1.0', $response->getCharset());
         $this->dom->validateOnParse = true;
         if ('x' == $matches[1]) {
             @$this->dom->loadXML($response->getContent());
         } else {
             @$this->dom->loadHTML($response->getContent());
         }
         $this->domCssSelector = new sfDomCssSelector($this->dom);
     }
     return $this;
 }
 protected function prepareDataForForm(sfForm $form, $arguments = array(), $options = array())
 {
     $data = array('user_id' => $form->getObject()->getUserId(), 'name' => $arguments['name'], 'vehicles_list' => $this->parseVehicles($arguments['vehicles']), 'date_range' => array('from' => isset($options['date_from']) ? $options['date_from'] : null, 'to' => isset($options['date_to']) ? $options['date_to'] : null), 'kilometers_range' => array('from' => isset($options['kilometers_from']) ? $options['kilometers_from'] : null, 'to' => isset($options['kilometers_to']) ? $options['kilometers_to'] : null), $form->getCSRFFieldName() => $form->getCSRFToken());
     return $data;
 }
 /**
  * Executes blacklistDelete action
  *
  * @param sfRequest $request A request object
  */
 public function executeBlacklistDelete(sfWebRequest $request)
 {
     $this->blacklist = Doctrine::getTable('Blacklist')->find($request->getParameter('id'));
     $this->forward404Unless($this->blacklist);
     $this->form = new sfForm();
     if ($request->isMethod(sfWebRequest::POST)) {
         $field = sfForm::getCSRFFieldName();
         $this->form->bind(array($field => $request->getParameter($field)));
         if ($this->form->isValid()) {
             $this->blacklist->delete();
             $this->redirect('member/blacklist');
         }
     }
     return sfView::SUCCESS;
 }
?>
        </th>
        <td>
          <?php 
echo $createFolderForm['parent_folder'];
?>
<br />
        </td>
      </tr>    </table>
    <input type="submit" name="create" value="<?php 
echo __('Create', null, 'sfAsset');
?>
"/>
  </div>
<?php 
if (isset($createFolderForm[sfForm::getCSRFFieldName()])) {
    echo $createFolderForm['_csrf_token'];
}
?>
</form>
    
<?php 
if (!$folder->getNode()->isRoot()) {
    ?>

  <form action="<?php 
    echo url_for('sfAsset/renameFolder?id=' . $folder->getId());
    ?>
" method="POST">
    <label for="new_directory">
      <?php 
function _get_json_data_token()
{
    // CSRF protection
    $form = new sfForm();
    if ($form->isCSRFProtected()) {
        $token = sprintf("', %s: '%s", $form->getCSRFFieldName(), $form->getCSRFToken());
        return $token;
    } else {
        return '';
    }
}
color:#0000FF;
font-size:20px;
font-weight:bold;
margin:10px;
padding:10px;
text-align:center;
" id="plugin_user">
<span id="plugin_user_count"><?php 
echo $package->countUsers();
?>
</span><br /><span>users</span>
<p style="margin-top: 10px; text-align: center; font-size: 9px; color: #000;">
<?php 
if ($package->isAllowed($sf_user->getRawValue()->getMember(), 'countUser')) {
    $form = new sfForm();
    $_ajax_parameter = '"' . sfForm::getCSRFFieldName() . '=' . $form->getDefault(sfForm::getCSRFFieldName()) . '"';
    echo link_to_remote(__('I don\'t use this plugin'), array('url' => '@package_use?name=' . $package->name, 'complete' => 'updateUser(request)', '404' => 'alert("' . __('CSRF attack detected.') . '")', 'with' => $_ajax_parameter), array('id' => 'package_unuse_link', 'style' => 'display:' . ($package->isUser($sf_user->getMemberId()) ? 'inline' : 'none')));
    echo link_to_remote(__('I use this plugin'), array('url' => '@package_use?name=' . $package->name, 'complete' => 'updateUser(request)', '404' => 'alert("' . __('CSRF attack detected.') . '")', 'with' => $_ajax_parameter), array('id' => 'package_use_link', 'style' => 'display:' . (!$package->isUser($sf_user->getMemberId()) ? 'inline' : 'none')));
} else {
    echo __('Please login to vote for this plugin');
}
?>
</p>
</div>
<?php 
echo javascript_tag('
function updateUser(ajax)
{
  var json = ajax.responseJSON;

  Element.update("plugin_user_count", json[0]);
Example #16
0
// ->embedFormForEach()
$t->diag('->embedFormForEach()');
$article->embedFormForEach('authors', $author, 2, null, null, array('id_format' => '%s_id'), array('class' => 'embedded'));
$v = $article->getValidatorSchema();
$w = $article->getWidgetSchema();
$d = $article->getDefaults();
$w->setNameFormat('article[%s]');
for ($i = 0; $i < 2; $i++) {
    $t->ok($v['authors'][$i]['first_name'] == $author_validator_schema['first_name'], '->embedFormForEach() embeds the validator schema');
    // ignore the parents in comparison
    $w['authors'][$i]['first_name']->setParent(null);
    $author_widget_schema['first_name']->setParent(null);
    $t->ok($w['authors'][$i]['first_name'] == $author_widget_schema['first_name'], '->embedFormForEach() embeds the widget schema');
    $t->is($d['authors'][$i]['first_name'], 'Fabien', '->embedFormForEach() merges default values from the embedded forms');
    $t->is($v['authors'][$i][sfForm::getCSRFFieldName()], null, '->embedFormForEach() removes the CSRF token for the embedded forms');
    $t->is($w['authors'][$i][sfForm::getCSRFFieldName()], null, '->embedFormForEach() removes the CSRF token for the embedded forms');
}
$t->is($w['authors'][0]->generateName('first_name'), 'article[authors][0][first_name]', '->embedFormForEach() changes the name format to reflect the embedding');
// bind too many values for embedded forms
$t->diag('bind too many values for embedded forms');
$list = new FormTest();
$list->setWidgets(array('title' => new sfWidgetFormInputText()));
$list->setValidators(array('title' => new sfValidatorString()));
$list->embedFormForEach('items', clone $list, 2);
$list->bind(array('title' => 'list title', 'items' => array(array('title' => 'item 1'), array('title' => 'item 2'), array('title' => 'extra item'))));
$t->isa_ok($list['items'][0]->getError(), 'sfValidatorErrorSchema', '"sfFormFieldSchema" is given an error schema when an extra embedded form is bound');
// does this trigger a fatal error?
$list['items']->render();
$t->pass('"sfFormFieldSchema" renders when an extra embedded form is bound');
// ->getEmbeddedForms()
$t->diag('->getEmbeddedForms()');
<table>
<tr>
<?php 
$form = new sfForm();
$csrfToken = '&' . $form->getCSRFFieldName() . '=' . $form->getCSRFToken();
for ($i = 0; $i < 3; $i++) {
    ?>
<td>
<?php 
    if (isset($options['images'][$i])) {
        $image = $options['images'][$i];
        echo op_image_tag_sf_image($image->getFile(), array('size' => '180x180'));
        ?>
<br />
<?php 
        if (isset($options['form'])) {
            ?>
[
<?php 
            echo link_to(__('Delete'), 'member/deleteImage?member_image_id=' . $image->getId() . $csrfToken);
            ?>
 |
<?php 
            if ($image->getIsPrimary()) {
                echo __('Main Photo');
            } else {
                echo link_to(__('Main Photo'), 'member/changeMainImage?member_image_id=' . $image->getId() . $csrfToken);
            }
            ?>
]
<?php 
Example #18
0
<?php

$form = new sfForm();
$redirectUrl = url_for('community/addAllMember?id=' . $community->getId()) . '?continue=1' . '&' . urlencode($form->getCSRFFieldName()) . '=' . urlencode($form->getCSRFToken());
$sf_response->addHttpMeta('Refresh', '0;URL=' . $redirectUrl);
?>

<?php 
slot('submenu');
include_partial('submenu');
end_slot();
?>

<?php 
slot('title', __('Make all members join in this %community%'));
?>

<p>
<?php 
echo __('Processing... (Remaining %num% records)', array('%num%' => $remaining));
?>
</p>