Exemple #1
0
 function __construct()
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("Director", "construct");
     }
     Session::addToArray('history', substr($_SERVER['REQUEST_URI'], strlen(Director::baseURL())));
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark("Director", "construct");
     }
 }
 function FieldHolder()
 {
     $fieldName = $this->name . 'ID';
     $relationName = $this->name;
     Profiler::mark("RelatedDataEditor.FieldHolder", "get data");
     $record = $this->form->getRecord();
     $relatedObject = $record->{$relationName}();
     Profiler::unmark("RelatedDataEditor.FieldHolder", "get data");
     $this->dropdownField->Name = $this->name . '[ID]';
     $this->dropdownField->Value = $record->{$fieldName};
     $extraclass = $this->IsNested() ? "nested" : "";
     $result .= "<div id=\"{$this->name}\" class=\"{$this->class} groupfield {$extraclass}\" >";
     $fieldholder = $this->dropdownField->FieldHolder();
     if ($this->showkeydropdown) {
         $result .= "<div id=\"{$this->name}_keyholder\" class=\"keyholder\">{$fieldholder}</div>";
         if ($this->children) {
             $result .= "<img id=\"{$this->name}_loading\" src=\"cms/images/network-save.gif\" style=\"display: none;\" />";
             $result .= "<img id=\"{$this->name}_loaded\" src=\"cms/images/alert-good.gif\" style=\"display: none;\" />";
         }
     } else {
         $result .= "<div id=\"{$this->name}_keyholder\" class=\"keyholder\" style=\"display: none\">{$fieldholder}</div>";
     }
     if ($this->children) {
         $result .= "<div id= \"{$this->name}_childrenholder\" class=\"children_holder\">";
         foreach ($this->children as $child) {
             if (!$child->isComposite()) {
                 $childFieldName = $child->Name();
                 $child->Name = $this->name . '[' . $child->Name() . ']';
                 if ($this->dropdownField->isSelected()) {
                     $child->Value = $relatedObject->{$childFieldName};
                 }
                 $child->setForm($this->form);
                 $result .= $child->FieldHolder();
             } else {
                 $fs = $child->FieldSet();
                 foreach ($fs as $subfield) {
                     $childFieldName = $subfield->Name();
                     $subfield->Name = $this->name . '[' . $subfield->Name() . ']';
                     if ($this->dropdownField->isSelected()) {
                         $subfield->Value = $relatedObject->{$childFieldName};
                     }
                     $subfield->setForm($this->form);
                 }
                 $result .= $child->FieldHolder();
             }
         }
         $result .= "<div class=\"clear\">&nbsp;</div>";
         $result .= "</div>";
     }
     $result .= "</div>";
     return $result;
 }
 /**
  * updates database fields
  * @param Bool $force - run it, even if it has run already
  * @return void
  */
 public function runUpdate($force = true)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark('OrderMaker::runUpdate');
     }
     if (!$this->IsRemoved()) {
         $this->checkField("OrderFor");
         parent::runUpdate($force);
     }
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark('OrderMaker::runUpdate');
     }
 }
 /**
  * For all modifers with their own database fields, we need to include this...
  * It will update each of the fields.
  * Within this method, we need to create the methods
  * Live{functionName}
  * e.g LiveMyField() and LiveMyReduction() in this case...
  * The OrderModifier already updates the basic database fields.
  * @param Bool $force - run it, even if it has run already
  */
 public function runUpdate($force = false)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark('ModifierExample::runUpdate');
     }
     if (!$this->IsRemoved()) {
         $this->checkField("MyField");
         $this->checkField("MyReduction");
     }
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark('ModifierExample::runUpdate');
     }
     parent::runUpdate($force);
 }
 /**
  * Update the given HTML content with the appropriate include tags for the registered
  * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
  * including a <head> tag. The requirements will insert before the closing <head> tag automatically.
  *
  * @todo Calculate $prefix properly
  * 
  * @param string $templateFilePath Absolute path for the *.ss template file
  * @param string $content HTML content that has already been parsed from the $templateFilePath through {@link SSViewer}.
  * @return string HTML content thats augumented with the requirements before the closing <head> tag.
  */
 function includeInHTML($templateFile, $content)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("Requirements::includeInHTML");
     }
     if (strpos($content, '</head') !== false && ($this->css || $this->javascript || $this->customCSS || $this->customScript || $this->customHeadTags)) {
         $requirements = '';
         $jsRequirements = '';
         // Combine files - updates $this->javascript and $this->css
         $this->process_combined_files();
         foreach (array_diff_key($this->javascript, $this->blocked) as $file => $dummy) {
             $path = $this->path_for_file($file);
             if ($path) {
                 $jsRequirements .= "<script type=\"text/javascript\" src=\"{$path}\"></script>\n";
             }
         }
         // add all inline javascript *after* including external files which
         // they might rely on
         if ($this->customScript) {
             foreach (array_diff_key($this->customScript, $this->blocked) as $script) {
                 $jsRequirements .= "<script type=\"text/javascript\">\n//<![CDATA[\n";
                 $jsRequirements .= "{$script}\n";
                 $jsRequirements .= "\n//]]>\n</script>\n";
             }
         }
         foreach (array_diff_key($this->css, $this->blocked) as $file => $params) {
             $path = $this->path_for_file($file);
             if ($path) {
                 $media = isset($params['media']) && !empty($params['media']) ? " media=\"{$params['media']}\"" : "";
                 $requirements .= "<link rel=\"stylesheet\" type=\"text/css\"{$media} href=\"{$path}\" />\n";
             }
         }
         foreach (array_diff_key($this->customCSS, $this->blocked) as $css) {
             $requirements .= "<style type=\"text/css\">\n{$css}\n</style>\n";
         }
         foreach (array_diff_key($this->customHeadTags, $this->blocked) as $customHeadTag) {
             $requirements .= "{$customHeadTag}\n";
         }
         if ($this->write_js_to_body) {
             // Remove all newlines from code to preserve layout
             $jsRequirements = preg_replace('/>\\n*/', '>', $jsRequirements);
             // We put script tags into the body, for performance.
             // If your template already has script tags in the body, then we put our script
             // tags just before those. Otherwise, we put it at the bottom.
             $p1 = strripos($content, '<script');
             $p2 = stripos($content, '<body');
             if ($p1 !== false && $p1 > $p2) {
                 $content = substr($content, 0, $p1) . $jsRequirements . substr($content, $p1);
             } else {
                 $content = preg_replace("/(<\\/body[^>]*>)/i", $jsRequirements . "\\1", $content);
             }
             // Put CSS at the bottom of the head
             $content = preg_replace("/(<\\/head>)/i", $requirements . "\\1", $content);
         } else {
             $content = preg_replace("/(<\\/head>)/i", $requirements . "\\1", $content);
             $content = preg_replace("/(<\\/head>)/i", $jsRequirements . "\\1", $content);
         }
     }
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark("Requirements::includeInHTML");
     }
     return $content;
 }
 /**
  * The process() method handles the "meat" of the template processing.
  * It takes care of caching the output (via {@link SS_Cache}),
  * as well as replacing the special "$Content" and "$Layout"
  * placeholders with their respective subtemplates.
  * The method injects extra HTML in the header via {@link Requirements::includeInHTML()}.
  * 
  * Note: You can call this method indirectly by {@link ViewableData->renderWith()}.
  * 
  * @param ViewableData $item
  * @param SS_Cache $cache Optional cache backend
  * @return String Parsed template output.
  */
 public function process($item, $cache = null)
 {
     SSViewer::$topLevel[] = $item;
     if (!$cache) {
         $cache = SS_Cache::factory('cacheblock');
     }
     if (isset($this->chosenTemplates['main'])) {
         $template = $this->chosenTemplates['main'];
     } else {
         $template = $this->chosenTemplates[reset($dummy = array_keys($this->chosenTemplates))];
     }
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("SSViewer::process", " for {$template}");
     }
     $cacheFile = TEMP_FOLDER . "/.cache" . str_replace(array('\\', '/', ':'), '.', realpath($template));
     $lastEdited = filemtime($template);
     if (!file_exists($cacheFile) || filemtime($cacheFile) < $lastEdited || isset($_GET['flush'])) {
         if (isset($_GET['debug_profile'])) {
             Profiler::mark("SSViewer::process - compile", " for {$template}");
         }
         $content = file_get_contents($template);
         $content = SSViewer::parseTemplateContent($content, $template);
         $fh = fopen($cacheFile, 'w');
         fwrite($fh, $content);
         fclose($fh);
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("SSViewer::process - compile", " for {$template}");
         }
     }
     if (isset($_GET['showtemplate']) && !Director::isLive()) {
         $lines = file($cacheFile);
         echo "<h2>Template: {$cacheFile}</h2>";
         echo "<pre>";
         foreach ($lines as $num => $line) {
             echo str_pad($num + 1, 5) . htmlentities($line);
         }
         echo "</pre>";
     }
     // Makes the rendered sub-templates available on the parent item,
     // through $Content and $Layout placeholders.
     foreach (array('Content', 'Layout') as $subtemplate) {
         if (isset($this->chosenTemplates[$subtemplate])) {
             $subtemplateViewer = new SSViewer($this->chosenTemplates[$subtemplate]);
             $item = $item->customise(array($subtemplate => $subtemplateViewer->process($item, $cache)));
         }
     }
     $itemStack = array();
     $val = "";
     $valStack = array();
     include $cacheFile;
     $output = $val;
     $output = Requirements::includeInHTML($template, $output);
     array_pop(SSViewer::$topLevel);
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark("SSViewer::process", " for {$template}");
     }
     // If we have our crazy base tag, then fix # links referencing the current page.
     if ($this->rewriteHashlinks && self::$options['rewriteHashlinks']) {
         if (strpos($output, '<base') !== false) {
             if (SSViewer::$options['rewriteHashlinks'] === 'php') {
                 $thisURLRelativeToBase = "<?php echo \$_SERVER['REQUEST_URI']; ?>";
             } else {
                 $thisURLRelativeToBase = Director::makeRelative(Director::absoluteURL($_SERVER['REQUEST_URI']));
             }
             $output = preg_replace('/(<a[^>]+href *= *)"#/i', '\\1"' . $thisURLRelativeToBase . '#', $output);
         }
     }
     return $output;
 }
 /**
  * Run the controller (default action)
  *
  * @param array $requestParams Passed request parameters
  */
 function index($requestParams)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("OpenIDAuthenticator_Controller");
     }
     $consumer = new Auth_OpenID_Consumer(new OpenIDStorage(), new SessionWrapper());
     // Complete the authentication process using the server's response.
     $response = $consumer->complete();
     if ($response->status == Auth_OpenID_CANCEL) {
         Session::set("Security.Message.message", _t('OpenIDAuthenticator.VERIFICATIONCANCELLED', 'The verification was cancelled. Please try again.'));
         Session::set("Security.Message.type", "bad");
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("OpenIDAuthenticator_Controller");
         }
         Director::redirect("Security/login");
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             Session::set("Security.Message.message", _t('OpenIDAuthenticator.AUTHFAILED', 'The OpenID/i-name authentication failed.'));
             Session::set("Security.Message.type", "bad");
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("OpenIDAuthenticator_Controller");
             }
             Director::redirect("Security/login");
         } else {
             if ($response->status == Auth_OpenID_SUCCESS) {
                 $openid = $response->identity_url;
                 if ($response->endpoint->canonicalID) {
                     $openid = $response->endpoint->canonicalID;
                 }
                 if (isset($_GET['debug_profile'])) {
                     Profiler::unmark("OpenIDAuthenticator_Controller");
                 }
                 $SQL_identity = Convert::raw2sql($openid);
                 if ($member = DataObject::get_one("Member", "Member.IdentityURL = '{$SQL_identity}'")) {
                     $firstname = Convert::raw2xml($member->FirstName);
                     Session::set("Security.Message.message", sprintf(_t('Member.WELCOMEBACK'), $firstname));
                     Session::set("Security.Message.type", "good");
                     $member->LogIn(Session::get('SessionForms.OpenIDLoginForm.Remember'));
                     Session::clear('SessionForms.OpenIDLoginForm.OpenIDURL');
                     Session::clear('SessionForms.OpenIDLoginForm.Remember');
                     if ($backURL = Session::get("BackURL")) {
                         Session::clear("BackURL");
                         Director::redirect($backURL);
                     } else {
                         Director::redirectBack();
                     }
                 } else {
                     Session::set("Security.Message.message", _t('OpenIDAuthenticator.LOGINFAILED', 'Login failed. Please try again.'));
                     Session::set("Security.Message.type", "bad");
                     if ($badLoginURL = Session::get("BadLoginURL")) {
                         Director::redirect($badLoginURL);
                     } else {
                         Director::redirectBack();
                     }
                 }
             }
         }
     }
 }
}
// Connect to database
require_once "core/model/DB.php";
// Redirect to the installer if no database is selected
if (!isset($databaseConfig) || !isset($databaseConfig['database']) || !$databaseConfig['database']) {
    $s = isset($_SERVER['SSL']) || isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 's' : '';
    $installURL = "http{$s}://" . $_SERVER['HTTP_HOST'] . BASE_URL . '/install.php';
    // The above dirname() will equate to "\" on Windows when installing directly from http://localhost (not using
    // a sub-directory), this really messes things up in some browsers. Let's get rid of the backslashes
    $installURL = str_replace('\\', '', $installURL);
    header("Location: {$installURL}");
    die;
}
if (isset($_GET['debug_profile'])) {
    Profiler::mark('DB::connect');
}
DB::connect($databaseConfig);
if (isset($_GET['debug_profile'])) {
    Profiler::unmark('DB::connect');
}
if (isset($_GET['debug_profile'])) {
    Profiler::unmark('main.php init');
}
// Direct away - this is the "main" function, that hands control to the appropriate controller
Director::direct($url);
if (isset($_GET['debug_profile'])) {
    Profiler::unmark('all_execution');
    if (!Director::isLive()) {
        Profiler::show(isset($_GET['profile_trace']));
    }
}
Exemple #9
0
 /**
  * Update the given HTML content with the appropriate include tags for the registered
  * requirements.
  * @todo Calculate $prefix properly
  */
 static function includeInHTML($templateFile, $content)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("Requirements::includeInHTML");
     }
     if (strpos($content, '</head') !== false && (Requirements::$javascript || Requirements::$css || Requirements::$customScript || Requirements::$customHeadTags)) {
         $prefix = "";
         $requirements = '';
         foreach (array_diff_key(self::$javascript, self::$blocked) as $file => $dummy) {
             if (substr($file, 0, 7) == 'http://' || Director::fileExists($file)) {
                 $requirements .= "<script type=\"text/javascript\" src=\"{$prefix}{$file}\"></script>\n";
             }
         }
         if (self::$customScript) {
             $requirements .= "<script type=\"text/javascript\">\n//<![CDATA[\n";
             foreach (array_diff_key(self::$customScript, self::$blocked) as $script) {
                 $requirements .= "{$script}\n";
             }
             $requirements .= "\n//]]>\n</script>\n";
         }
         foreach (array_diff_key(self::$css, self::$blocked) as $file => $params) {
             if (Director::fileExists($file)) {
                 $media = isset($params['media']) ? " media=\"{$params['media']}\"" : "";
                 $requirements .= "<link rel=\"stylesheet\" type=\"text/css\"{$media} href=\"{$prefix}{$file}\" />\n";
             }
         }
         foreach (array_diff_key(self::$customCSS, self::$blocked) as $css) {
             $requirements .= "<style type=\"text/css\">\n{$css}\n</style>\n";
         }
         $requirements .= self::$customHeadTags;
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("Requirements::includeInHTML");
         }
         return eregi_replace("(</head[^>]*>)", $requirements . "\\1", $content);
     } else {
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("Requirements::includeInHTML");
         }
         return $content;
     }
 }
