Save a redirect by it's slug
@param $slug
@param $postValues
7340
public function saveRedirect($slug, $postValues)
    {
        $redirectObject = RedirectsFactory::createRedirectFromPostValues($postValues);

        $redirects = $this->repository->redirects;
        foreach ($redirects as $key => $redirect) {
            if ($redirect->slug == $slug) {
                $redirects[$key] = $redirectObject;
            }
        }
        $this->repository->redirects = $redirects;
        $this->save();
    }
1225475
public function resolve(array &$routeValues)
    {
        if ($this->name === null || $this->name === '') {
            return false;
        }
        $this->value = $this->name;
        if ($this->lowerCase) {
            $this->value = strtolower($this->value);
        }
        return true;
    }
369468
public function saveDocumentType($slug, $postValues)
    {
        $documentTypeObject = DocumentTypeFactory::createDocumentTypeFromPostValues($postValues);

        $documentTypes = $this->repository->documentTypes;
        foreach ($documentTypes as $key => $documentType) {
            if ($documentType->slug == $slug) {
                $documentTypes[$key] = $documentTypeObject;
            }
        }
        $this->repository->documentTypes = $documentTypes;
        $this->save();
    }
35661
protected function alterPostedValues(array $postedValues)
    {
        foreach ($this->getMeta() as $key => $fieldMeta) {
            /** @var \stdClass $fieldMeta */
            if ($fieldMeta->type === 'checkbox') {
                if (isset($postedValues[$fieldMeta->collection]) && is_array($postedValues[$fieldMeta->collection])) {
                    if (in_array($key, $postedValues[$fieldMeta->collection])) {
                        $postedValues[$key] = $fieldMeta->collection;
                    }
                }
            }
        }
        return $postedValues;
    }
56136
protected function save($value, \WP_Post $post = null){
        update_post_meta($post->ID, $this->name, $value);
    }
1012510
public static function createSitemapItemFromPostValues($postValues)
    {
        if (isset($postValues['title'], $postValues['url'], $postValues['component'], $postValues['template'])) {
            $sitemapObject = new \stdClass();
            $sitemapObject->title = $postValues['title'];
            $sitemapObject->slug = StringUtil::slugify($postValues['title']);
            $sitemapObject->url = $postValues['url'];
            $sitemapObject->component = $postValues['component'];
            $sitemapObject->template = $postValues['template'];
            $sitemapObject->regex = isset($postValues['regex']);
            $sitemapObject->parameters = new \stdClass();
            if (isset($postValues['parameterNames'], $postValues['parameterValues'])) {
                foreach ($postValues['parameterNames'] as $key => $value) {
                    $sitemapObject->parameters->$value = $postValues['parameterValues'][$key];
                }
            }

            return $sitemapObject;
        } else {
            throw new \Exception('Trying to create sitemap item with invalid data.');
        }
    }
931067
public function InsertForApproval($FormPostValues, $Options = array()) {
      $RoleIDs = C('Garden.Registration.ApplicantRoleID');
      if (!$RoleIDs) {
         throw new Exception(T('The default role has not been configured.'), 400);
      }

      // Define the primary key in this model's table.
      $this->DefineSchema();

      // Add & apply any extra validation rules:
      $this->Validation->ApplyRule('Email', 'Email');

      // Make sure that the checkbox val for email is saved as the appropriate enum
      if (array_key_exists('ShowEmail', $FormPostValues))
         $FormPostValues['ShowEmail'] = ForceBool($FormPostValues['ShowEmail'], '0', '1', '0');
      
      if (array_key_exists('Banned', $FormPostValues))
         $FormPostValues['Banned'] = ForceBool($FormPostValues['Banned'], '0', '1', '0');

      $this->AddInsertFields($FormPostValues);

      if ($this->Validate($FormPostValues, TRUE)) {
         // Check for spam.
         $Spam = SpamModel::IsSpam('Registration', $FormPostValues);
         if ($Spam) {
            $this->Validation->AddValidationResult('Spam', 'You are not allowed to register at this time.');
            return;
         }

         $Fields = $this->Validation->ValidationFields(); // All fields on the form that need to be validated (including non-schema field rules defined above)
         $Username = ArrayValue('Name', $Fields);
         $Email = ArrayValue('Email', $Fields);
         $Fields = $this->Validation->SchemaValidationFields(); // Only fields that are present in the schema
         $Fields = RemoveKeyFromArray($Fields, $this->PrimaryKey);

         if (!$this->ValidateUniqueFields($Username, $Email))
            return FALSE;

         // Define the other required fields:
         $Fields['Email'] = $Email;
         $Fields['Roles'] = (array)$RoleIDs;

         // And insert the new user
         $UserID = $this->_Insert($Fields, $Options);
      } else {
         $UserID = FALSE;
      }
      return $UserID;
   }
