/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { Craft::log('Moving the logo from storage/logo to storage/rebrand/logo', LogLevel::Info, true); IOHelper::rename(craft()->path->getStoragePath() . 'logo', craft()->path->getRebrandPath() . 'logo', true); Craft::log('Done moving the logo from storage/logo to storage/rebrand/logo', LogLevel::Info, true); return true; }
/** * Save remote photo * * @param string $photoUrl * @param UserModel $user * * @return bool */ public function saveRemotePhoto($photoUrl, UserModel $user) { $filename = 'photo'; $tempPath = craft()->path->getTempPath() . 'social/userphotos/' . $user->email . '/'; IOHelper::createFolder($tempPath); $tempFilepath = $tempPath . $filename; $client = new \Guzzle\Http\Client(); $response = $client->get($photoUrl)->setResponseBody($tempPath . $filename)->send(); $extension = substr($response->getContentType(), strpos($response->getContentType(), "/") + 1); IOHelper::rename($tempPath . $filename, $tempPath . $filename . '.' . $extension); craft()->users->deleteUserPhoto($user); $image = craft()->images->loadImage($tempPath . $filename . '.' . $extension); $imageWidth = $image->getWidth(); $imageHeight = $image->getHeight(); $dimension = min($imageWidth, $imageHeight); $horizontalMargin = ($imageWidth - $dimension) / 2; $verticalMargin = ($imageHeight - $dimension) / 2; $image->crop($horizontalMargin, $imageWidth - $horizontalMargin, $verticalMargin, $imageHeight - $verticalMargin); craft()->users->saveUserPhoto($filename . '.' . $extension, $image, $user); IOHelper::deleteFile($tempPath . $filename . '.' . $extension); return true; }
/** * @param $manifestData * @param $sourceTempFolder * @param $handle * * @return bool */ public static function doFileUpdate($manifestData, $sourceTempFolder, $handle) { if ($handle == 'craft') { $destDirectory = craft()->path->getAppPath(); $sourceFileDirectory = 'app/'; } else { $destDirectory = craft()->path->getPluginsPath() . $handle . '/'; $sourceFileDirectory = ''; } try { foreach ($manifestData as $row) { if (static::isManifestVersionInfoLine($row)) { continue; } $folder = false; $rowData = explode(';', $row); if (static::isManifestLineAFolder($rowData[0])) { $folder = true; $tempPath = static::cleanManifestFolderLine($rowData[0]); } else { $tempPath = $rowData[0]; } $destFile = IOHelper::normalizePathSeparators($destDirectory . $tempPath); $sourceFile = IOHelper::getRealPath(IOHelper::normalizePathSeparators($sourceTempFolder . '/' . $sourceFileDirectory . $tempPath)); switch (trim($rowData[1])) { // update the file case PatchManifestFileAction::Add: if ($folder) { Craft::log('Updating folder: ' . $destFile, LogLevel::Info, true); $tempFolder = rtrim($destFile, '/') . StringHelper::UUID() . '/'; $tempTempFolder = rtrim($destFile, '/') . '-tmp/'; IOHelper::createFolder($tempFolder); IOHelper::copyFolder($sourceFile, $tempFolder); IOHelper::rename($destFile, $tempTempFolder); IOHelper::rename($tempFolder, $destFile); IOHelper::clearFolder($tempTempFolder); IOHelper::deleteFolder($tempTempFolder); } else { Craft::log('Updating file: ' . $destFile, LogLevel::Info, true); IOHelper::copyFile($sourceFile, $destFile); } break; } } } catch (\Exception $e) { Craft::log('Error updating files: ' . $e->getMessage(), LogLevel::Error); UpdateHelper::rollBackFileChanges($manifestData, $handle); return false; } return true; }
/** * Saves a new or existing user. * * ```php * $user = new UserModel(); * $user->username = '******'; * $user->firstName = 'Tom'; * $user->lastName = 'Foolery'; * $user->email = '*****@*****.**'; * * $user->getContent()->birthYear = 1812; * * $success = craft()->users->saveUser($user); * * if (!$success) * { * Craft::log('Couldn’t save the user "'.$user->username.'"', LogLevel::Error); * } * ``` * * @param UserModel $user The user to be saved. * * @throws \Exception * @return bool Whether the user was saved successfully. */ public function saveUser(UserModel $user) { $isNewUser = !$user->id; if (!$isNewUser) { $userRecord = $this->_getUserRecordById($user->id); if (!$userRecord) { throw new Exception(Craft::t('No user exists with the ID “{id}”.', array('id' => $user->id))); } $oldUsername = $userRecord->username; } else { $userRecord = new UserRecord(); $userRecord->pending = true; } // Set the user record attributes $userRecord->username = $user->username; $userRecord->firstName = $user->firstName; $userRecord->lastName = $user->lastName; $userRecord->photo = $user->photo; $userRecord->email = $user->email; $userRecord->admin = $user->admin; $userRecord->client = $user->client; $userRecord->passwordResetRequired = $user->passwordResetRequired; $userRecord->preferredLocale = $user->preferredLocale; $userRecord->weekStartDay = $user->weekStartDay; $userRecord->unverifiedEmail = $user->unverifiedEmail; $userRecord->validate(); $user->addErrors($userRecord->getErrors()); if (craft()->getEdition() == Craft::Pro) { // Validate any content. if (!craft()->content->validateContent($user)) { $user->addErrors($user->getContent()->getErrors()); } } // If newPassword is set at all, even to an empty string, validate & set it. if ($user->newPassword !== null) { $this->_setPasswordOnUserRecord($user, $userRecord); } if ($user->hasErrors()) { return false; } $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // Fire an 'onBeforeSaveUser' event $event = new Event($this, array('user' => $user, 'isNewUser' => $isNewUser)); $this->onBeforeSaveUser($event); // Is the event is giving us the go-ahead? if ($event->performAction) { // Save the element $success = craft()->elements->saveElement($user, false); // If it didn't work, rollback the transaction in case something changed in onBeforeSaveUser if (!$success) { if ($transaction !== null) { $transaction->rollback(); } return false; } // Now that we have an element ID, save it on the other stuff if ($isNewUser) { $userRecord->id = $user->id; } $userRecord->save(false); if (!$isNewUser) { // Has the username changed? if ($user->username != $oldUsername) { // Rename the user's photo directory $oldFolder = craft()->path->getUserPhotosPath() . $oldUsername; $newFolder = craft()->path->getUserPhotosPath() . $user->username; if (IOHelper::folderExists($newFolder)) { IOHelper::deleteFolder($newFolder); } if (IOHelper::folderExists($oldFolder)) { IOHelper::rename($oldFolder, $newFolder); } } } } else { $success = false; } // Commit the transaction regardless of whether we saved the user, in case something changed // in onBeforeSaveUser if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } if ($success) { // Fire an 'onSaveUser' event $this->onSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if ($this->hasEventHandler('onSaveProfile')) { // Fire an 'onSaveProfile' event (deprecated) $this->onSaveProfile(new Event($this, array('user' => $user))); } // They got unsuspended if ($userRecord->suspended == true && $user->suspended == false) { $this->unsuspendUser($user); } else { if ($userRecord->suspended == false && $user->suspended == true) { $this->suspendUser($user); } } // They got activated if ($userRecord->pending == true && $user->pending == false) { $this->activateUser($user); } } return $success; }
/** * @param $newName * @return bool */ public function rename($newName) { if (!IOHelper::rename($this->getRealPath(), $newName)) { return false; } return true; }
/** * If 'unverifiedEmail' is set on the UserModel, then this method will transfer it to the official email property * and clear the unverified one. * * @param UserModel $user * * @throws Exception */ public function verifyEmailForUser(UserModel $user) { if ($user->unverifiedEmail) { $userRecord = $this->_getUserRecordById($user->id); $oldEmail = $userRecord->email; $userRecord->email = $user->unverifiedEmail; if (craft()->config->get('useEmailAsUsername')) { $userRecord->username = $user->unverifiedEmail; $oldProfilePhotoPath = craft()->path->getUserPhotosPath() . AssetsHelper::cleanAssetName($oldEmail, false, true); $newProfilePhotoPath = craft()->path->getUserPhotosPath() . AssetsHelper::cleanAssetName($user->unverifiedEmail, false, true); // Update the user profile photo folder name, if it exists. if (IOHelper::folderExists($oldProfilePhotoPath)) { IOHelper::rename($oldProfilePhotoPath, $newProfilePhotoPath); } } $userRecord->unverifiedEmail = null; $userRecord->save(); // If the user status is pending, let's activate them. if ($userRecord->pending == true) { $this->activateUser($user); } } }
/** * @inheritDoc BaseAssetSourceType::renameSourceFolder() * * @param AssetFolderModel $folder * @param string $newName * * @return bool */ protected function renameSourceFolder(AssetFolderModel $folder, $newName) { $newFullPath = IOHelper::getParentFolderPath($folder->path) . $newName . '/'; return IOHelper::rename($this->getSourceFileSystemPath() . $folder->path, $this->getSourceFileSystemPath() . $newFullPath); }
/** * Saves a user, or registers a new one. * * @param UserModel $user * @throws Exception * @return bool */ public function saveUser(UserModel $user) { if (($isNewUser = !$user->id) == false) { $userRecord = $this->_getUserRecordById($user->id); if (!$userRecord) { throw new Exception(Craft::t('No user exists with the ID “{id}”', array('id' => $user->id))); } $oldUsername = $userRecord->username; } else { $userRecord = new UserRecord(); } // Set the user record attributes $userRecord->username = $user->username; $userRecord->firstName = $user->firstName; $userRecord->lastName = $user->lastName; $userRecord->email = $user->email; $userRecord->admin = $user->admin; $userRecord->passwordResetRequired = $user->passwordResetRequired; $userRecord->preferredLocale = $user->preferredLocale; $userRecord->validate(); $user->addErrors($userRecord->getErrors()); // If newPassword is set at all, even to an empty string, validate & set it. if ($user->newPassword !== null) { $this->_setPasswordOnUserRecord($user, $userRecord); } if (!$user->hasErrors()) { if ($user->verificationRequired) { $userRecord->status = $user->status = UserStatus::Pending; $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord); } // Fire an 'onBeforeSaveUser' event $this->onBeforeSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if ($isNewUser) { // Create the entry record $elementRecord = new ElementRecord(); $elementRecord->type = ElementType::User; $elementRecord->save(); // Now that we have the entry ID, save it on everything else $user->id = $elementRecord->id; $userRecord->id = $elementRecord->id; } $userRecord->save(false); if (!$isNewUser) { // Has the username changed? if ($user->username != $oldUsername) { // Rename the user's photo directory $oldFolder = craft()->path->getUserPhotosPath() . $oldUsername; $newFolder = craft()->path->getUserPhotosPath() . $user->username; if (IOHelper::folderExists($newFolder)) { IOHelper::deleteFolder($newFolder); } if (IOHelper::folderExists($oldFolder)) { IOHelper::rename($oldFolder, $newFolder); } } } // Update the search index craft()->search->indexElementAttributes($user); if ($isNewUser && $user->verificationRequired) { craft()->templates->registerTwigAutoloader(); craft()->email->sendEmailByKey($user, 'account_activation', array('link' => new \Twig_Markup(craft()->config->getActivateAccountPath($unhashedVerificationCode, $userRecord->uid), craft()->templates->getTwig()->getCharset()))); } // Fire an 'onSaveUser' event $this->onSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); return true; } else { return false; } }
/** * Saves a new or existing user. * * ```php * $user = new UserModel(); * $user->username = '******'; * $user->firstName = 'Tom'; * $user->lastName = 'Foolery'; * $user->email = '*****@*****.**'; * * $user->getContent()->birthYear = 1812; * * $success = craft()->users->saveUser($user); * * if (!$success) * { * Craft::log('Couldn’t save the user "'.$user->username.'"', LogLevel::Error); * } * ``` * * @param UserModel $user The user to be saved. * * @throws \Exception * @return bool Whether the user was saved successfully. */ public function saveUser(UserModel $user) { $isNewUser = !$user->id; if (!$isNewUser) { $userRecord = $this->_getUserRecordById($user->id); if (!$userRecord) { throw new Exception(Craft::t('No user exists with the ID “{id}”', array('id' => $user->id))); } $oldUsername = $userRecord->username; } else { $userRecord = new UserRecord(); } // Set the user record attributes $userRecord->username = $user->username; $userRecord->firstName = $user->firstName; $userRecord->lastName = $user->lastName; $userRecord->photo = $user->photo; $userRecord->email = $user->email; $userRecord->admin = $user->admin; $userRecord->client = $user->client; $userRecord->passwordResetRequired = $user->passwordResetRequired; $userRecord->preferredLocale = $user->preferredLocale; $userRecord->status = $user->status; $userRecord->unverifiedEmail = $user->unverifiedEmail; $userRecord->validate(); $user->addErrors($userRecord->getErrors()); if (craft()->getEdition() == Craft::Pro) { // Validate any content. if (!craft()->content->validateContent($user)) { $user->addErrors($user->getContent()->getErrors()); } } // If newPassword is set at all, even to an empty string, validate & set it. if ($user->newPassword !== null) { $this->_setPasswordOnUserRecord($user, $userRecord, false); } if ($user->hasErrors()) { return false; } $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // If we're going through account verification, in whatever form if ($user->unverifiedEmail) { $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord); } // Set a default status of pending, if one wasn't supplied. if (!$user->status) { $user->status = UserStatus::Pending; } // Fire an 'onBeforeSaveUser' event $this->onBeforeSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if (craft()->elements->saveElement($user, false)) { // Now that we have an element ID, save it on the other stuff if ($isNewUser) { $userRecord->id = $user->id; } $userRecord->save(false); if ($user->unverifiedEmail) { // Temporarily set the unverified email on the UserModel so the verification email goes to the // right place $originalEmail = $user->email; $user->email = $user->unverifiedEmail; try { craft()->email->sendEmailByKey($user, $isNewUser ? 'account_activation' : 'verify_new_email', array('link' => TemplateHelper::getRaw(craft()->config->getActivateAccountPath($unhashedVerificationCode, $userRecord->uid)))); } catch (\phpmailerException $e) { craft()->userSession->setError(Craft::t('User saved, but couldn’t send verification email. Check your email settings.')); } $user->email = $originalEmail; } if (!$isNewUser) { // Has the username changed? if ($user->username != $oldUsername) { // Rename the user's photo directory $oldFolder = craft()->path->getUserPhotosPath() . $oldUsername; $newFolder = craft()->path->getUserPhotosPath() . $user->username; if (IOHelper::folderExists($newFolder)) { IOHelper::deleteFolder($newFolder); } if (IOHelper::folderExists($oldFolder)) { IOHelper::rename($oldFolder, $newFolder); } } } if ($transaction !== null) { $transaction->commit(); } } else { return false; } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } // If we've made it here, everything has been successful so far. // Fire an 'onSaveUser' event $this->onSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if ($this->hasEventHandler('onSaveProfile')) { // Fire an 'onSaveProfile' event (deprecated) $this->onSaveProfile(new Event($this, array('user' => $user))); } return true; }
/** * @throws EtException|\Exception * @return EtModel|null */ public function phoneHome() { try { $missingLicenseKey = empty($this->_model->licenseKey); // No craft/config/license.key file and we can't even write to the config folder. Don't even make the call home. if ($missingLicenseKey && !$this->_isConfigFolderWritable()) { throw new EtException('Craft needs to be able to write to your “craft/config” folder and it can’t.', 10001); } if (!craft()->fileCache->get('etConnectFailure')) { $data = JsonHelper::encode($this->_model->getAttributes(null, true)); $response = \Requests::post($this->_endpoint, array(), $data, $this->_options); if ($response->success) { // Clear the connection failure cached item if it exists. if (craft()->fileCache->get('etConnectFailure')) { craft()->fileCache->delete('etConnectFailure'); } if (isset($this->_options['filename'])) { $fileName = IOHelper::getFileName($this->_options['filename'], false); // If the file name is a UUID, we know it was temporarily set and they want to use the name of the file that was on the sending server. if (StringHelper::isUUID($fileName)) { $contentDisposition = $response->headers->offsetGet('content-disposition'); preg_match("/\"(.*)\"/us", $contentDisposition, $matches); $fileName = $matches[1]; IOHelper::rename($this->_options['filename'], IOHelper::getFolderName($this->_options['filename']) . $fileName); } return $fileName; } $etModel = craft()->et->decodeEtModel($response->body); if ($etModel) { if ($missingLicenseKey && !empty($etModel->licenseKey)) { $this->_setLicenseKey($etModel->licenseKey); } // Do some packageTrial timestamp to datetime conversions. if (!empty($etModel->packageTrials)) { $packageTrials = $etModel->packageTrials; foreach ($etModel->packageTrials as $packageHandle => $expiryTimestamp) { $expiryDate = DateTime::createFromFormat('U', $expiryTimestamp); $currentDate = DateTimeHelper::currentUTCDateTime(); if ($currentDate > $expiryDate) { unset($packageTrials[$packageHandle]); } } $etModel->packageTrials = $packageTrials; } // Cache the license key status and which packages are associated with it craft()->fileCache->set('licenseKeyStatus', $etModel->licenseKeyStatus); craft()->fileCache->set('licensedPackages', $etModel->licensedPackages); craft()->fileCache->set('packageTrials', $etModel->packageTrials); if ($etModel->licenseKeyStatus == LicenseKeyStatus::MismatchedDomain) { craft()->fileCache->set('licensedDomain', $etModel->licensedDomain); } return $etModel; } else { Craft::log('Error in calling ' . $this->_endpoint . ' Response: ' . $response->body, LogLevel::Warning); if (craft()->fileCache->get('etConnectFailure')) { // There was an error, but at least we connected. craft()->fileCache->delete('etConnectFailure'); } } } else { Craft::log('Error in calling ' . $this->_endpoint . ' Response: ' . $response->body, LogLevel::Warning); if (craft()->fileCache->get('etConnectFailure')) { // There was an error, but at least we connected. craft()->fileCache->delete('etConnectFailure'); } } } } catch (EtException $e) { Craft::log('Error in ' . __METHOD__ . '. Message: ' . $e->getMessage(), LogLevel::Error); if (craft()->fileCache->get('etConnectFailure')) { // There was an error, but at least we connected. craft()->fileCache->delete('etConnectFailure'); } throw $e; } catch (\Exception $e) { Craft::log('Error in ' . __METHOD__ . '. Message: ' . $e->getMessage(), LogLevel::Error); // Cache the failure for 5 minutes so we don't try again. craft()->fileCache->set('etConnectFailure', true, 300); } return null; }