Exemple #10
0
 /**
  * Generate the given field on the table, modifying whatever already exists as necessary.
  * @param string $table The table name.
  * @param string $field The field name.
  * @param string $spec The field specification.
  */
 function requireField($table, $field, $spec)
 {
     $newTable = false;
     Profiler::mark('requireField');
     // Collations didn't come in until MySQL 4.1.  Anything earlier will throw a syntax error if you try and use
     // collations.
     if (!$this->supportsCollations()) {
         $spec = eregi_replace(' *character set [^ ]+( collate [^ ]+)?( |$)', '\\2', $spec);
     }
     if (!isset($this->tableList[strtolower($table)])) {
         $newTable = true;
     }
     if (!$newTable && !isset($this->fieldList[$table])) {
         $this->fieldList[$table] = $this->fieldList($table);
     }
     if ($newTable || !isset($this->fieldList[$table][$field])) {
         Profiler::mark('createField');
         $this->transCreateField($table, $field, $spec);
         Profiler::unmark('createField');
         Database::alteration_message("Field {$table}.{$field}: created as {$spec}", "created");
     } else {
         if ($this->fieldList[$table][$field] != $spec) {
             // If enums are being modified, then we need to fix existing data in the table.
             // Update any records where the enum is set to a legacy value to be set to the default.
             // One hard-coded exception is SiteTree - the default for this is Page.
             if (substr($spec, 0, 4) == "enum") {
                 $new = substr($spec, 5);
                 $old = substr($this->fieldList[$table][$field], 5);
                 $new = substr($new, 0, strpos($new, ')'));
                 $old = substr($old, 0, strpos($old, ')'));
                 $new = str_replace("'", '', $new);
                 $old = str_replace("'", '', $old);
                 $new = explode(',', $new);
                 $old = explode(',', $old);
                 $holder = array();
                 foreach ($old as $check) {
                     if (!in_array($check, $new)) {
                         $holder[] = $check;
                     }
                 }
                 if (count($holder)) {
                     $default = explode('default ', $spec);
                     $default = $default[1];
                     if ($default == "'SiteTree'") {
                         $default = "'Page'";
                     }
                     $query = "UPDATE `{$table}` SET {$field}={$default} WHERE {$field} IN (";
                     for ($i = 0; $i + 1 < count($holder); $i++) {
                         $query .= "'{$holder[$i]}', ";
                     }
                     $query .= "'{$holder[$i]}')";
                     DB::query($query);
                     $amount = DB::affectedRows();
                     Database::alteration_message("Changed {$amount} rows to default value of field {$field} (Value: {$default})");
                 }
             }
             Profiler::mark('alterField');
             $this->transAlterField($table, $field, $spec);
             Profiler::unmark('alterField');
             Database::alteration_message("Field {$table}.{$field}: changed to {$spec} <i style=\"color: #AAA\">(from {$this->fieldList[$table][$field]})</i>", "changed");
         }
     }
     Profiler::unmark('requireField');
 }