588605
public function postProcessFormValues(array $formValues)
    {
        $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Neos.Flow.persistence.backendOptions.driver', $formValues['driver']);
        $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Neos.Flow.persistence.backendOptions.dbname', $formValues['dbname']);
        $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Neos.Flow.persistence.backendOptions.user', $formValues['user']);
        $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Neos.Flow.persistence.backendOptions.password', $formValues['password']);
        $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Neos.Flow.persistence.backendOptions.host', $formValues['host']);
        // Postgres natively supports multibyte-UTF8. It does not know utf8mb4, which is the default now
        if ($formValues['driver'] === 'pdo_pgsql') {
            $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Neos.Flow.persistence.backendOptions.charset', 'utf8');
        }
        $this->configurationSource->save(FLOW_PATH_CONFIGURATION . ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, $this->distributionSettings);

        $this->configurationManager->refreshConfiguration();

        $settings = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow');
        $connectionSettings = $settings['persistence']['backendOptions'];
        try {
            $this->connectToDatabase($connectionSettings);
        } catch (\Exception $exception) {
            if (!$exception instanceof DBALException && !$exception instanceof \PDOException) {
                throw $exception;
            }
            try {
                $this->createDatabase($connectionSettings, $formValues['dbname']);
            } catch (DBALException $exception) {
                throw new SetupException(sprintf('Database "%s" could not be created. Please check the permissions for user "%s". DBAL Exception: "%s"', $formValues['dbname'], $formValues['user'], $exception->getMessage()), 1351000841, $exception);
            } catch (\PDOException $exception) {
                throw new SetupException(sprintf('Database "%s" could not be created. Please check the permissions for user "%s". PDO Exception: "%s"', $formValues['dbname'], $formValues['user'], $exception->getMessage()), 1346758663, $exception);
            }
            try {
                $this->connectToDatabase($connectionSettings);
            } catch (DBALException $exception) {
                throw new SetupException(sprintf('Could not connect to database "%s". Please check the permissions for user "%s". DBAL Exception: "%s"', $formValues['dbname'], $formValues['user'], $exception->getMessage()), 1351000864);
            } catch (\PDOException $exception) {
                throw new SetupException(sprintf('Could not connect to database "%s". Please check the permissions for user "%s". PDO Exception: "%s"', $formValues['dbname'], $formValues['user'], $exception->getMessage()), 1346758737);
            }
        }

        $migrationExecuted = Scripts::executeCommand('neos.flow:doctrine:migrate', $settings, false);
        if ($migrationExecuted !== true) {
            throw new SetupException(sprintf('Could not execute database migrations. Please check the permissions for user "%s" and execute "./flow neos.flow:doctrine:migrate" manually.', $formValues['user']), 1346759486);
        }

        $this->resetPolicyRolesCacheAfterDatabaseChanges();
    }
