/** * Clean posted data. Convert tabs to spaces (primarily for yaml) and * stripslashes when magic quotes are turned on. * * @param mixed $var * @return string */ function cleanPostedData($var) { if (is_array($var)) { foreach ($var as $key => $value) { $var[$key] = cleanPostedData($value); } } elseif (is_string($var)) { $var = str_replace("\t", " ", $var); // Ah, the joys of \"magic quotes\"! if (get_magic_quotes_gpc()) { $var = stripslashes($var); } } return $var; }
/** * Clean posted data. Convert tabs to spaces (primarily for yaml) and * stripslashes when magic quotes are turned on. * * @param mixed $var * @param bool $stripslashes * @param bool $strip_control_chars * @return string */ function cleanPostedData($var, $stripslashes = true, $strip_control_chars = false) { if (is_array($var)) { foreach ($var as $key => $value) { $var[$key] = cleanPostedData($value); } } elseif (is_string($var)) { // expand tabs $var = str_replace("\t", " ", $var); // prune control characters if ($strip_control_chars) { $var = preg_replace('/[[:cntrl:][:space:]]/', ' ', $var); } // Ah, the joys of \"magic quotes\"! if ($stripslashes && get_magic_quotes_gpc()) { $var = stripslashes($var); } } return $var; }
public static function search(Request $request, Silex\Application $app) { $q = ''; if ($request->query->has('q')) { $q = $request->get('q'); } elseif ($request->query->has('search')) { $q = $request->get('search'); } $q = cleanPostedData($q, false); // Make paging work $page_size = 10; $page = 1; if ($request->query->has('page')) { $page = intval($request->get('page')); } if ($page < 1) { $page = 1; } $offset = ($page - 1) * $page_size; $limit = $page_size; // set-up filters from URL $filters = array(); foreach ($request->query->all() as $key => $value) { if (strpos($key, '_') > 0) { list($contenttypeslug, $field) = explode('_', $key, 2); if (isset($filters[$contenttypeslug])) { $filters[$contenttypeslug][$field] = $value; } else { $contenttype = $app['storage']->getContentType($contenttypeslug); if (is_array($contenttype)) { $filters[$contenttypeslug] = array($field => $value); } } } } if (count($filters) == 0) { $filters = null; } $result = $app['storage']->searchContent($q, null, $filters, $limit, $offset); $pager = array('for' => 'search', 'count' => $result['no_of_results'], 'totalpages' => ceil($result['no_of_results'] / $page_size), 'current' => $page, 'showing_from' => $offset + 1, 'showing_to' => $offset + count($result['results'])); $GLOBALS['pager']['search'] = $pager; $GLOBALS['pager']['search']['link'] = '/search?q=' . rawurlencode($q) . '&page='; $app['twig']->addGlobal('records', $result['results']); $app['twig']->addGlobal('search', $result['query']['use_q']); $app['twig']->addGlobal('searchresult', $result); $template = $app['config']->get('general/search_results_template', $app['config']->get('general/listing_template')); return $app['render']->render($template); }
/** * Prepare/edit/save a translation */ public function translation($domain, $tr_locale, Silex\Application $app, Request $request) { $short_locale = substr($tr_locale, 0, 2); $type = 'yml'; $file = "app/resources/translations/{$short_locale}/{$domain}.{$short_locale}.{$type}"; $filename = realpath(__DIR__ . "/../../../..") . "/{$file}"; $app['log']->add("Editing translation: {$file}", $app['debug'] ? 1 : 3); if ($domain == 'infos') { // no gathering here : if the file doesn't exist yet, we load a // copy from the locale_fallback version (en) if (!file_exists($filename) || filesize($filename) < 10) { $srcfile = "app/resources/translations/en/{$domain}.en.{$type}"; $srcfilename = realpath(__DIR__ . "/../../../..") . "/{$srcfile}"; $content = file_get_contents($srcfilename); } else { $content = file_get_contents($filename); } } else { $translated = array(); if (is_file($filename) && is_readable($filename)) { try { $translated = Yaml::parse($filename); } catch (ParseException $e) { $app['session']->getFlashBag()->set('error', printf("Unable to parse the YAML translations: %s", $e->getMessage())); } } list($msg, $ctype) = gatherTranslatableStrings($tr_locale, $translated); $ts = date("Y/m/d H:i:s"); $content = "# {$file} -- generated on {$ts}\n"; if ($domain == 'messages') { $cnt = count($msg['not_translated']); if ($cnt) { $content .= sprintf("# %d untranslated strings\n\n", $cnt); foreach ($msg['not_translated'] as $key) { $content .= "{$key}: #\n"; } $content .= "\n#-----------------------------------------\n"; } else { $content .= "# no untranslated strings; good ;-)\n\n"; } $cnt = count($msg['translated']); $content .= sprintf("# %d translated strings\n\n", $cnt); foreach ($msg['translated'] as $key => $trans) { $content .= "{$key}: {$trans}\n"; } } else { $cnt = count($ctype['not_translated']); if ($cnt) { $content .= sprintf("# %d untranslated strings\n\n", $cnt); foreach ($ctype['not_translated'] as $key) { $content .= "{$key}: #\n"; } $content .= "\n#-----------------------------------------\n"; } else { $content .= "# no untranslated strings: good ;-)\n\n"; } $cnt = count($ctype['translated']); $content .= sprintf("# %d translated strings\n\n", $cnt); foreach ($ctype['translated'] as $key => $trans) { $content .= "{$key}: {$trans}\n"; } } //========================== //$file = "app/resources/translations/$short_locale/$domain.yml"; //$filename = realpath(__DIR__."/../../../..")."/$file"; //$type = 'yml'; } // maybe no translations yet if (!file_exists($filename) && !is_writable(dirname($filename))) { $app['session']->getFlashBag()->set('info', __("The translations file '%s' can't be created. You will have to use your own editor to make modifications to this file.", array('%s' => $file))); $writeallowed = false; $title = __("View translations file '%s'.", array('%s' => $file)); } elseif (file_exists($filename) && !is_readable($filename)) { $error = __("The translations file '%s' is not readable.", array('%s' => $file)); $app->abort(404, $error); } elseif (!is_writable($filename)) { $app['session']->getFlashBag()->set('warning', __("The file '%s' is not writable. You will have to use your own editor to make modifications to this file.", array('%s' => $file))); $writeallowed = false; $title = __("View file '%s'.", array('%s' => $file)); } else { $writeallowed = true; $title = __("Edit translations file '%s'.", array('%s' => $file)); } $data['contents'] = $content; $form = $app['form.factory']->createBuilder('form', $data)->add('contents', 'textarea', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 10))))); $form = $form->getForm(); // Check if the form was POST-ed, and valid. If so, store the file. if ($request->getMethod() == "POST") { $form->bind($app['request']->get($form->getName())); if ($form->isValid()) { $data = $form->getData(); $contents = cleanPostedData($data['contents']) . "\n"; $ok = true; // Before trying to save a yaml file, check if it's valid. if ($type == "yml") { //$yamlparser = new \Symfony\Component\Yaml\Parser(); try { //$ok = $yamlparser->parse($contents); $ok = Yaml::parse($contents); } catch (\Symfony\Component\Yaml\Exception\ParseException $e) { $ok = false; $app['session']->getFlashBag()->set('error', __("File '%s' could not be saved: ", array('%s' => $file)) . $e->getMessage()); } } if ($ok) { if (file_put_contents($filename, $contents)) { $app['session']->getFlashBag()->set('info', __("File '%s' has been saved.", array('%s' => $file))); return redirect('translation', array('domain' => $domain, 'tr_locale' => $tr_locale)); } else { $app['session']->getFlashBag()->set('error', __("File '%s' could not be saved, for some reason.", array('%s' => $file))); } } } } return $app['render']->render('editlocale.twig', array('form' => $form->createView(), 'title' => $title, 'filetype' => $type, 'writeallowed' => $writeallowed)); }
public function setFromPost($values, $contenttype) { global $app; $values = cleanPostedData($values); // Some field type need to do things to the POST-ed value. foreach ($contenttype['fields'] as $fieldname => $field) { if ($field['type'] == "video" && isset($values[$fieldname])) { $video = $values[$fieldname]; // update the HTML, according to given width and height if (!empty($video['width']) && !empty($video['height'])) { $video['html'] = preg_replace("/width=(['\"])([0-9]+)(['\"])/i", 'width=${1}' . $video['width'] . '${3}', $video['html']); $video['html'] = preg_replace("/height=(['\"])([0-9]+)(['\"])/i", 'height=${1}' . $video['height'] . '${3}', $video['html']); } $responsiveclass = "responsive-video"; // See if it's widescreen or not.. if ($video['width'] / $video['height'] > 1.76) { $responsiveclass .= " widescreen"; } if (strpos($video['url'], "vimeo") !== false) { $responsiveclass .= " vimeo"; } $video['responsive'] = sprintf('<div class="%s">%s</div>', $responsiveclass, $video['html']); $values[$fieldname] = $video; } } // TODO: check for allowed file types.. // Handle file-uploads. if (!empty($_FILES)) { foreach ($_FILES as $key => $file) { $filename = sprintf("%s/files/%s/%s", $app['paths']['rootpath'], date("Y-m"), safeString($file['name'][0], false, "[]{}()")); $basename = sprintf("/%s/%s", date("Y-m"), safeString($file['name'][0], false, "[]{}()")); if ($file['error'][0] != UPLOAD_ERR_OK) { $app['log']->add("Upload: Error occured during upload: " . $file['error'][0], 2); continue; } if (substr($key, 0, 11) != "fileupload-") { $app['log']->add("Upload: skipped an upload that wasn't for Content.", 2); continue; } $fieldname = substr($key, 11); // Make sure the folder exists. makeDir(dirname($filename)); // Check if we don't have doubles. if (is_file($filename)) { while (is_file($filename)) { $filename = $this->upcount_name($filename); $basename = $this->upcount_name($basename); } } if (is_writable(dirname($filename))) { // Yes, we can create the file! move_uploaded_file($file['tmp_name'][0], $filename); $app['log']->add("Upload: uploaded file '{$basename}'.", 2); $values[$fieldname] = $basename; } else { $app['log']->add("Upload: couldn't write upload '{$basename}'.", 2); } } } $this->setValues($values); }
public function setFromPost($values, $contenttype) { $values = cleanPostedData($values); if (!$this->id) { // this is a new record: current user becomes the owner. $user = $this->app['users']->getCurrentUser(); $this['ownerid'] = $user['id']; } // If the owner is set explicitly, check if the current user is allowed // to do this. if (isset($values['ownerid'])) { if ($this['ownerid'] != $values['ownerid']) { if (!$this->app['users']->isAllowed("contenttype:{$contenttype}:change-ownership:{$this->id}")) { throw new \Exception("Changing ownership is not allowed."); } $this['ownerid'] = intval($values['ownerid']); } } // Make sure we have a proper status.. if (!in_array($values['status'], array('published', 'timed', 'held', 'draft'))) { if ($this['status']) { $values['status'] = $this['status']; } else { $values['status'] = "draft"; } } // If we set a 'publishdate' in the future, and the status is 'published', set it to 'timed' instead. if ($values['datepublish'] > date("Y-m-d H:i:s") && $values['status'] == "published") { $values['status'] = "timed"; } // Get the taxonomies from the POST-ed values. We don't support 'order' for taxonomies that // can have multiple values. // @todo use $this->setTaxonomy() for this if (!empty($values['taxonomy'])) { foreach ($values['taxonomy'] as $taxonomytype => $value) { if (!is_array($value)) { $value = explode(",", $value); } if (isset($values['taxonomy-order'][$taxonomytype])) { foreach ($value as $k => $v) { $value[$k] = $v . "#" . $values['taxonomy-order'][$taxonomytype]; } } $this->taxonomy[$taxonomytype] = $value; } unset($values['taxonomy']); unset($values['taxonomy-order']); } // Get the relations from the POST-ed values. // @todo use $this->setRelation() for this if (!empty($values['relation'])) { $this->relation = $values['relation']; unset($values['relation']); } // @todo check for allowed file types.. // Handle file-uploads. if (!empty($_FILES)) { foreach ($_FILES as $key => $file) { if (empty($file['name'][0])) { continue; // Skip 'empty' uploads.. } $filename = sprintf("%s/files/%s/%s", $this->app['paths']['rootpath'], date("Y-m"), safeString($file['name'][0], false, "[]{}()")); $basename = sprintf("/%s/%s", date("Y-m"), safeString($file['name'][0], false, "[]{}()")); if ($file['error'][0] != UPLOAD_ERR_OK) { $this->app['log']->add("Upload: Error occured during upload: " . $file['error'][0] . " - " . $filename, 2); continue; } if (substr($key, 0, 11) != "fileupload-") { $this->app['log']->add("Upload: skipped an upload that wasn't for Content. - " . $filename, 2); continue; } $fieldname = substr($key, 11); // Make sure the folder exists. makeDir(dirname($filename)); // Check if we don't have doubles. if (is_file($filename)) { while (is_file($filename)) { $filename = $this->upcountName($filename); $basename = $this->upcountName($basename); } } if (is_writable(dirname($filename))) { // Yes, we can create the file! move_uploaded_file($file['tmp_name'][0], $filename); $this->app['log']->add("Upload: uploaded file '{$basename}'.", 2); $values[$fieldname] = $basename; } else { $this->app['log']->add("Upload: couldn't write upload '{$basename}'.", 2); } } } $this->setValues($values); }
function fileedit($file, Silex\Application $app, Request $request) { $title = "Edit file '{$file}'."; $filename = realpath(__DIR__ . "/../../../../" . $file); $type = getExtension($filename); if (!file_exists($filename) || !is_readable($filename)) { $error = sprintf("file '%s/config/%s' doesn't exist, or is not readable.", basename(__DIR__), $file); $app->abort(404, $error); } if (!is_writable($filename)) { $app['session']->setFlash('error', sprintf("The file '%s/config/%s' is not writable. You will not be able to save your changes, until you fix this.", basename(__DIR__), $file)); $writeallowed = false; } else { $writeallowed = true; } $data['contents'] = file_get_contents($filename); $form = $app['form.factory']->createBuilder('form', $data)->add('contents', 'textarea', array('constraints' => array(new Assert\NotBlank(), new Assert\MinLength(10)))); $form = $form->getForm(); // Check if the form was POST-ed, and valid. If so, store the user. if ($request->getMethod() == "POST") { //$form->bindRequest($request); $form->bind($app['request']->get($form->getName())); if ($form->isValid()) { $data = $form->getData(); $contents = cleanPostedData($data['contents']); $ok = true; // Before trying to save a yaml file, check if it's valid. if ($type == "yml") { $yamlparser = new \Symfony\Component\Yaml\Parser(); try { $ok = $yamlparser->parse($contents); } catch (Exception $e) { $ok = false; $app['session']->setFlash('error', "File '" . $file . "' could not be saved: not valid YAML."); } } if ($ok) { if (file_put_contents($filename, $contents)) { $app['session']->setFlash('info', "File '" . $file . "' has been saved."); // If we've saved contenttypes.yml, update the database.. if (basename($file) == "contenttypes.yml") { return redirect('dbupdate', '', "?return=edit"); } } else { $app['session']->setFlash('error', "File '" . $file . "' could not be saved, for some reason."); } } return redirect('fileedit', array('file' => $file)); } } return $app['twig']->render('editconfig.twig', array('form' => $form->createView(), 'title' => $title, 'filetype' => $type, 'writeallowed' => $writeallowed)); }