Exemple #11
0
 /**
  * The process() method handles the "meat" of the template processing.
  * It takes care of caching the output (via {@link SS_Cache}),
  * as well as replacing the special "$Content" and "$Layout"
  * placeholders with their respective subtemplates.
  * The method injects extra HTML in the header via {@link Requirements::includeInHTML()}.
  * 
  * Note: You can call this method indirectly by {@link ViewableData->renderWith()}.
  * 
  * @param ViewableData $item
  * @param SS_Cache $cache Optional cache backend
  * @return String Parsed template output.
  */
 public function process($item, $arguments = null)
 {
     SSViewer::$topLevel[] = $item;
     if ($arguments && $arguments instanceof Zend_Cache_Core) {
         Deprecation::notice('3.0', 'Use setPartialCacheStore to override the partial cache storage backend, the second argument to process is now an array of variables.');
         $this->setPartialCacheStore($arguments);
         $arguments = null;
     }
     if (isset($this->chosenTemplates['main'])) {
         $template = $this->chosenTemplates['main'];
     } else {
         $keys = array_keys($this->chosenTemplates);
         $key = reset($keys);
         $template = $this->chosenTemplates[$key];
     }
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("SSViewer::process", " for {$template}");
     }
     $cacheFile = TEMP_FOLDER . "/.cache" . str_replace(array('\\', '/', ':'), '.', Director::makeRelative(realpath($template)));
     $lastEdited = filemtime($template);
     if (!file_exists($cacheFile) || filemtime($cacheFile) < $lastEdited || isset($_GET['flush'])) {
         if (isset($_GET['debug_profile'])) {
             Profiler::mark("SSViewer::process - compile", " for {$template}");
         }
         $content = file_get_contents($template);
         $content = SSViewer::parseTemplateContent($content, $template);
         $fh = fopen($cacheFile, 'w');
         fwrite($fh, $content);
         fclose($fh);
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("SSViewer::process - compile", " for {$template}");
         }
     }
     $underlay = array('I18NNamespace' => basename($template));
     // Makes the rendered sub-templates available on the parent item,
     // through $Content and $Layout placeholders.
     foreach (array('Content', 'Layout') as $subtemplate) {
         if (isset($this->chosenTemplates[$subtemplate])) {
             $subtemplateViewer = new SSViewer($this->chosenTemplates[$subtemplate]);
             $subtemplateViewer->setPartialCacheStore($this->getPartialCacheStore());
             $underlay[$subtemplate] = $subtemplateViewer->process($item, $arguments);
         }
     }
     $val = $this->includeGeneratedTemplate($cacheFile, $item, $arguments, $underlay);
     $output = Requirements::includeInHTML($template, $val);
     array_pop(SSViewer::$topLevel);
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark("SSViewer::process", " for {$template}");
     }
     // If we have our crazy base tag, then fix # links referencing the current page.
     if ($this->rewriteHashlinks && self::$options['rewriteHashlinks']) {
         if (strpos($output, '<base') !== false) {
             if (SSViewer::$options['rewriteHashlinks'] === 'php') {
                 $thisURLRelativeToBase = "<?php echo strip_tags(\$_SERVER['REQUEST_URI']); ?>";
             } else {
                 $thisURLRelativeToBase = strip_tags($_SERVER['REQUEST_URI']);
             }
             $output = preg_replace('/(<a[^>]+href *= *)"#/i', '\\1"' . $thisURLRelativeToBase . '#', $output);
         }
     }
     return $output;
 }