289355
public function save_urls()
    {
        if ($this->isPost()) {
            if (!$this->token->validate('save_urls')) {
                $this->error->add($this->token->getErrorMessage());
            }

            if ($this->post('canonical_url') &&
                !(
                    strpos(strtolower($this->post('canonical_url')), 'http://') === 0 ||
                    strpos(strtolower($this->post('canonical_url')), 'https://') === 0
                )) {
                $this->error->add(t('The canonical URL provided must start with "http://" or "https://".'));
            }
            if ($this->post('canonical_url_alternative') &&
                !(
                    strpos(strtolower($this->post('canonical_url_alternative')), 'http://') === 0 ||
                    strpos(strtolower($this->post('canonical_url_alternative')), 'https://') === 0
                )) {
                $this->error->add(t('The alternative canonical URL provided must start with "http://" or "https://".'));
            }
            if (!$this->error->has()) {
                $globalConfig = $this->app->make('config');
                $siteConfig = $this->getSite()->getConfigRepository();
                $siteConfig->save('seo.canonical_url', $this->post('canonical_url'));
                $siteConfig->save('seo.canonical_url_alternative', $this->post('canonical_url_alternative'));
                $globalConfig->save('concrete.seo.redirect_to_canonical_url', $this->post('redirect_to_canonical_url') ? 1 : 0);
                $siteConfig->save('seo.canonical_tag.enabled', (bool) $this->post('canonical_tag'));

                $urlRewriting = (bool) $this->post('URL_REWRITING');
                $globalConfig->save('concrete.seo.url_rewriting', $urlRewriting);
                $globalConfig->set('concrete.seo.url_rewriting', $urlRewriting);
                $manager = $this->app->make('Concrete\Core\Service\Manager\ServiceManager');
                /* @var \Concrete\Core\Service\Manager\ServiceManager $manager */
                $prettyUrlState = '';
                $services = $manager->getActiveServices();
                if (empty($services)) {
                    $prettyUrlState = 'unrecognized';
                } else {
                    $service = $services[0];
                    if (!$service->getStorage()->canRead()) {
                        $prettyUrlState = 'not-readable';
                    } else {
                        $rule = $service->getGenerator()->getRule('pretty_urls');
                        if ($rule === null) {
                            $prettyUrlState = 'not-needed';
                        } else {
                            $configuration = $service->getStorage()->read();
                            if ($service->getConfigurator()->hasRule($configuration, $rule) === $urlRewriting) {
                                $prettyUrlState = 'not-needed';
                            } else {
                                if ($service->getStorage()->canWrite() === false) {
                                    $prettyUrlState = 'not-writable';
                                } else {
                                    if ($urlRewriting) {
                                        $configuration = $service->getConfigurator()->addRule($configuration, $rule);
                                    } else {
                                        $configuration = $service->getConfigurator()->removeRule($configuration, $rule);
                                    }
                                    $service->getStorage()->write($configuration);
                                    $prettyUrlState = 'saved';
                                }
                            }
                        }
                    }
                }
                $this->redirect('/dashboard/system/seo/urls', 'saved', $prettyUrlState);
            }
        }
        $this->view();
    }
290998
public function saveDocument($postValues, $state = 'unpublished')
    {
        if (!in_array($state, Document::$DOCUMENT_STATES, true)) {
            throw new \RuntimeException('Unsupported document state: ' . $state);
        }
        $oldPath = '/' . $postValues['path'];

        $container = $this->getDocumentContainerByPath($oldPath);
        $documentObject = DocumentFactory::createDocumentFromPostValues($postValues,
            new DocumentTypesStorage($this->repository));
        if ($container->path === '/') {
            $newPath = $container->path . $documentObject->slug;
        } else {
            $newPath = $container->path . '/' . $documentObject->slug;
        }
        $documentObject->path = $newPath;
        $this->repository->getContentRepository()->saveDocument($documentObject, $state);
        return $newPath;
    }
648860
public function addRedirect($postValues)
    {
        $redirectObject = RedirectsFactory::createRedirectFromPostValues($postValues);
        $redirects = $this->repository->redirects;
        $redirects[] = $redirectObject;
        $this->repository->redirects = $redirects;
        $this->save();
    }
1222851
private function save_meta_data( $slug, $data ) {

		$prev = get_post_meta( $this->post->ID, $slug, true );

		if ( null === $data && $prev ) {
			delete_post_meta( $this->post->ID, $slug );
		} elseif ( $data !== $prev ) {
			update_post_meta( $this->post->ID, $slug, $data );
		}

	}
