/** * Exports the Craft datamodel. * * @param string $file file to write the schema to * @param array $exclude Data to not export * * @return int */ public function actionIndex($file = 'craft/config/schema.yml', array $exclude = null) { $dataTypes = Schematic::getExportableDataTypes(); // If there are data exclusions. if ($exclude !== null) { // Find any invalid data to exclude. $invalidExcludes = array_diff($exclude, $dataTypes); // If any invalid exclusions were specified. if (count($invalidExcludes) > 0) { $errorMessage = 'Invalid exlude'; if (count($invalidExcludes) > 1) { $errorMessage .= 's'; } $errorMessage .= ': ' . implode(', ', $invalidExcludes) . '.'; $errorMessage .= ' Valid exclusions are ' . implode(', ', $dataTypes); // Output an error message outlining what invalid exclusions were specified. echo "\n" . $errorMessage . "\n\n"; return 1; } // Remove any explicitly excluded data types from the list of data types to export. $dataTypes = array_diff($dataTypes, $exclude); } Craft::app()->schematic->exportToYaml($file, $dataTypes); Craft::log(Craft::t('Exported schema to {file}', ['file' => $file])); return 0; }
/** * Logging any messages to Craft. * * @param String $msg * @param String $level * @param Bool $force * @return Void */ public static function log($msg, $level = LogLevel::Info, $force = false) { if (version_compare('2.0', craft()->getVersion(), '>')) { Craft::log($msg, $level, $force); } else { parent::log($msg, $level, $force); } }
/** * @param array $data * * @return array */ public function export(array $data = []) { Craft::log(Craft::t('Exporting Locales')); $locales = $this->getLocalizationService()->getSiteLocales(); $localeDefinitions = []; foreach ($locales as $locale) { $localeDefinitions[] = $locale->getId(); } return $localeDefinitions; }
/** * Converts a currency value to word representation. * * @param float $value * @param string $locale * @param string $currency * @param string $decPoint * * @return string The word representation */ function currencyToWords($value, $locale = 'en_US', $currency = '', $decPoint = null) { $numbersWords = $this->getNumbersWords(); $return = $numbersWords->toCurrency($value, $locale, $currency, $decPoint); if (PEAR::isError($return)) { Craft::log('(Helpers) couldn’t convert “' . $value . '” to its word representation: ' . $return->message); return false; } return $return; }
public function authenticate() { \Craft\Craft::log(__METHOD__, \Craft\LogLevel::Info, true); $socialUser = \Craft\craft()->social->getSocialUserById($this->socialUserId); if ($socialUser) { $this->_id = $socialUser->user->id; $this->username = $socialUser->user->username; $this->errorCode = static::ERROR_NONE; return true; } else { return false; } }
/** * Imports the Craft datamodel. * * @param string $file yml file containing the schema definition * @param string $override_file yml file containing the override values * @param bool $force if set to true items not in the import will be deleted * * @return int */ public function actionIndex($file = 'craft/config/schema.yml', $override_file = 'craft/config/override.yml', $force = false) { if (!IOHelper::fileExists($file)) { $this->usageError(Craft::t('File not found.')); } $result = Craft::app()->schematic->importFromYaml($file, $override_file, $force); if (!$result->hasErrors()) { Craft::log(Craft::t('Loaded schema from {file}', ['file' => $file])); return 0; } Craft::log(Craft::t('There was an error loading schema from {file}', ['file' => $file])); print_r($result->getErrors()); return 1; }
/** * Perform our clean up task. Remove any orphan assets from our crop source. */ public function cleanUp() { $plugin = craft()->plugins->getPlugin('ImageCropper'); $settings = $plugin->getSettings(); $sourceId = $settings->source; $assets = craft()->assets->getFilesBySourceId($sourceId); $validAssetIds = craft()->db->createCommand()->selectDistinct('targetId')->from('relations')->query(); $targetIds = array(); foreach ($validAssetIds as $idArr) { $targetIds[] = $idArr['targetId']; } $task = craft()->tasks->createTask('ImageCropper', 'Cleaning up images', array('assets' => $assets, 'validAssetIds' => $targetIds)); $taskSuccessful = craft()->tasks->runTask($task); if (!$taskSuccessful) { Craft::log('Unable to complete ImageCropperTask. Some failure occurred.'); } }
/** * Attempt to import user settings. * * @param array $user_settings * @param bool $force If set to true user settings not included in the import will be deleted * * @return Result */ public function import(array $user_settings, $force = true) { Craft::log(Craft::t('Importing Users')); // always delete existing fieldlayout first Craft::app()->fields->deleteLayoutsByType(ElementType::User); if (isset($user_settings['fieldLayout'])) { $fieldLayoutDefinition = (array) $user_settings['fieldLayout']; } else { $fieldLayoutDefinition = []; } $fieldLayout = Craft::app()->schematic_fields->getFieldLayout($fieldLayoutDefinition); $fieldLayout->type = ElementType::User; if (!Craft::app()->fields->saveLayout($fieldLayout)) { // Save fieldlayout via craft $this->addErrors($fieldLayout->getAllErrors()); } return $this->getResultModel(); }
/** * @param array $data * * @return array */ public function export(array $data = []) { Craft::log(Craft::t('Exporting Element Index Settings')); $settingDefinitions = []; // Get all element types $elementTypes = $this->getElementsService()->getAllElementTypes(); // Loop through element types foreach ($elementTypes as $elementType) { // Get element type name $elementTypeName = preg_replace('/^Craft\\\\(.*?)ElementType$/', '$1', get_class($elementType)); // Get existing settings for element type $settings = $this->getElementIndexesService()->getSettings($elementTypeName); // If there are settings, export if (is_array($settings)) { // Group by element type and add to definitions $settingDefinitions[$elementTypeName] = $settings; } } return $settingDefinitions; }
/** * Attempt to import tagGroups. * * @param array $tagGroupDefinitions * @param bool $force If set to true tagGroups not included in the import will be deleted * * @return Result */ public function import(array $tagGroupDefinitions, $force = false) { Craft::log(Craft::t('Importing TagGroups')); $tagGroups = Craft::app()->tags->getAllTagGroups('handle'); foreach ($tagGroupDefinitions as $tagGroupHandle => $tagGroupDefinition) { $tagGroup = array_key_exists($tagGroupHandle, $tagGroups) ? $tagGroups[$tagGroupHandle] : new TagGroupModel(); unset($tagGroups[$tagGroupHandle]); $this->populateTagGroup($tagGroup, $tagGroupDefinition, $tagGroupHandle); if (!Craft::app()->tags->saveTagGroup($tagGroup)) { // Save taggroup via craft $this->addErrors($tagGroup->getAllErrors()); continue; } } if ($force) { foreach ($tagGroups as $tagGroup) { Craft::app()->tags->deleteTagGroupById($tagGroup->id); } } return $this->getResultModel(); }
/** * Attempt to import globals. * * @param array $globalSetDefinitions * @param bool $force If set to true globals not included in the import will be deleted * * @return Result */ public function import(array $globalSetDefinitions, $force = false) { Craft::log(Craft::t('Importing Global Sets')); $globalSets = Craft::app()->globals->getAllSets('handle'); foreach ($globalSetDefinitions as $globalSetHandle => $globalSetDefinition) { $global = array_key_exists($globalSetHandle, $globalSets) ? $globalSets[$globalSetHandle] : new GlobalSetModel(); unset($globalSets[$globalSetHandle]); $this->populateGlobalSet($global, $globalSetDefinition, $globalSetHandle); if (!Craft::app()->globals->saveSet($global)) { // Save globalset via craft $this->addErrors($global->getAllErrors()); continue; } } if ($force) { foreach ($globalSets as $globalSet) { Craft::app()->globals->deleteSetById($globalSet->id); } } return $this->getResultModel(); }
public function login($socialUserId) { $rememberMe = true; Craft::log(__METHOD__, LogLevel::Info, true); $this->_identity = new TokenIdentity($socialUserId); $this->_identity->authenticate(); // Was the login successful? if ($this->_identity->errorCode == TokenIdentity::ERROR_NONE) { // Get how long this session is supposed to last. $this->authTimeout = craft()->config->getUserSessionDuration($rememberMe); $id = $this->_identity->getId(); $user = craft()->users->getUserById($id); $states = $this->_identity->getPersistentStates(); // Run any before login logic. if ($this->beforeLogin($id, $states, false)) { $this->changeIdentity($id, $this->_identity->getName(), $states); if ($this->authTimeout) { if ($this->allowAutoLogin) { if ($user) { // Save the necessary info to the identity cookie. $sessionToken = StringHelper::UUID(); $hashedToken = craft()->security->hashData(base64_encode(serialize($sessionToken))); $uid = craft()->users->handleSuccessfulLogin($user, $hashedToken); $data = array($this->getName(), $sessionToken, $uid, $rememberMe ? 1 : 0, craft()->request->getUserAgent(), $this->saveIdentityStates()); $this->saveCookie('', $data, $this->authTimeout); } else { throw new Exception(Craft::t('Could not find a user with Id of {userId}.', array('{userId}' => $this->getId()))); } } else { throw new Exception(Craft::t('{class}.allowAutoLogin must be set true in order to use cookie-based authentication.', array('{class}' => get_class($this)))); } } // Run any after login logic. $this->afterLogin(false); } return !$this->getIsGuest(); } Craft::log('Tried to log in unsuccessfully.', LogLevel::Warning); return false; }
/** * Attempt to import category groups. * * @param array $categoryGroupDefinitions * @param bool $force If set to true category groups not included in the import will be deleted * * @return Result */ public function import(array $categoryGroupDefinitions, $force = false) { Craft::log(Craft::t('Importing Category Groups')); $this->resetCraftCategoriesServiceCache(); $categoryGroups = Craft::app()->categories->getAllGroups('handle'); foreach ($categoryGroupDefinitions as $categoryGroupHandle => $categoryGroupDefinition) { $categoryGroup = array_key_exists($categoryGroupHandle, $categoryGroups) ? $categoryGroups[$categoryGroupHandle] : new CategoryGroupModel(); unset($categoryGroups[$categoryGroupHandle]); $this->populateCategoryGroup($categoryGroup, $categoryGroupDefinition, $categoryGroupHandle); if (!Craft::app()->categories->saveGroup($categoryGroup)) { // Save categorygroup via craft $this->addErrors($categoryGroup->getAllErrors()); continue; } } if ($force) { foreach ($categoryGroups as $categoryGroup) { Craft::app()->categories->deleteGroupById($categoryGroup->id); } } return $this->getResultModel(); }
public function callLever($url) { $cachedResponse = craft()->fileCache->get($url); if ($cachedResponse) { return $cachedResponse; } try { $client = new Client(); $request = $client->get($url); $response = $request->send(); if (!$response->isSuccessful()) { return; } $items = $response->json(); craft()->fileCache->set($url, $items); return $items; } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) { Craft::log(__METHOD__ . " Couldn't get lever response", LogLevel::Info, true); } catch (\Guzzle\Http\Exception\CurlException $e) { Craft::log(__METHOD__ . " " . $e->getMessage(), LogLevel::Info, true); } }
/** * Initialize Sentry. */ public function init() { try { // Get plugin settings $settings = $this->getSettings(); // See if we have to report in devMode if (craft()->config->get('devMode')) { if (!$settings->reportInDevMode) { return; } } $this->configureBackendSentry(); $this->configureFrontendSentry(); } catch (Exception $e) { Craft::log("ERROR: The craft sentry plugin encountered an error wheil trying to initialize: {$e}", LogLevel::Error); } }
/** * Attempt to import sections. * * @param array $sectionDefinitions * @param bool $force If set to true sections not included in the import will be deleted * * @return Result */ public function import(array $sectionDefinitions, $force = false) { Craft::log(Craft::t('Importing Sections')); $sections = Craft::app()->sections->getAllSections('handle'); foreach ($sectionDefinitions as $sectionHandle => $sectionDefinition) { $section = array_key_exists($sectionHandle, $sections) ? $sections[$sectionHandle] : new SectionModel(); unset($sections[$sectionHandle]); if ($sectionDefinition === $this->getSectionDefinition($section, null)) { Craft::log(Craft::t('Skipping `{name}`, no changes detected', ['name' => $section->name])); continue; } if (!array_key_exists('locales', $sectionDefinition)) { $this->addError('`sections[handle].locales` must be defined'); continue; } if (!array_key_exists('entryTypes', $sectionDefinition)) { $this->addError('errors', '`sections[handle].entryTypes` must exist be defined'); continue; } Craft::log(Craft::t('Importing section `{name}`', ['name' => $sectionDefinition['name']])); $this->populateSection($section, $sectionDefinition, $sectionHandle); $this->resetCraftFieldsSectionModelCache($section); // Create initial section record if (!$this->preSaveSection($section)) { $this->addErrors($section->getAllErrors()); continue; } $this->importEntryTypes($section, $sectionDefinition['entryTypes'], $force); // Save section via craft after entrytypes have been created if (!Craft::app()->sections->saveSection($section)) { $this->addErrors($section->getAllErrors()); } } if ($force) { foreach ($sections as $section) { Craft::app()->sections->deleteSectionById($section->id); } } return $this->getResultModel(); }
/** * Return the request * * @param string $handle * * @param array $options * * @throws Exception * * @return mixed */ public function findRequestByHandle($handle) { Craft::log(__METHOD__, LogLevel::Info, true); // Get the request record by its handle // --------------------------------------------- $record = Placid_RequestsRecord::model()->find('handle=:handle', array(':handle' => $handle)); if ($record) { return Placid_RequestsModel::populateModel($record); } else { throw new Exception(Craft::t('Can\'t find request with handle "{handle}"', array('handle' => $handle))); } }
private function _getRemotePlugin($pluginHandle) { Craft::log(__METHOD__, LogLevel::Info, true); $url = 'https://dukt.net/craft/' . $pluginHandle . '/releases.xml'; // devMode $pluginHashes = craft()->config->get('pluginHashes'); if (isset($pluginHashes[$pluginHandle])) { $url = 'https://dukt.net/actions/tracks/updates/' . $pluginHashes[$pluginHandle] . '/develop/xml'; } // or refresh cache and get new updates if cache expired or forced update $xml = @simplexml_load_file($url); if (!$xml) { return null; } // XML from here on $namespaces = $xml->getNameSpaces(true); $versions = array(); $zips = array(); $xml_version = array(); if (!empty($xml->channel->item)) { foreach ($xml->channel->item as $version) { $ee_addon = $version->children($namespaces['ee_addon']); $version_number = (string) $ee_addon->version; $versions[$version_number] = array('xml' => $version, 'addon' => $ee_addon); return $versions[$version_number]; } } else { Craft::log(__METHOD__ . ' : Could not get channel items', LogLevel::Info, true); } }
/** * Get Remote Plugin */ private function _getRemotePlugin($pluginHandle) { Craft::log(__METHOD__, LogLevel::Info, true); $url = 'https://dukt.net/craft/' . $pluginHandle . '/releases.xml'; // or refresh cache and get new updates if cache expired or forced update $client = new Client(); $response = $client->get($url)->send(); $xml = $response->xml(); // XML from here on $namespaces = $xml->getNameSpaces(true); $versions = array(); $zips = array(); $xml_version = array(); if (!empty($xml->channel->item)) { foreach ($xml->channel->item as $version) { $ee_addon = $version->children($namespaces['ee_addon']); $version_number = (string) $ee_addon->version; $versions[$version_number] = array('xml' => $version, 'addon' => $ee_addon); return $versions[$version_number]; } } else { Craft::log(__METHOD__ . ' : Could not get channel items', LogLevel::Info, true); } }
/** * Get the response from a client and request * * @param Client $client a guzzle client * @param object $request a guzzle request object * @return array the response */ private function _getResponse(Client $client, $request) { try { $response = $client->send($request); } catch (RequestException $e) { // If we are in devmode, return the error message Craft::log('Placid - ' . $e->getMessage(), LogLevel::Error); $message = array('failed' => true); if (method_exists($e, 'getResponse')) { $response = $e->getResponse(); $message['statusCode'] = $response->getStatusCode(); } if (craft()->request->isAjaxRequest()) { return $message; } else { return null; } } if ($this->config['cache']) { craft()->placid_cache->set($request->getUrl(), $response->json(), $this->config['duration']); } try { $output = $response->json(); } catch (\RuntimeException $e) { Craft::log('Placid - ' - $e->getMessage(), LogLevel::Error); $output = null; } return $output; }
/** * Logs error * @param $message */ private function logError($message) { Craft::log($message, LogLevel::Error); }
/** * Import usergroups. * * @param array $groupDefinitions * @param bool $force if set to true items not in the import will be deleted * * @return Result */ public function import(array $groupDefinitions, $force = false) { Craft::log(Craft::t('Importing User Groups')); $this->sectionsByHandle = $this->getSectionsService()->getAllSections('handle'); $this->assetSourceByHandle = $this->getAssetSourcesService()->getAllSources('handle'); $this->globalSetsByHandle = $this->getGlobalsService()->getAllSets('handle'); $userGroups = $this->getUserGroupsService()->getAllGroups('handle'); foreach ($groupDefinitions as $groupHandle => $groupDefinition) { $group = array_key_exists($groupHandle, $userGroups) ? $userGroups[$groupHandle] : new UserGroupModel(); unset($userGroups[$groupHandle]); $group->name = $groupDefinition['name']; $group->handle = $groupHandle; if (!$this->getUserGroupsService()->saveGroup($group)) { $this->addErrors($group->getAllErrors()); continue; } $permissions = $this->getPermissions($groupDefinition['permissions']); $this->getUserPermissionsService()->saveGroupPermissions($group->id, $permissions); } if ($force) { foreach ($userGroups as $group) { $this->getUserGroupsService()->deleteGroupById($group->id); } } return $this->getResultModel(); }
/** * Attempt to import fields. * * @param array $groupDefinitions * @param bool $force if set to true items not in the import will be deleted * * @return Result */ public function import(array $groupDefinitions, $force = false) { Craft::log(Craft::t('Importing Fields')); if (!empty($groupDefinitions)) { $contentService = $this->getContentService(); $contentService->fieldContext = 'global'; $contentService->contentTable = 'content'; $this->groups = $this->getFieldsService()->getAllGroups('name'); $this->fields = $this->getFieldsService()->getAllFields('handle'); foreach ($groupDefinitions as $name => $fieldDefinitions) { try { $this->beginTransaction(); $group = $this->createFieldGroupModel($name); $this->importFields($fieldDefinitions, $group); $this->commitTransaction(); } catch (\Exception $e) { $this->rollbackTransaction(); $this->addError($e->getMessage()); } $this->unsetData($name, $fieldDefinitions); } if ($force) { // Remove not imported data $this->deleteFieldsAndGroups(); } } return $this->getResultModel(); }
/** * @param array $data * * @return array */ public function export(array $data = []) { Craft::log(Craft::t('Exporting Plugins')); $plugins = $this->getPluginService()->getPlugins(false); $pluginDefinitions = []; foreach ($plugins as $plugin) { $handle = preg_replace('/^Craft\\\\(.*?)Plugin$/', '$1', get_class($plugin)); $pluginDefinitions[$handle] = $this->getPluginDefinition($plugin); } ksort($pluginDefinitions); return $pluginDefinitions; }
/** * Get API Object */ private function getApiObject() { $handle = $this->oauthHandle; // provider $provider = craft()->oauth->getProvider($handle); if ($provider) { // token $token = craft()->analytics->getToken(); if ($token) { // make token compatible with Google library $arrayToken = array('created' => 0, 'access_token' => $token->accessToken, 'expires_in' => $token->endOfLife); $arrayToken = json_encode($arrayToken); // client $client = new Google_Client(); $client->setApplicationName('Google+ PHP Starter Application'); $client->setClientId('clientId'); $client->setClientSecret('clientSecret'); $client->setRedirectUri('redirectUri'); $client->setAccessToken($arrayToken); $api = new Google_Service_Analytics($client); return $api; } else { Craft::log(__METHOD__ . ' : No token defined', LogLevel::Info, true); return false; } } else { Craft::log(__METHOD__ . ' : Could not get provider connected', LogLevel::Info, true); return false; } }
/** * Export all asset sources. * * @param array $data * * @return array */ public function export(array $data = []) { Craft::log(Craft::t('Exporting Asset Sources')); $assetSources = $this->getAssetSourcesService()->getAllSources(); $assetSourceDefinitions = []; foreach ($assetSources as $assetSource) { $assetSourceDefinitions[$assetSource->handle] = $this->getAssetSourceDefinition($assetSource); } return $assetSourceDefinitions; }
/** * Internal error handler * * @internal Internal error handler * @param string $message Error message * @param string $file Filename * @param integer $line Line number * @param integer $code Error code * @return void */ private static function __triggerError($message, $file, $line, $code = 0) { \Craft\Craft::log("GoogleCloud: Error: " . $message, \Craft\LogLevel::Error); if (self::$useExceptions) { throw new GCException($message, $file, $line, $code); } else { trigger_error($message, E_USER_WARNING); } }
/** * Import field group fields. * * @param array $fieldDefinitions * @param FieldGroupModel $group * * @throws \Exception */ private function importFields(array $fieldDefinitions, FieldGroupModel $group) { $fieldFactory = $this->getFieldFactory(); foreach ($fieldDefinitions as $fieldHandle => $fieldDef) { $field = $this->getFieldModel($fieldHandle); $schematicFieldModel = $fieldFactory->build($fieldDef['type']); if ($schematicFieldModel->getDefinition($field, true) === $fieldDef) { Craft::log(Craft::t('Skipping `{name}`, no changes detected', ['name' => $field->name])); continue; } Craft::log(Craft::t('Importing `{name}`', ['name' => $fieldDef['name']])); $schematicFieldModel->populate($fieldDef, $field, $fieldHandle, $group); $this->saveFieldModel($field); } }
/** * Performs a get request on the Twitter API * * @param string $uri * @param array $params * @param array $headers * @param array $postFields * @param bool $enableCache * @return array|null */ public function get($uri, $params = array(), $headers = array(), $enableCache = false, $cacheExpire = 0) { if (!craft()->twitter_plugin->checkDependencies()) { throw new Exception("Twitter plugin dependencies are not met"); } // get from cache if (craft()->config->get('disableCache', 'twitter') == true) { $enableCache = false; } if ($enableCache) { $token = craft()->twitter_oauth->getToken(); $key = 'twitter.' . md5($uri . serialize(array($token, $params))); $response = craft()->fileCache->get($key); if ($response) { return $response; } } // run request try { $response = $this->request('get', $uri, $params, $headers); // cache response if ($enableCache) { craft()->fileCache->set($key, $response, $cacheExpire); } return $response; } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) { Craft::log('Twitter API Error: ' . __METHOD__ . " Couldn't get twitter response", LogLevel::Info, true); } catch (\Guzzle\Http\Exception\CurlException $e) { Craft::log('Twitter API Error: ' . __METHOD__ . " " . $e->getMessage(), LogLevel::Info, true); } }
/** * Exports the Craft datamodel. * * @param string $file file to write the schema to * * @return int */ public function actionIndex($file = 'craft/config/schema.yml') { Craft::app()->schematic->exportToYaml($file); Craft::log(Craft::t('Exported schema to {file}', ['file' => $file])); return 0; }