Exemple #12
0
 /**
  * Get the value of a field on this object, automatically inserting the value into any available casting objects
  * that have been specified.
  *
  * @param string $fieldName
  * @param array $arguments
  * @param bool $forceReturnedObject if TRUE, the value will ALWAYS be casted to an object before being returned,
  *        even if there is no explicit casting information
  * @param string $cacheName a custom cache name
  */
 public function obj($fieldName, $arguments = null, $forceReturnedObject = true, $cache = false, $cacheName = null)
 {
     if (isset($_REQUEST['debug_profile'])) {
         Profiler::mark("obj.{$fieldName}", "on a {$this->class} object");
     }
     if (!$cacheName) {
         $cacheName = $arguments ? $fieldName . implode(',', $arguments) : $fieldName;
     }
     if (!isset($this->objCache[$cacheName])) {
         if ($this->hasMethod($fieldName)) {
             $value = $arguments ? call_user_func_array(array($this, $fieldName), $arguments) : $this->{$fieldName}();
         } else {
             $value = $this->{$fieldName};
         }
         if (!is_object($value) && ($this->castingClass($fieldName) || $forceReturnedObject)) {
             if (!($castConstructor = $this->castingHelper($fieldName))) {
                 $castConstructor = $this->stat('default_cast');
             }
             $valueObject = Object::create_from_string($castConstructor, $fieldName);
             $valueObject->setValue($value, $this->hasMethod('getAllFields') ? $this->getAllFields() : null);
             $value = $valueObject;
         }
         if ($cache) {
             $this->objCache[$cacheName] = $value;
         }
     } else {
         $value = $this->objCache[$cacheName];
     }
     if (isset($_REQUEST['debug_profile'])) {
         Profiler::unmark("obj.{$fieldName}", "on a {$this->class} object");
     }
     if (!is_object($value) && $forceReturnedObject) {
         $default = Object::get_static('ViewableData', 'default_cast');
         $value = new $default($fieldName);
     }
     return $value;
 }
 /**
  * Determines fields and actions for the given {$data_type}, and populates
  * these fields with values from {$data_type} and any connected {$data_type_extra}.
  * Adds default actions ("save" and "delete") if no custom actions are found.
  * Returns an empty form if no fields or actions are found (on first load).
  * 
  * @param $id Number
  * @return Form
  */
 function getEditForm($id)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark('getEditForm');
     }
     $genericData = DataObject::get_by_id($this->stat('data_type'), $id);
     $fields = method_exists($genericData, 'getCMSFields') ? $genericData->getCMSFields() : new FieldSet();
     if (!$fields->dataFieldByName('ID')) {
         $fields->push($idField = new HiddenField("ID", "ID", $id));
         $idField->setValue($id);
     }
     if (method_exists($genericData, 'getGenericStatus')) {
         $genericDataStatus = $genericData->getGenericStatus();
         if ($genericDataStatus) {
             $fields->push($dataStatusField = new ReadonlyField("GenericDataStatus", "", $genericDataStatus));
             $dataStatusField->dontEscape = true;
         }
     }
     $actions = method_exists($genericData, 'getCMSActions') ? $genericData->getCMSActions() : new FieldSet();
     if (!$actions->fieldByName('action_save')) {
         $actions->push(new FormAction('save', _t('GenericDataAdmin.SAVE', 'Save'), 'ajaxAction-save'));
     }
     if (!$actions->fieldByName('action_delete')) {
         $actions->push(new FormAction('delete', _t('GenericDataAdmin.DELETE', 'Delete'), 'ajaxAction-delete'));
     }
     $required = method_exists($genericData, 'getCMSRequiredField') ? $genericData->getCMSRequiredField() : new RequiredFields();
     $form = new Form($this, "EditForm", $fields, $actions, $required);
     if ($this->stat('data_type_extra')) {
         foreach ($this->stat('data_type_extra') as $oneRelated) {
             $oneExtra = $genericData->{$oneRelated}();
             if ($oneExtra) {
                 $allFields = $oneExtra->getAllFields();
                 foreach ($allFields as $k => $v) {
                     $fieldname = $oneRelated . "[" . $k . "]";
                     $allFields[$fieldname] = $v;
                     unset($allFields[$k]);
                 }
                 $form->loadDataFrom($allFields);
             }
         }
     }
     $form->loadDataFrom($genericData);
     $form->disableDefaultAction();
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark('getEditForm');
     }
     return $form;
 }