769835
public function convert( $old_slug, $names, $post_id ) {

		$new_slug = $this->maybeUpgradeSlug( $old_slug );
		if ( $new_slug === $old_slug ) {
			return false; // Nothing to convert
		}

		if ( ! is_array( $names ) ) {
			$names = [ $names ];
		}

		$result = false;
		foreach ( $names as $contributors ) {
			$values = oxford_comma_explode( $contributors );
			foreach ( $values as $v ) {
				$result = $this->insert( $v, $post_id, $new_slug );
			}
		}

		return $result;
	}
689089
public function addBrick($postValues)
    {
        $brickObject = BrickFactory::createBrickFromPostValues($postValues);

        $bricks = $this->repository->bricks;
        $bricks[] = $brickObject;
        $this->repository->bricks = $bricks;

        $this->save();
    }
220958
public function save ($post_ID)
    {
        if (!$this->doSave())
            return;
        if ($post_ID === self::SITE)
            update_option($this->identifier, $this->getPostValue());
        else
            update_post_meta($post_ID, $this->identifier, $this->getPostValue());
    }
201026
public static function createRouteFile(string $slug, $controller = 'PostController')
    {
        $stub =  File::get(stubPath('PostType'));
        $route = str_replace('DummySlug', cleanPostTypeSlug($slug), $stub);
        $route = str_replace('DummyController', $controller, $route);
        $bytes_written = File::put(base_path().'/routes/'.$slug.'.php', $route);
        if ($bytes_written === false) {
            die("Error writing to new route file");
        }
        return $route;
    }