Exemple #14
0
 static function getControllerForURL($url)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("Director", "getControllerForURL");
     }
     $url = preg_replace(array('/\\/+/', '/^\\//', '/\\/$/'), array('/', '', ''), $url);
     $urlParts = split('/+', $url);
     krsort(Director::$rules);
     if (isset($_REQUEST['debug'])) {
         Debug::show(Director::$rules);
     }
     foreach (Director::$rules as $priority => $rules) {
         foreach ($rules as $pattern => $controller) {
             $patternParts = explode('/', $pattern);
             $matched = true;
             $arguments = array();
             foreach ($patternParts as $i => $part) {
                 $part = trim($part);
                 if (isset($part[0]) && $part[0] == '$') {
                     $arguments[substr($part, 1)] = isset($urlParts[$i]) ? $urlParts[$i] : null;
                     if ($part == '$Controller' && !class_exists($arguments['Controller'])) {
                         $matched = false;
                         break;
                     }
                 } else {
                     if (!isset($urlParts[$i]) || $urlParts[$i] != $part) {
                         $matched = false;
                         break;
                     }
                 }
             }
             if ($matched) {
                 if (substr($controller, 0, 2) == '->') {
                     if ($_REQUEST['debug'] == 1) {
                         Debug::message("Redirecting to {$controller}");
                     }
                     if (isset($_GET['debug_profile'])) {
                         Profiler::unmark("Director", "getControllerForURL");
                     }
                     return "redirect:" . Director::absoluteURL(substr($controller, 2), true);
                 } else {
                     if (isset($arguments['Controller']) && $controller == "*") {
                         $controller = $arguments['Controller'];
                     }
                     if (isset($_REQUEST['debug'])) {
                         Debug::message("Using controller {$controller}");
                     }
                     if (isset($arguments['Action'])) {
                         $arguments['Action'] = str_replace('-', '', $arguments['Action']);
                     }
                     if (isset($arguments['Action']) && ClassInfo::exists($controller . '_' . $arguments['Action'])) {
                         $controller = $controller . '_' . $arguments['Action'];
                     }
                     Director::$urlParams = $arguments;
                     $controllerObj = new $controller();
                     $controllerObj->setURLParams($arguments);
                     if (isset($arguments['URLSegment'])) {
                         self::$urlSegment = $arguments['URLSegment'] . "/";
                     }
                     if (isset($_GET['debug_profile'])) {
                         Profiler::unmark("Director", "getControllerForURL");
                     }
                     return $controllerObj;
                 }
             }
         }
     }
 }
 /**
  * updates database fields
  * @param Bool $force - run it, even if it has run already
  * @return void
  */
 public function runUpdate($force = true)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark('AUPostDeliverModifier::runUpdate');
     }
     //ORDER IS CRUCIAL HERE...
     $this->checkField("PostalCode");
     $this->checkField("IsPickUp");
     $this->checkField("TotalWeight");
     $this->checkField("Country");
     $this->checkField("ServiceType");
     $this->LiveCalculatedTotal();
     $this->checkField("TableSubTitle");
     //this must be last!
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark('AUPostDeliverModifier::runUpdate');
     }
     parent::runUpdate($force);
 }
 /**
  * Overridden to load all children from Matrix. For now we're ignoring
  * the $showAll param - we have a separate 'dependentChildren' method
  * to specifically handle dependent and non-dependent children
  * 
  * @param boolean $showAll
  * @return ArrayList
  */
 public function stageChildren($showAll = false)
 {
     if (!$this->ID) {
         return MatrixContentSource::get();
     }
     if (!$this->objChildren) {
         $this->objChildren = new ArrayList();
         // For the first batch, just get all the immediate children of the
         // top level
         $repo = $this->source->getRemoteRepository();
         if ($repo->isConnected()) {
             if (isset($_GET['debug_profile'])) {
                 Profiler::mark("MatrixContentItem", "getChildren");
             }
             if (!isset($this->remoteProperties['id'])) {
                 // for some reason the call failed!
                 return $this->objChildren;
             }
             $childItems = $repo->getChildren(array('id' => $this->remoteProperties['id'], 'depth' => 1));
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("MatrixContentItem", "getChildren");
             }
             // make sure that there's no errors!!
             if (!isset($childItems->error)) {
                 if (isset($_GET['debug_profile'])) {
                     Profiler::mark("MatrixContentItem", "loadChildren");
                 }
                 // means there weren't any children of this asset
                 foreach ($childItems as $childId => $properties) {
                     $item = $this->source->getObject($properties->id);
                     if (isset($properties->LinkType)) {
                         $item->ShowInMenus = true;
                     }
                     $this->objChildren->push($item);
                 }
                 if (isset($_GET['debug_profile'])) {
                     Profiler::unmark("MatrixContentItem", "loadChildren");
                 }
             }
         }
     }
     return $this->objChildren;
 }
function silverstripe_main($chain)
{
    global $token;
    if (isset($_GET['flush']) && !$token->tokenProvided()) {
        unset($_GET['flush']);
    } else {
        $chain->setSuppression(false);
    }
    /**
     * Include Sapphire's core code
     */
    require_once "core/Core.php";
    if (function_exists('mb_http_output')) {
        mb_http_output('UTF-8');
        mb_internal_encoding('UTF-8');
    }
    Session::start();
    if (isset($_GET['debug_profile'])) {
        Profiler::init();
        Profiler::mark('all_execution');
        Profiler::mark('main.php init');
    }
    // Connect to database
    require_once "core/model/DB.php";
    global $databaseConfig;
    if (isset($_GET['debug_profile'])) {
        Profiler::mark('DB::connect');
    }
    if ($databaseConfig) {
        DB::connect($databaseConfig);
    }
    if (isset($_GET['debug_profile'])) {
        Profiler::unmark('DB::connect');
    }
    if ($token->parameterProvided() && !$token->tokenProvided()) {
        // First, check if we're in dev mode, or the database doesn't have any security data
        $canFlush = Director::isDev() || !Security::database_is_ready();
        // Otherwise, we start up the session if needed, then check for admin
        if (!$canFlush) {
            if (!isset($_SESSION) && (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))) {
                Session::start();
            }
            if (Permission::check('ADMIN')) {
                $canFlush = true;
            } else {
                $loginPage = Director::absoluteURL('Security/login');
                $loginPage .= "?BackURL=" . urlencode($_SERVER['REQUEST_URI']);
                header('location: ' . $loginPage, true, 302);
                die;
            }
        }
        // And if we can flush, reload with an authority token
        if ($canFlush) {
            $token->reloadWithToken();
        }
    }
}
 /**
  * Get the value of a field on this object, automatically inserting the value into any available casting objects
  * that have been specified.
  *
  * @param string $fieldName
  * @param array $arguments
  * @param bool $forceReturnedObject if TRUE, the value will ALWAYS be casted to an object before being returned,
  *        even if there is no explicit casting information
  * @param string $cacheName a custom cache name
  */
 public function obj($fieldName, $arguments = null, $forceReturnedObject = true, $cache = false, $cacheName = null)
 {
     if (isset($_REQUEST['debug_profile'])) {
         Profiler::mark("obj.{$fieldName}", "on a {$this->class} object");
     }
     if (!$cacheName) {
         $cacheName = $arguments ? $fieldName . implode(',', $arguments) : $fieldName;
     }
     if (!isset($this->objCache[$cacheName])) {
         // HACK: Don't call the deprecated FormField::Name() method
         $methodIsAllowed = true;
         if ($this instanceof FormField && $fieldName == 'Name') {
             $methodIsAllowed = false;
         }
         if ($methodIsAllowed && $this->hasMethod($fieldName)) {
             $value = $arguments ? call_user_func_array(array($this, $fieldName), $arguments) : $this->{$fieldName}();
         } else {
             $value = $this->{$fieldName};
         }
         if (!is_object($value) && ($this->castingClass($fieldName) || $forceReturnedObject)) {
             if (!($castConstructor = $this->castingHelper($fieldName))) {
                 $castConstructor = $this->stat('default_cast');
             }
             $valueObject = Object::create_from_string($castConstructor, $fieldName);
             $valueObject->setValue($value, $this->hasMethod('toMap') ? $this->toMap() : null);
             $value = $valueObject;
         }
         if ($cache) {
             $this->objCache[$cacheName] = $value;
         }
     } else {
         $value = $this->objCache[$cacheName];
     }
     if (isset($_REQUEST['debug_profile'])) {
         Profiler::unmark("obj.{$fieldName}", "on a {$this->class} object");
     }
     if (!is_object($value) && $forceReturnedObject) {
         $default = Config::inst()->get('ViewableData', 'default_cast', Config::FIRST_SET);
         $value = new $default($fieldName);
     }
     return $value;
 }
Exemple #19
0
	/**
	 * The process() method handles the "meat" of the template processing.
	 */
	public function process($item) {
		SSViewer::$topLevel[] = $item;

		if(isset($this->chosenTemplates['main'])) {
			$template = $this->chosenTemplates['main'];
		} else {
			$template = $this->chosenTemplates[ reset($dummy = array_keys($this->chosenTemplates)) ];
		}
		
		if(isset($_GET['debug_profile'])) Profiler::mark("SSViewer::process", " for $template");
		$cacheFile = TEMP_FOLDER . "/.cache" . str_replace(array('\\','/',':'),'.',realpath($template));

		$lastEdited = filemtime($template);

		if(!file_exists($cacheFile) || filemtime($cacheFile) < $lastEdited || isset($_GET['flush'])) {
			if(isset($_GET['debug_profile'])) Profiler::mark("SSViewer::process - compile", " for $template");
			
			$content = file_get_contents($template);
			$content = SSViewer::parseTemplateContent($content, $template);
			
			$fh = fopen($cacheFile,'w');
			fwrite($fh, $content);
			fclose($fh);

			if(isset($_GET['debug_profile'])) Profiler::unmark("SSViewer::process - compile", " for $template");
		}
	
		
		if(isset($_GET['showtemplate']) && !Director::isLive()) {
			$lines = file($cacheFile);
			echo "<h2>Template: $cacheFile</h2>";
			echo "<pre>";
			foreach($lines as $num => $line) {
				echo str_pad($num+1,5) . htmlentities($line);
			}
			echo "</pre>";
		}
		
		
		foreach(array('Content', 'Layout') as $subtemplate) {
			if(isset($this->chosenTemplates[$subtemplate])) {
				$subtemplateViewer = new SSViewer($this->chosenTemplates[$subtemplate]);
				$item = $item->customise(array(
					$subtemplate => $subtemplateViewer->process($item)
				));
			}
		}
		
		$itemStack = array();
		$val = "";

		include($cacheFile);

		$output = $val;		
		$output = Requirements::includeInHTML($template, $output);
		
		array_pop(SSViewer::$topLevel);

		if(isset($_GET['debug_profile'])) Profiler::unmark("SSViewer::process", " for $template");
		
		
		// If we have our crazy base tag, then fix # links referencing the current page.
		if(strpos($output, '<base') !== false) {		
			$thisURLRelativeToBase = Director::makeRelative(Director::absoluteURL($_SERVER['REQUEST_URI']));
			$output = preg_replace('/(<a[^>+]href *= *")#/i', '\\1' . $thisURLRelativeToBase . '#', $output);
		}

		return $output;
	}