311707
public function Save($FormPostValues, $Settings = FALSE) {
      // See if the user's related roles should be saved or not.
      $SaveRoles = GetValue('SaveRoles', $Settings);

      // Define the primary key in this model's table.
      $this->DefineSchema();
      
      // Custom Rule: This will make sure that at least one role was selected if saving roles for this user.
      if ($SaveRoles) {
         $this->Validation->AddRule('OneOrMoreArrayItemRequired', 'function:ValidateOneOrMoreArrayItemRequired');
         // $this->Validation->AddValidationField('RoleID', $FormPostValues);
         $this->Validation->ApplyRule('RoleID', 'OneOrMoreArrayItemRequired');
      }

      // Make sure that checkbox vals are saved as the appropriate value
      
      if (array_key_exists('ShowEmail', $FormPostValues))
         $FormPostValues['ShowEmail'] = ForceBool($FormPostValues['ShowEmail'], '0', '1', '0');

      if (array_key_exists('Banned', $FormPostValues))
         $FormPostValues['Banned'] = ForceBool($FormPostValues['Banned'], '0', '1', '0');
      
      if (array_key_exists('Confirmed', $FormPostValues))
         $FormPostValues['Confirmed'] = ForceBool($FormPostValues['Confirmed'], '0', '1', '0');

      // Validate the form posted values
      
      $UserID = GetValue('UserID', $FormPostValues);
      $User = array();
      $Insert = $UserID > 0 ? FALSE : TRUE;
      if ($Insert) {
         $this->AddInsertFields($FormPostValues);
      } else {
         $this->AddUpdateFields($FormPostValues);
         $User = $this->GetID($UserID, DATASET_TYPE_ARRAY);

         // Block banning the superadmin or System accounts
         if (GetValue('Admin',$User) == 2 && GetValue('Banned', $FormPostValues))
            $this->Validation->AddValidationResult('Banned', 'You may not ban a System user.');
         elseif (GetValue('Admin',$User) && GetValue('Banned', $FormPostValues))
            $this->Validation->AddValidationResult('Banned', 'You may not ban a user with the Admin flag set.');
      }
      
      $this->EventArguments['FormPostValues'] = $FormPostValues;
      $this->FireEvent('BeforeSaveValidation');

      $RecordRoleChange = TRUE;
      
      if ($UserID && GetValue('FixUnique', $Settings)) {
         $UniqueValid = $this->ValidateUniqueFields(GetValue('Name', $FormPostValues), GetValue('Email', $FormPostValues), $UserID, TRUE);
         if (!$UniqueValid['Name'])
            unset($FormPostValues['Name']);
         if (!$UniqueValid['Email'])
            unset($FormPostValues['Email']);
         $UniqueValid = TRUE;
      } else {
         $UniqueValid = $this->ValidateUniqueFields(GetValue('Name', $FormPostValues), GetValue('Email', $FormPostValues), $UserID);
      }
      
      // Add & apply any extra validation rules:
      if (array_key_exists('Email', $FormPostValues) && GetValue('ValidateEmail', $Settings, TRUE))
         $this->Validation->ApplyRule('Email', 'Email');
      
      if ($this->Validate($FormPostValues, $Insert) && $UniqueValid) {
         $Fields = $this->Validation->ValidationFields(); // All fields on the form that need to be validated (including non-schema field rules defined above)
         $RoleIDs = GetValue('RoleID', $Fields, 0);
         $Username = GetValue('Name', $Fields);
         $Email = GetValue('Email', $Fields);
         $Fields = $this->Validation->SchemaValidationFields(); // Only fields that are present in the schema
         // Remove the primary key from the fields collection before saving
         $Fields = RemoveKeyFromArray($Fields, $this->PrimaryKey);
         if (in_array('AllIPAddresses', $Fields) && is_array($Fields['AllIPAddresses'])) {
            $Fields['AllIPAddresses'] = implode(',', $Fields['AllIPAddresses']);
         }
         
         if (!$Insert && array_key_exists('Password', $Fields)) {
            // Encrypt the password for saving only if it won't be hashed in _Insert()
            $PasswordHash = new Gdn_PasswordHash();
            $Fields['Password'] = $PasswordHash->HashPassword($Fields['Password']);
            $Fields['HashMethod'] = 'Vanilla';
         }
         
         // Check for email confirmation.
         if (self::RequireConfirmEmail() && !GetValue('NoConfirmEmail', $Settings)) {
            
            // Email address has changed
            if (isset($Fields['Email']) && (
                     array_key_exists('Confirmed', $Fields) &&
                     $Fields['Confirmed'] == 0 || 
                  (
                     $UserID == Gdn::Session()->UserID && 
                     $Fields['Email'] != Gdn::Session()->User->Email && 
                     !Gdn::Session()->CheckPermission('Garden.Users.Edit')
                  )
               )) {
               
               $Attributes = GetValue('Attributes', Gdn::Session()->User);
               if (is_string($Attributes)) $Attributes = @unserialize($Attributes);
               
               $ConfirmEmailRoleID = C('Garden.Registration.ConfirmEmailRole');
               if (RoleModel::Roles($ConfirmEmailRoleID)) {
                  // The confirm email role is set and it exists so go ahead with the email confirmation.
                  $NewKey = RandomString(8);
                  $EmailKey = TouchValue('EmailKey', $Attributes, $NewKey);
                  $Fields['Attributes'] = serialize($Attributes);
                  $Fields['Confirmed'] = 0;
               }
            }
         }
         
         $this->EventArguments['SaveRoles'] = &$SaveRoles;
         $this->EventArguments['RoleIDs'] = &$RoleIDs;
         $this->EventArguments['Fields'] = &$Fields;
         $this->FireEvent('BeforeSave');
         $User = array_merge($User, $Fields);
         
         // Check the validation results again in case something was added during the BeforeSave event.
         if (count($this->Validation->Results()) == 0) {
            // If the primary key exists in the validated fields and it is a
            // numeric value greater than zero, update the related database row.
            if ($UserID > 0) {
               // If they are changing the username & email, make sure they aren't
               // already being used (by someone other than this user)
               if (ArrayValue('Name', $Fields, '') != '' || ArrayValue('Email', $Fields, '') != '') {
                  if (!$this->ValidateUniqueFields($Username, $Email, $UserID))
                     return FALSE;
               }
               
               if (array_key_exists('Attributes', $Fields) && !is_string($Fields['Attributes'])) {
                  $Fields['Attributes'] = serialize($Fields['Attributes']);
               }
   
               // Perform save DB operation
               $this->SQL->Put($this->Name, $Fields, array($this->PrimaryKey => $UserID));
   
               // Record activity if the person changed his/her photo.
               $Photo = ArrayValue('Photo', $FormPostValues);
               if ($Photo !== FALSE) {
                  if (GetValue('CheckExisting', $Settings)) {
                     $User = $this->GetID($UserID);
                     $OldPhoto = GetValue('Photo', $User);
                  }

                  if (isset($OldPhoto) && $OldPhoto != $Photo) {
                     if (strpos($Photo, '//'))
                        $PhotoUrl = $Photo;
                     else
                        $PhotoUrl = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s'));

                     $ActivityModel = new ActivityModel();
                     if ($UserID == Gdn::Session()->UserID) {
                        $HeadlineFormat = T('HeadlineFormat.PictureChange', '{RegardingUserID,You} changed {ActivityUserID,your} profile picture.');
                     } else {
                        $HeadlineFormat = T('HeadlineFormat.PictureChange.ForUser', '{RegardingUserID,You} changed the profile picture for {ActivityUserID,user}.');
                     }
                     
                     $ActivityModel->Save(array(
                         'ActivityUserID' => $UserID,
                         'RegardingUserID' => Gdn::Session()->UserID,
                         'ActivityType' => 'PictureChange',
                         'HeadlineFormat' => $HeadlineFormat,
                         'Story' => Img($PhotoUrl, array('alt' => T('Thumbnail')))
                         ));
                  }
               }
   
            } else {
               $RecordRoleChange = FALSE;
               if (!$this->ValidateUniqueFields($Username, $Email))
                  return FALSE;
   
               // Define the other required fields:
               $Fields['Email'] = $Email;
               
               $Fields['Roles'] = $RoleIDs;
               // Make sure that the user is assigned to one or more roles:
               $SaveRoles = FALSE;
   
               // And insert the new user.
               $UserID = $this->_Insert($Fields, $Settings);
   
               if ($UserID) {
                  // Report that the user was created.
                  $ActivityModel = new ActivityModel();
                  $ActivityModel->Save(array(
                      'ActivityType' => 'Registration',
                      'ActivityUserID' => $UserID,
                      'HeadlineFormat' => T('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'),
                      'Story' => T('Welcome Aboard!')),
                      FALSE,
                      array('GroupBy' => 'ActivityTypeID'));
                  
                  // Report the creation for mods.
                  $ActivityModel->Save(array(
                      'ActivityType' => 'Registration',
                      'ActivityUserID' => Gdn::Session()->UserID,
                      'RegardingUserID' => $UserID,
                      'NotifyUserID' => ActivityModel::NOTIFY_MODS,
                      'HeadlineFormat' => T('HeadlineFormat.AddUser', '{ActivityUserID,user} added an account for {RegardingUserID,user}.')));
               }
            }
            // Now update the role settings if necessary.
            if ($SaveRoles) {
               // If no RoleIDs were provided, use the system defaults
               if (!is_array($RoleIDs))
                  $RoleIDs = Gdn::Config('Garden.Registration.DefaultRoles');
   
               $this->SaveRoles($UserID, $RoleIDs, $RecordRoleChange);
            }

            // Send the confirmation email.
            if (isset($EmailKey)) {
               if (!is_array($User)) $User = $this->GetID($UserID, DATASET_TYPE_ARRAY);
               $this->SendEmailConfirmationEmail($User, true);
            }

            $this->EventArguments['UserID'] = $UserID;
            $this->FireEvent('AfterSave');
         } else {
            $UserID = FALSE;
         }
      } else {
         $UserID = FALSE;
      }
      
      // Clear cached user data
      if (!$Insert && $UserID) {
         $this->ClearCache($UserID, array('user'));
      }
      
      return $UserID;
   }