Exemple #20
0
 function run($requestParams)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("Controller", "run");
     }
     $this->pushCurrent();
     $this->response = new HTTPResponse();
     $this->requestParams = $requestParams;
     $this->action = isset($this->urlParams['Action']) ? str_replace("-", "_", $this->urlParams['Action']) : "";
     if (!$this->action) {
         $this->action = 'index';
     }
     // Check security on the controller
     if (!$this->checkAccessAction($this->action)) {
         user_error("Disallowed action: '{$this->action}' on controller '{$this->class}'", E_USER_ERROR);
     }
     // Init
     $this->baseInitCalled = false;
     $this->init();
     if (!$this->baseInitCalled) {
         user_error("init() method on class '{$this->class}' doesn't call Controller::init().  Make sure that you have parent::init() included.", E_USER_WARNING);
     }
     // If we had a redirection or something, halt processing.
     if ($this->response->isFinished()) {
         $this->popCurrent();
         return $this->response;
     }
     // Look at the action variables for forms
     $funcName = null;
     foreach ($this->requestParams as $paramName => $paramVal) {
         if (substr($paramName, 0, 7) == 'action_') {
             // Cleanup action_, _x and _y from image fields
             $funcName = preg_replace(array('/^action_/', '/_x$|_y$/'), '', $paramName);
             break;
         }
     }
     // Form handler
     if (isset($this->requestParams['executeForm']) && is_string($this->requestParams['executeForm'])) {
         if (isset($funcName)) {
             Form::set_current_action($funcName);
         }
         // Get the appropraite ocntroller: sometimes we want to get a form from another controller
         if (isset($this->requestParams['formController'])) {
             $formController = Director::getControllerForURL($this->requestParams['formController']);
             while (is_a($formController, 'NestedController')) {
                 $formController = $formController->getNestedController();
             }
         } else {
             $formController = $this;
         }
         // Create the form object
         $form = $formController;
         $formObjParts = explode('.', $this->requestParams['executeForm']);
         foreach ($formObjParts as $formMethod) {
             if (isset($_GET['debug_profile'])) {
                 Profiler::mark("Calling {$formMethod}", "on {$form->class}");
             }
             $form = $form->{$formMethod}();
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("Calling {$formMethod}", "on {$form->class}");
             }
             if (!$form) {
                 break;
             }
             //user_error("Form method '" . $this->requestParams['executeForm'] . "' returns null in controller class '$this->class' ($_SERVER[REQUEST_URI])", E_USER_ERROR);
         }
         // Populate the form
         if (isset($_GET['debug_profile'])) {
             Profiler::mark("Controller", "populate form");
         }
         if ($form) {
             $form->loadDataFrom($this->requestParams, true);
             // disregard validation if a single field is called
             if (!isset($_REQUEST['action_callfieldmethod'])) {
                 $valid = $form->beforeProcessing();
                 if (!$valid) {
                     $this->popCurrent();
                     return $this->response;
                 }
             } else {
                 $fieldcaller = $form->dataFieldByName($requestParams['fieldName']);
                 if (is_a($fieldcaller, "TableListField")) {
                     if ($fieldcaller->hasMethod('php')) {
                         $valid = $fieldcaller->php($requestParams);
                         if (!$valid) {
                             exit;
                         }
                     }
                 }
             }
             // If the action wasnt' set, choose the default on the form.
             if (!isset($funcName) && ($defaultAction = $form->defaultAction())) {
                 $funcName = $defaultAction->actionName();
             }
             if (isset($funcName)) {
                 $form->setButtonClicked($funcName);
             }
         } else {
             user_error("No form (" . Session::get('CMSMain.currentPage') . ") returned by {$formController->class}->{$_REQUEST['executeForm']}", E_USER_WARNING);
         }
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("Controller", "populate form");
         }
         if (!isset($funcName)) {
             user_error("No action button has been clicked in this form executon, and no default has been allowed", E_USER_ERROR);
         }
         // Protection against CSRF attacks
         if ($form->securityTokenEnabled()) {
             $securityID = Session::get('SecurityID');
             if (!$securityID || !isset($this->requestParams['SecurityID']) || $securityID != $this->requestParams['SecurityID']) {
                 // Don't show error on live sites, as spammers create a million of these
                 if (!Director::isLive()) {
                     trigger_error("Security ID doesn't match, possible CRSF attack.", E_USER_ERROR);
                 } else {
                     die;
                 }
             }
         }
         // First, try a handler method on the controller
         if ($this->hasMethod($funcName) || !$form) {
             if (isset($_GET['debug_controller'])) {
                 Debug::show("Found function {$funcName} on the controller");
             }
             if (isset($_GET['debug_profile'])) {
                 Profiler::mark("{$this->class}::{$funcName} (controller action)");
             }
             $result = $this->{$funcName}($this->requestParams, $form);
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("{$this->class}::{$funcName} (controller action)");
             }
             // Otherwise, try a handler method on the form object
         } else {
             if (isset($_GET['debug_controller'])) {
                 Debug::show("Found function {$funcName} on the form object");
             }
             if (isset($_GET['debug_profile'])) {
                 Profiler::mark("{$form->class}::{$funcName} (form action)");
             }
             $result = $form->{$funcName}($this->requestParams, $form);
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("{$form->class}::{$funcName} (form action)");
             }
         }
         // Normal action
     } else {
         if (!isset($funcName)) {
             $funcName = $this->action;
         }
         if ($this->hasMethod($funcName)) {
             if (isset($_GET['debug_controller'])) {
                 Debug::show("Found function {$funcName} on the {$this->class} controller");
             }
             if (isset($_GET['debug_profile'])) {
                 Profiler::mark("{$this->class}::{$funcName} (controller action)");
             }
             $result = $this->{$funcName}($this->urlParams);
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("{$this->class}::{$funcName} (controller action)");
             }
         } else {
             if (isset($_GET['debug_controller'])) {
                 Debug::show("Running default action for {$funcName} on the {$this->class} controller");
             }
             if (isset($_GET['debug_profile'])) {
                 Profiler::mark("Controller::defaultAction({$funcName})");
             }
             $result = $this->defaultAction($funcName, $this->urlParams);
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("Controller::defaultAction({$funcName})");
             }
         }
     }
     // If your controller function returns an array, then add that data to the
     // default template
     if (is_array($result)) {
         $extended = $this->customise($result);
         $viewer = $this->getViewer($funcName);
         $result = $viewer->process($extended);
     }
     $this->response->setBody($result);
     if ($result) {
         ContentNegotiator::process($this->response);
     }
     // Set up HTTP cache headers
     HTTP::add_cache_headers($this->response);
     if (isset($_GET['debug_profile'])) {
         Profiler::unmark("Controller", "run");
     }
     $this->popCurrent();
     return $this->response;
 }
Exemple #21
0
	/**
	 * Generate the given field on the table, modifying whatever already exists as necessary.
	 * @param string $table The table name.
	 * @param string $field The field name.
	 * @param array|string $spec The field specification. If passed in array syntax, the specific database
	 * 	driver takes care of the ALTER TABLE syntax. If passed as a string, its assumed to
	 * 	be prepared as a direct SQL framgment ready for insertion into ALTER TABLE. In this case you'll
	 * 	need to take care of database abstraction in your DBField subclass.  
	 */
	function requireField($table, $field, $spec) {
		//TODO: this is starting to get extremely fragmented.
		//There are two different versions of $spec floating around, and their content changes depending
		//on how they are structured.  This needs to be tidied up.
		$fieldValue = null;
		$newTable = false;
		
		Profiler::mark('requireField');
		
		// backwards compatibility patch for pre 2.4 requireField() calls
		$spec_orig=$spec;
		
		if(!is_string($spec)) {
			$spec['parts']['name'] = $field;
			$spec_orig['parts']['name'] = $field;
			//Convert the $spec array into a database-specific string
			$spec=DB::getConn()->$spec['type']($spec['parts'], true);
		}
		
		// Collations didn't come in until MySQL 4.1.  Anything earlier will throw a syntax error if you try and use
		// collations.
		// TODO: move this to the MySQLDatabase file, or drop it altogether?
		if(!$this->supportsCollations()) {
			$spec = preg_replace('/ *character set [^ ]+( collate [^ ]+)?( |$)/', '\\2', $spec);
		}
		
		if(!isset($this->tableList[strtolower($table)])) $newTable = true;

		if(!$newTable && !isset($this->fieldList[$table])) {
			$this->fieldList[$table] = $this->fieldList($table);
		}

		if(is_array($spec)) {
			$specValue = DB::getConn()->$spec_orig['type']($spec_orig['parts']);
		} else {
			$specValue = $spec;
		}

		// We need to get db-specific versions of the ID column:
		if($spec_orig==DB::getConn()->IdColumn() || $spec_orig==DB::getConn()->IdColumn(true))
			$specValue=DB::getConn()->IdColumn(true);
		
		if(!$newTable) {
			if(isset($this->fieldList[$table][$field])) {
				if(is_array($this->fieldList[$table][$field])) {
					$fieldValue = $this->fieldList[$table][$field]['data_type'];
				} else {
					$fieldValue = $this->fieldList[$table][$field];
				}
			}
		}
		
		// Get the version of the field as we would create it. This is used for comparison purposes to see if the
		// existing field is different to what we now want
		if(is_array($spec_orig)) {
			$spec_orig=DB::getConn()->$spec_orig['type']($spec_orig['parts']);
		}
		
		if($newTable || $fieldValue=='') {
			Profiler::mark('createField');
			
			$this->transCreateField($table, $field, $spec_orig);
			Profiler::unmark('createField');
			$this->alterationMessage("Field $table.$field: created as $spec_orig","created");
		} else if($fieldValue != $specValue) {
			// If enums/sets are being modified, then we need to fix existing data in the table.
			// Update any records where the enum is set to a legacy value to be set to the default.
			// One hard-coded exception is SiteTree - the default for this is Page.
			foreach(array('enum','set') as $enumtype) {
				if(preg_match("/^$enumtype/i",$specValue)) {
					$newStr = preg_replace("/(^$enumtype\s*\(')|('$\).*)/i","",$spec_orig);
					$new = preg_split("/'\s*,\s*'/", $newStr);
				
					$oldStr = preg_replace("/(^$enumtype\s*\(')|('$\).*)/i","", $fieldValue);
					$old = preg_split("/'\s*,\s*'/", $newStr);

					$holder = array();
					foreach($old as $check) {
						if(!in_array($check, $new)) {
							$holder[] = $check;
						}
					}
					if(count($holder)) {
						$default = explode('default ', $spec_orig);
						$default = $default[1];
						if($default == "'SiteTree'") $default = "'Page'";
						$query = "UPDATE \"$table\" SET $field=$default WHERE $field IN (";
						for($i=0;$i+1<count($holder);$i++) {
							$query .= "'{$holder[$i]}', ";
						}
						$query .= "'{$holder[$i]}')";
						DB::query($query);
						$amount = DB::affectedRows();
						$this->alterationMessage("Changed $amount rows to default value of field $field (Value: $default)");
					}
				}
			}
			Profiler::mark('alterField');
			$this->transAlterField($table, $field, $spec_orig);
			Profiler::unmark('alterField');
			$this->alterationMessage("Field $table.$field: changed to $specValue <i style=\"color: #AAA\">(from {$fieldValue})</i>","changed");
		}
		Profiler::unmark('requireField');
	}
Exemple #22
0
 function XML_val($fieldName, $args = null)
 {
     if (isset($this->extraData[$fieldName])) {
         if (isset($_GET['debug_profile'])) {
             Profiler::mark("template({$fieldName})", " on {$this->class} object");
         }
         if (is_object($this->extraData[$fieldName])) {
             $val = $this->extraData[$fieldName]->forTemplate();
         } else {
             $val = $this->extraData[$fieldName];
         }
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("template({$fieldName})", " on {$this->class} object");
         }
         return $val;
     } else {
         return $this->obj->XML_val($fieldName, $args);
     }
 }
 /**
  * Overridden to load all children from Alfresco instead of this node
  * directly
  * 
  * @param boolean $showAll
  * @return DataObjectSet
  */
 public function stageChildren($showAll = false)
 {
     if (!$this->ID) {
         return DataObject::get('SeaMistContentSource');
     }
     $repo = $this->source->getRemoteRepository();
     $children = new DataObjectSet();
     if ($repo->isConnected()) {
         if (isset($_GET['debug_profile'])) {
             Profiler::mark("SeaMistContentItem", "getChildren");
         }
         $childItems = $repo->getChildren($this->cmisObject);
         foreach ($childItems as $child) {
             $item = new SeaMistContentItem($this->source, $child);
             $children->push($item);
         }
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("SeaMistContentItem", "getChildren");
         }
     }
     return $children;
 }
	/**
	 * Update the given HTML content with the appropriate include tags for the registered
	 * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
	 * including a <head> tag. The requirements will insert before the closing <head> tag automatically.
	 *
	 * @todo Calculate $prefix properly
	 * 
	 * @param string $templateFilePath Absolute path for the *.ss template file
	 * @param string $content HTML content that has already been parsed from the $templateFilePath through {@link SSViewer}.
	 * @return string HTML content thats augumented with the requirements before the closing <head> tag.
	 */
	function includeInHTML($templateFile, $content) {
		if(isset($_GET['debug_profile'])) Profiler::mark("Requirements::includeInHTML");
		
		if(strpos($content, '</head') !== false && ($this->javascript || $this->css || $this->customScript || $this->customHeadTags)) {
			$requirements = '';
			$jsRequirements = '';
			
			// Combine files - updates $this->javascript and $this->css 
			$this->process_i18n_javascript(); 
 			$this->process_combined_files(); 
	
			foreach(array_diff_key($this->javascript,$this->blocked) as $file => $dummy) { 
				$path = self::path_for_file($file);
				if($path) {
					$jsRequirements .= "<script type=\"text/javascript\" src=\"$path\"></script>\n";
				}
			}
			
			// add all inline javascript *after* including external files which
			// they might rely on
			if($this->customScript) {
				foreach(array_diff_key($this->customScript,$this->blocked) as $script) { 
					$jsRequirements .= "<script type=\"text/javascript\">\n//<![CDATA[\n";
					$jsRequirements .= "$script\n";
					$jsRequirements .= "\n//]]>\n</script>\n";
				}
			}
			
			foreach(array_diff_key($this->css,$this->blocked) as $file => $params) {  					
				$path = self::path_for_file($file);
				if($path) {
					$media = (isset($params['media']) && !empty($params['media'])) ? " media=\"{$params['media']}\"" : "";
					$requirements .= "<link rel=\"stylesheet\" type=\"text/css\"{$media} href=\"$path\" />\n";
				}
			}
			foreach(array_diff_key($this->customCSS, $this->blocked) as $css) { 
				$requirements .= "<style type=\"text/css\">\n$css\n</style>\n";
			}
			
			foreach(array_diff_key($this->customHeadTags,$this->blocked) as $customHeadTag) { 
				$requirements .= "$customHeadTag\n"; 
			}
	
			if($this->write_js_to_body) {
				// Remove all newlines from code to preserve layout
				$jsRequirements = preg_replace('/>\n*/', '>', $jsRequirements);
				
				// We put script tags into the body, for performance.
				// If your template already has script tags in the body, then we put our script tags at the top of the body.
				// Otherwise, we put it at the bottom.
				$p1 = strripos($content, '<script');
				$p2 = stripos($content, '<body');
				if($p1 !== false && $p1 > $p2) {
					user_error("You have a script tag in the body, moving requirements to top of <body> for compatibilty.  I recommend removing the script tag from your template's body.", E_USER_NOTICE);
					$content = eregi_replace("(<body[^>]*>)", "\\1" . $jsRequirements, $content);
				} else {
					$content = eregi_replace("(</body[^>]*>)", $jsRequirements . "\\1", $content);
				}
				
				// Put CSS at the bottom of the head			
				$content = eregi_replace("(</head[^>]*>)", $requirements . "\\1", $content);
			} else {
				$content = eregi_replace("(</head[^>]*>)", $requirements . "\\1", $content);
				$content = eregi_replace("(</head[^>]*>)", $jsRequirements . "\\1", $content);
			}
		} 
		
		if(isset($_GET['debug_profile'])) Profiler::unmark("Requirements::includeInHTML");
		
		return $content;
	}