/**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Changing tasks table settings column to mediumtext.', LogLevel::Info, true);
     $this->alterColumn('tasks', 'settings', array('column' => ColumnType::MediumText));
     Craft::log('Done changing tasks table settings column to mediumtext.', LogLevel::Info, true);
     return true;
 }
 private function transferSystemToken($namespace)
 {
     try {
         if (file_exists(CRAFT_PLUGINS_PATH . 'oauth/vendor/autoload.php')) {
             require_once CRAFT_PLUGINS_PATH . 'oauth/vendor/autoload.php';
         }
         if (class_exists('OAuth\\OAuth1\\Token\\StdOAuth1Token')) {
             // get token record
             $row = craft()->db->createCommand()->select('*')->from('oauth_old_tokens')->where('namespace = :namespace', array(':namespace' => $namespace))->queryRow();
             if ($row) {
                 // transform token
                 $token = @unserialize(base64_decode($row['token']));
                 if ($token) {
                     // oauth 1
                     $newToken = new \OAuth\OAuth1\Token\StdOAuth1Token();
                     $newToken->setAccessToken($token->access_token);
                     $newToken->setRequestToken($token->access_token);
                     $newToken->setRequestTokenSecret($token->secret);
                     $newToken->setAccessTokenSecret($token->secret);
                     $this->saveToken($newToken);
                 } else {
                     Craft::log('Token error.', LogLevel::Info, true);
                 }
             } else {
                 Craft::log('Token record error.', LogLevel::Info, true);
             }
         } else {
             Craft::log('Class error.', LogLevel::Info, true);
         }
     } catch (\Exception $e) {
         Craft::log($e->getMessage(), LogLevel::Info, true);
     }
 }
Esempio n. 3
0
 /**
  *
  */
 public function init()
 {
     try {
         parent::init();
     } catch (\CDbException $e) {
         Craft::log($e->getMessage(), LogLevel::Error);
         $missingPdo = false;
         // TODO: Multi-db driver check.
         if (!extension_loaded('pdo')) {
             $missingPdo = true;
             $messages[] = Craft::t('Craft requires the PDO extension to operate.');
         }
         if (!extension_loaded('pdo_mysql')) {
             $missingPdo = true;
             $messages[] = Craft::t('Craft requires the PDO_MYSQL driver to operate.');
         }
         if (!$missingPdo) {
             Craft::log($e->getMessage(), LogLevel::Error);
             $messages[] = Craft::t('There is a problem connecting to the database with the credentials supplied in your db config file.');
         }
     } catch (\Exception $e) {
         Craft::log($e->getMessage(), LogLevel::Error);
         $messages[] = Craft::t('There is a problem connecting to the database with the credentials supplied in your db config file.');
     }
     if (!empty($messages)) {
         throw new DbConnectException(Craft::t('Database configuration errors: {errors}', array('errors' => implode(PHP_EOL, $messages))));
     }
     $this->_isDbConnectionValid = true;
     // Now that we've validated the config and connection, set extra db logging if devMode is enabled.
     if (craft()->config->get('devMode')) {
         $this->enableProfiling = true;
         $this->enableParamLogging = true;
     }
 }
 /**
  * Sends the push notification.
  *
  * @param $args
  *
  * @return int
  */
 public function actionSend($args)
 {
     // Log invocation
     Craft::log($this->getCommandRunner()->getScriptName());
     // Get notification id
     $id = $args[0];
     // Validate id
     if (!is_numeric($id)) {
         $this->usageError(Craft::t('The argument must be a numeric id'));
     }
     // Get notification
     $notification = craft()->pushNotifications_notifications->getNotificationById($id);
     // Validate notification
     if (!$notification) {
         $this->usageError(Craft::t('No notification found with id "{id}"', array('id' => $id)));
     }
     try {
         // Send notification
         $platforms = craft()->pushNotifications_push->sendNotification($notification);
     } catch (\Exception $e) {
         $this->usageError($e->getMessage());
     }
     // Count devices
     $devices = 0;
     foreach ($platforms as $platform) {
         $devices += $platform;
     }
     // Show result
     echo Craft::t('Notification sent to {devices} device(s)', array('devices' => $devices)) . "\n";
     exit(0);
 }
 /**
  * Saves a global set.
  */
 public function actionSaveSet()
 {
     $this->requirePostRequest();
     $globalSet = new GlobalSetModel();
     // Set the simple stuff
     $globalSet->id = craft()->request->getPost('setId');
     $globalSet->name = craft()->request->getPost('name');
     $globalSet->handle = craft()->request->getPost('handle');
     // Set the field layout
     $fieldLayout = craft()->fields->assembleLayoutFromPost(false);
     $fieldLayout->type = ElementType::GlobalSet;
     $globalSet->setFieldLayout($fieldLayout);
     // Save it
     if (craft()->globals->saveSet($globalSet)) {
         craft()->userSession->setNotice(Craft::t('Global set saved.'));
         // TODO: Remove for 2.0
         if (isset($_POST['redirect']) && strpos($_POST['redirect'], '{setId}') !== false) {
             Craft::log('The {setId} token within the ‘redirect’ param on globals/saveSet requests has been deprecated. Use {id} instead.', LogLevel::Warning);
             $_POST['redirect'] = str_replace('{setId}', '{id}', $_POST['redirect']);
         }
         $this->redirectToPostedUrl($globalSet);
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save global set.'));
     }
     // Send the global set back to the template
     craft()->urlManager->setRouteVariables(array('globalSet' => $globalSet));
 }
 /**
  * Saves a field.
  */
 public function actionSaveField()
 {
     $this->requirePostRequest();
     $field = new FieldModel();
     $field->id = craft()->request->getPost('fieldId');
     $field->groupId = craft()->request->getRequiredPost('group');
     $field->name = craft()->request->getPost('name');
     $field->handle = craft()->request->getPost('handle');
     $field->instructions = craft()->request->getPost('instructions');
     $field->translatable = (bool) craft()->request->getPost('translatable');
     $field->type = craft()->request->getRequiredPost('type');
     $typeSettings = craft()->request->getPost('types');
     if (isset($typeSettings[$field->type])) {
         $field->settings = $typeSettings[$field->type];
     }
     if (craft()->fields->saveField($field)) {
         craft()->userSession->setNotice(Craft::t('Field saved.'));
         // TODO: Remove for 2.0
         if (isset($_POST['redirect']) && strpos($_POST['redirect'], '{fieldId}') !== false) {
             Craft::log('The {fieldId} token within the ‘redirect’ param on fields/saveField requests has been deprecated. Use {id} instead.', LogLevel::Warning);
             $_POST['redirect'] = str_replace('{fieldId}', '{id}', $_POST['redirect']);
         }
         $this->redirectToPostedUrl($field);
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save field.'));
     }
     // Send the field back to the template
     craft()->urlManager->setRouteVariables(array('field' => $field));
 }
 /**
  * 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;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Adding locked column to users table...', LogLevel::Info, true);
     $this->addColumnAfter('users', 'locked', array(AttributeType::Bool, 'required' => true), 'status');
     Craft::log('Adding suspended column to users table...', LogLevel::Info, true);
     $this->addColumnAfter('users', 'suspended', array(AttributeType::Bool, 'required' => true), 'locked');
     Craft::log('Adding pending column to users table...', LogLevel::Info, true);
     $this->addColumnAfter('users', 'pending', array(AttributeType::Bool, 'required' => true), 'suspended');
     Craft::log('Adding archived column to users table...', LogLevel::Info, true);
     $this->addColumnAfter('users', 'archived', array(AttributeType::Bool, 'required' => true), 'pending');
     Craft::log('Updating locked users...', LogLevel::Info, true);
     $this->update('users', array('locked' => 1), array('status' => 'locked'));
     $this->update('users', array('locked' => 0), 'locked IS NULL');
     Craft::log('Updating pending users...', LogLevel::Info, true);
     $this->update('users', array('pending' => 1), array('status' => 'pending'));
     $this->update('users', array('pending' => 0), 'pending IS NULL');
     Craft::log('Updating archived users...', LogLevel::Info, true);
     $this->update('users', array('archived' => 1), array('status' => 'archived'));
     $this->update('users', array('archived' => 0), 'archived IS NULL');
     Craft::log('Updating suspended users...', LogLevel::Info, true);
     $this->update('users', array('suspended' => 1), array('status' => 'suspended'));
     $this->update('users', array('suspended' => 0), 'suspended IS NULL');
     Craft::log('Dropping status column from users table...', LogLevel::Info, true);
     $this->dropColumn('users', 'status');
     Craft::log('Done updating user statuses.', LogLevel::Info, true);
     return true;
 }
 public function init()
 {
     Craft::log(__METHOD__, LogLevel::Info, true);
     // request params
     $providerHandle = craft()->request->getParam('provider');
     $namespace = craft()->request->getParam('namespace');
     $scope = unserialize(base64_decode(craft()->request->getParam('scope')));
     // userMode
     $userMode = false;
     if (!$namespace) {
         $userMode = true;
     }
     // clean session vars
     if (!craft()->httpSession->get('oauth.social')) {
         craft()->oauth->sessionClean();
     }
     // set session vars
     craft()->oauth->sessionAdd('oauth.providerClass', $providerHandle);
     craft()->oauth->sessionAdd('oauth.userMode', $userMode);
     craft()->oauth->sessionAdd('oauth.referer', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
     craft()->oauth->sessionAdd('oauth.scope', $scope);
     // redirect
     $url = UrlHelper::getActionUrl('oauth/public/connect/', array('provider' => $providerHandle, 'namespace' => $namespace));
     $this->redirect($url);
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Renaming `social_accounts` table to `social_login_accounts`', LogLevel::Info, true);
     MigrationHelper::renameTable('social_accounts', 'social_login_accounts');
     Craft::log('Done renaming `social_accounts` table to `social_login_accounts`', LogLevel::Info, true);
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     if (!craft()->db->schema->columnExists('content', 'title')) {
         $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId();
         // Add the new 'title' column to the content table
         $this->addColumnAfter('content', 'title', array('column' => ColumnType::Varchar), 'locale');
         // Migrate the entry titles
         $entries = craft()->db->createCommand()->select('entryId, locale, title')->from('entries_i18n')->queryAll();
         foreach ($entries as $entry) {
             $this->insertOrUpdate('content', array('elementId' => $entry['entryId'], 'locale' => $entry['locale']), array('title' => $entry['title']));
         }
         unset($entries);
         // Delete the old entry titles column
         $this->dropIndex('entries_i18n', 'title');
         $this->dropColumn('entries_i18n', 'title');
         // Create asset titles based on the filenames
         $assets = craft()->db->createCommand()->select('id, filename')->from('assetfiles')->queryAll();
         foreach ($assets as $asset) {
             $filename = pathinfo($asset['filename'], PATHINFO_FILENAME);
             $filename = str_replace('_', ' ', $filename);
             $this->insertOrUpdate('content', array('elementId' => $asset['id'], 'locale' => $primaryLocaleId), array('title' => $filename));
         }
         unset($assets);
         // Create the index on the new titles column
         craft()->db->createCommand()->createIndex('content', 'title');
     } else {
         Craft::log('Tried to add a `title` column to the `content` table, but there is already one there.', LogLevel::Warning);
     }
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Changing asset index data table uri column to text.', LogLevel::Info, true);
     $this->alterColumn('assetindexdata', 'uri', array('column' => ColumnType::Text));
     Craft::log('Done changing asset index data table uri column to text.', LogLevel::Info, true);
     return true;
 }
 public function safeUp()
 {
     $productIds = craft()->db->createCommand()->select('id')->from("market_products")->queryColumn();
     $variantProductIds = craft()->db->createCommand()->select('productId')->from("market_variants")->queryColumn();
     $variantProductIds = array_unique($variantProductIds);
     foreach ($variantProductIds as $vId) {
         if (!in_array($vId, $productIds)) {
             Craft::log("Deleting variant with productId: " . $vId);
             craft()->db->createCommand()->delete('market_variants', 'productId=:id', array(':id' => $vId));
         }
     }
     $types = ['Market_Product', 'Market_Variant', 'Market_Order'];
     foreach ($types as $type) {
         $elements = craft()->db->createCommand()->select('id')->from('elements')->where('type = :type', [':type' => $type])->queryColumn();
         $tableName = strtolower($type) . "s";
         $marketTableElements = craft()->db->createCommand()->select('id')->from($tableName)->queryColumn();
         $count = 0;
         foreach ($elements as $p) {
             if (!in_array($p, $marketTableElements)) {
                 Craft::log("Deleting " . $type . " element not in market table id: " . $p);
                 craft()->db->createCommand()->delete('elements', 'id=:id', array(':id' => $p));
                 $count++;
             }
         }
         Craft::log("Total " . $type . " elements removed as they are not in market tables: " . $count);
     }
     $table = craft()->db->schema->getTable('craft_market_variants');
     if (isset($table->columns['deletedAt'])) {
         $this->dropColumn('market_variants', 'deletedAt');
     }
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     // unique index for 'userMapping' and 'provider'
     $tableName = 'oauth_tokens';
     $providersTable = $this->dbConnection->schema->getTable('{{' . $tableName . '}}');
     if ($providersTable) {
         $columns = 'userMapping, provider';
         $unique = true;
         $this->createIndex($tableName, $columns, $unique);
     } else {
         Craft::log('Could not find an `' . $tableName . '` table. Wut?', LogLevel::Error);
     }
     // unique index for 'userId' and 'provider'
     $tableName = 'oauth_tokens';
     $providersTable = $this->dbConnection->schema->getTable('{{' . $tableName . '}}');
     if ($providersTable) {
         $columns = 'userId, provider';
         $unique = true;
         $this->createIndex($tableName, $columns, $unique);
     } else {
         Craft::log('Could not find an `' . $tableName . '` table. Wut?', LogLevel::Error);
     }
     // unique index for 'namespace' and 'provider'
     $tableName = 'oauth_tokens';
     $providersTable = $this->dbConnection->schema->getTable('{{' . $tableName . '}}');
     if ($providersTable) {
         $columns = 'namespace, provider';
         $unique = true;
         $this->createIndex($tableName, $columns, $unique);
     } else {
         Craft::log('Could not find an `' . $tableName . '` table. Wut?', LogLevel::Error);
     }
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     // Create the categorygroups table
     if (!craft()->db->tableExists('categorygroups')) {
         Craft::log('Creating the categorygroups table', LogLevel::Info, true);
         $this->createTable('categorygroups', array('structureId' => array('column' => ColumnType::Int, 'null' => false), 'fieldLayoutId' => array('column' => ColumnType::Int), 'name' => array('column' => ColumnType::Varchar, 'required' => true), 'handle' => array('column' => ColumnType::Varchar, 'required' => true), 'hasUrls' => array('column' => ColumnType::Bool, 'required' => true, 'default' => true), 'template' => array('column' => ColumnType::Varchar, 'maxLength' => 500)));
         $this->createIndex('categorygroups', 'name', true);
         $this->createIndex('categorygroups', 'handle', true);
         $this->addForeignKey('categorygroups', 'structureId', 'structures', 'id', 'CASCADE');
         $this->addForeignKey('categorygroups', 'fieldLayoutId', 'fieldlayouts', 'id', 'SET NULL');
     }
     // Create the categorygroups_i18n table
     if (!craft()->db->tableExists('categorygroups_i18n')) {
         Craft::log('Creating the categorygroups_i18n table', LogLevel::Info, true);
         $this->createTable('categorygroups_i18n', array('groupId' => array('column' => ColumnType::Int, 'required' => true), 'locale' => array('column' => ColumnType::Locale, 'required' => true), 'urlFormat' => array('column' => ColumnType::Varchar), 'nestedUrlFormat' => array('column' => ColumnType::Varchar)));
         $this->createIndex('categorygroups_i18n', 'groupId,locale', true);
         $this->addForeignKey('categorygroups_i18n', 'groupId', 'categorygroups', 'id', 'CASCADE');
         $this->addForeignKey('categorygroups_i18n', 'locale', 'locales', 'locale', 'CASCADE', 'CASCADE');
     }
     // Create the categories table
     if (!craft()->db->tableExists('categories')) {
         Craft::log('Creating the categories table', LogLevel::Info, true);
         $this->createTable('categories', array('id' => array('column' => ColumnType::Int, 'required' => true, 'primaryKey' => true), 'groupId' => array('column' => ColumnType::Int, 'required' => true)), null, false);
         $this->addForeignKey('categories', 'id', 'elements', 'id', 'CASCADE');
         $this->addForeignKey('categories', 'groupId', 'categorygroups', 'id', 'CASCADE');
     }
     return true;
 }
 /**
  * @param string $template
  *
  * @return TemplateLoaderException
  */
 public function __construct($template)
 {
     $this->template = $template;
     $message = Craft::t('Unable to find the template “{template}”.', array('template' => $this->template));
     Craft::log($message, LogLevel::Error);
     parent::__construct($message);
 }
Esempio n. 17
0
 /**
  * Settings
  *
  * @return null
  */
 public function actionSettings()
 {
     craft()->twitter_plugin->requireDependencies();
     $plugin = craft()->plugins->getPlugin('twitter');
     $variables = array('provider' => false, 'account' => false, 'token' => false, 'error' => false);
     $provider = craft()->oauth->getProvider('twitter');
     if ($provider && $provider->isConfigured()) {
         $token = craft()->twitter_oauth->getToken();
         if ($token) {
             try {
                 $account = craft()->twitter_cache->get(['getAccount', $token]);
                 if (!$account) {
                     $account = $provider->getAccount($token);
                     craft()->twitter_cache->set(['getAccount', $token], $account);
                 }
                 if ($account) {
                     Craft::log("Twitter OAuth Account:\r\n" . print_r($account, true), LogLevel::Info);
                     $variables['account'] = $account;
                     $variables['settings'] = $plugin->getSettings();
                 }
             } catch (\Exception $e) {
                 if (method_exists($e, 'getResponse')) {
                     Craft::log("Couldn’t get account: " . $e->getResponse(), LogLevel::Error);
                 } else {
                     Craft::log("Couldn’t get account: " . $e->getMessage(), LogLevel::Error);
                 }
                 $variables['error'] = $e->getMessage();
             }
         }
         $variables['token'] = $token;
         $variables['provider'] = $provider;
     }
     $this->renderTemplate('twitter/settings', $variables);
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     $this->addColumnAfter('oauth_tokens', 'accessToken', array(ColumnType::Varchar, 'required' => false), 'pluginHandle');
     $this->addColumnAfter('oauth_tokens', 'secret', array(ColumnType::Varchar, 'required' => false), 'accessToken');
     $this->addColumnAfter('oauth_tokens', 'endOfLife', array(ColumnType::Varchar, 'required' => false), 'secret');
     $this->addColumnAfter('oauth_tokens', 'refreshToken', array(ColumnType::Varchar, 'required' => false), 'endOfLife');
     require_once CRAFT_PLUGINS_PATH . 'oauth/vendor/autoload.php';
     $rows = craft()->db->createCommand()->select('*')->from('oauth_tokens')->queryAll();
     foreach ($rows as $row) {
         $token = $row['encodedToken'];
         $token = @unserialize(base64_decode($token));
         if ($token && is_object($token)) {
             $attributes = array();
             $attributes['accessToken'] = $token->getAccessToken();
             if (method_exists($token, 'getAccessTokenSecret')) {
                 $attributes['secret'] = $token->getAccessTokenSecret();
             }
             $attributes['endOfLife'] = $token->getEndOfLife();
             $attributes['refreshToken'] = $token->getRefreshToken();
             $this->update('oauth_tokens', $attributes, 'id = :id', array(':id' => $row['id']));
         }
     }
     Craft::log('Dropping the encodedToken column from the structures table...', LogLevel::Info, true);
     $this->dropColumn('oauth_tokens', 'encodedToken');
     Craft::log('Done dropping the encodedToken column from the structures table.', LogLevel::Info, true);
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     if (!craft()->db->columnExists('elements_i18n', 'slug')) {
         Craft::log('Creating an elements_i18n.slug column.', LogLevel::Info, true);
         $this->addColumnAfter('elements_i18n', 'slug', ColumnType::Varchar, 'locale');
     }
     if (craft()->db->tableExists('entries_i18n')) {
         Craft::log('Copying the slugs from entries_i18n into elements_i18n.', LogLevel::Info, true);
         $rows = craft()->db->createCommand()->select('entryId, locale, slug')->from('entries_i18n')->queryAll();
         foreach ($rows as $row) {
             $this->update('elements_i18n', array('slug' => $row['slug']), array('elementId' => $row['entryId'], 'locale' => $row['locale']));
         }
         Craft::log('Dropping the entries_i18n table.');
         $this->dropTable('entries_i18n');
     }
     if (!craft()->db->columnExists('elements_i18n', 'enabled')) {
         Craft::log('Creating an elements_i18n.enabled column.', LogLevel::Info, true);
         $this->addColumnAfter('elements_i18n', 'enabled', array('column' => ColumnType::Bool, 'default' => true), 'uri');
     }
     MigrationHelper::refresh();
     MigrationHelper::dropIndexIfExists('elements_i18n', array('slug', 'locale'));
     MigrationHelper::dropIndexIfExists('elements_i18n', array('enabled'));
     $this->createIndex('elements_i18n', 'slug,locale');
     $this->createIndex('elements_i18n', 'enabled');
     return true;
 }
Esempio n. 20
0
 /**
  * Fetches and parses an RSS or Atom feed, and returns its items.
  *
  * Each element in the returned array will have the following keys:
  *
  * - **authors** – An array of the item’s authors, where each sub-element has the following keys:
  *     - **name** – The author’s name
  *     - **url** – The author’s URL
  *     - **email** – The author’s email
  * - **categories** – An array of the item’s categories, where each sub-element has the following keys:
  *     - **term** – The category’s term
  *     - **scheme** – The category’s scheme
  *     - **label** – The category’s label
  * - **content** – The item’s main content.
  * - **contributors** – An array of the item’s contributors, where each sub-element has the following keys:
  *     - **name** – The contributor’s name
  *     - **url** – The contributor’s URL
  *     - **email** – The contributor’s email
  * - **date** – A {@link DateTime} object representing the item’s date.
  * - **dateUpdated** – A {@link DateTime} object representing the item’s last updated date.
  * - **permalink** – The item’s URL.
  * - **summary** – The item’s summary content.
  * - **title** – The item’s title.
  *
  * @param string $url           The feed’s URL.
  * @param int    $limit         The maximum number of items to return. Default is 0 (no limit).
  * @param int    $offset        The number of items to skip. Defaults to 0.
  * @param string $cacheDuration Any valid [PHP time format](http://www.php.net/manual/en/datetime.formats.time.php).
  *
  * @return array|string The list of feed items.
  */
 public function getFeedItems($url, $limit = 0, $offset = 0, $cacheDuration = null)
 {
     $items = array();
     if (!extension_loaded('dom')) {
         Craft::log('Craft needs the PHP DOM extension (http://www.php.net/manual/en/book.dom.php) enabled to parse feeds.', LogLevel::Warning);
         return $items;
     }
     if (!$cacheDuration) {
         $cacheDuration = craft()->config->getCacheDuration();
     } else {
         $cacheDuration = DateTimeHelper::timeFormatToSeconds($cacheDuration);
     }
     $feed = new \SimplePie();
     $feed->set_feed_url($url);
     $feed->set_cache_location(craft()->path->getCachePath());
     $feed->set_cache_duration($cacheDuration);
     $feed->init();
     // Something went wrong.
     if ($feed->error()) {
         Craft:
         log('There was a problem parsing the feed: ' . $feed->error(), LogLevel::Warning);
         return array();
     }
     foreach ($feed->get_items($offset, $limit) as $item) {
         $date = $item->get_date('U');
         $dateUpdated = $item->get_updated_date('U');
         $items[] = array('authors' => $this->_getItemAuthors($item->get_authors()), 'categories' => $this->_getItemCategories($item->get_categories()), 'content' => $item->get_content(true), 'contributors' => $this->_getItemAuthors($item->get_contributors()), 'date' => $date ? new DateTime('@' . $date) : null, 'dateUpdated' => $dateUpdated ? new DateTime('@' . $dateUpdated) : null, 'permalink' => $item->get_permalink(), 'summary' => $item->get_description(true), 'title' => $item->get_title(), 'enclosures' => $this->_getEnclosures($item->get_enclosures()));
     }
     return $items;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Dropping the movePermission column from the structures table...', LogLevel::Info, true);
     $this->dropColumn('structures', 'movePermission');
     Craft::log('Done dropping the movePermission column from the structures table.', LogLevel::Info, true);
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Renaming social_accounts `gateway` column by `providerHandle`', LogLevel::Info, true);
     MigrationHelper::renameColumn('social_accounts', 'gateway', 'providerHandle');
     Craft::log('Done renaming social_accounts `gateway` column by `providerHandle`', LogLevel::Info, true);
     return true;
 }
Esempio n. 23
0
 public function getSettingsHtml()
 {
     $pluginSettings = craft()->plugins->getPlugin('placid')->getSettings();
     // Get placid requests and send them to the widget settings
     $requests = craft()->placid_requests->findAllRequests();
     $requestsArray = array('' => 'No request selected');
     foreach ($requests as $request) {
         $requestsArray[$request->handle] = $request->name;
     }
     $templatesPath = craft()->path->getSiteTemplatesPath() . $pluginSettings->widgetTemplatesPath;
     $templates = IOHelper::getFolderContents($templatesPath, TRUE);
     $templatesArray = array('' => Craft::t('No template selected'));
     if (!$templates) {
         $templatesArray = array('' => 'Cannot find templates');
         Craft::log('Cannot find templates in path "' . $templatesPath . '"', LogLevel::Error);
     } else {
         // Turn array into ArrayObject
         $templates = new \ArrayObject($templates);
         // Iterate over template list
         // * Remove full path
         // * Remove folders from list
         for ($list = $templates->getIterator(); $list->valid(); $list->next()) {
             $filename = $list->current();
             $filename = str_replace($templatesPath, '', $filename);
             $filenameIncludingSubfolder = $filename;
             $isTemplate = preg_match("/(.html|.twig)\$/u", $filename);
             if ($isTemplate) {
                 $templatesArray[$filenameIncludingSubfolder] = $filename;
             }
         }
     }
     return craft()->templates->render('placid/_widgets/request/settings', array('requests' => $requestsArray, 'templates' => $templatesArray, 'settings' => $this->getSettings()));
 }
Esempio n. 24
0
 /**
  * Handles a thrown exception.  Will also log extra information if the exception happens to by a MySql deadlock.
  *
  * @param \Exception $exception The exception captured.
  *
  * @return null
  */
 protected function handleException($exception)
 {
     // Log MySQL deadlocks
     if ($exception instanceof \CDbException && strpos($exception->getMessage(), 'Deadlock') !== false) {
         $data = craft()->db->createCommand('SHOW ENGINE INNODB STATUS')->query();
         $info = $data->read();
         $info = serialize($info);
         Craft::log('Deadlock error, innodb status: ' . $info, LogLevel::Error, 'system.db.CDbCommand');
     }
     // If this is a Twig Runtime exception, use the previous one instead
     if ($exception instanceof \Twig_Error_Runtime) {
         if ($previousException = $exception->getPrevious()) {
             $exception = $previousException;
         }
     }
     // Special handling for Twig syntax errors
     if ($exception instanceof \Twig_Error) {
         $this->handleTwigError($exception);
     } else {
         if ($exception instanceof DbConnectException) {
             $this->handleDbConnectionError($exception);
         } else {
             parent::handleException($exception);
         }
     }
 }
Esempio n. 25
0
 public function getProfile()
 {
     try {
         $token = $this->token;
         if ($token) {
             // make token compatible with Google library
             $arrayToken = array();
             $arrayToken['created'] = 0;
             $arrayToken['access_token'] = $token->accessToken;
             $arrayToken['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);
             $service = new Google_Service_Oauth2($client);
             $response = $service->userinfo->get();
             return array('id' => $response->id, 'email' => $response->email, 'photo' => $response->picture, 'locale' => $response->locale, 'firstName' => $response->givenName, 'lastName' => $response->familyName, 'profileUrl' => $response->link, 'gender' => $response->gender);
         } else {
             Craft::log(__METHOD__ . ' : No token defined', LogLevel::Info, true);
             return false;
         }
     } catch (\Exception $e) {
         // todo: catch errors
         // throw $e;
     }
 }
 /**
  * @inheritDoc ITask::runStep()
  *
  * @param int $step
  *
  * @return bool
  */
 public function runStep($step)
 {
     // NOTE: Perhaps much of this should be moved into a service
     $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build();
     // Make the client
     $client = new \Guzzle\Http\Client();
     // Set the Accept header
     $client->setDefaultOption('headers/Accept', '*/*');
     // Loop the paths in this step
     foreach ($this->_paths[$step] as $path) {
         // Make the url, stripping 'site:' from the path if it exists
         $newPath = preg_replace('/site:/', '', $path, 1);
         $url = UrlHelper::getSiteUrl($newPath);
         // Create the GET request
         $request = $client->get($url);
         // Add it to the batch
         $batch->add($request);
     }
     // Flush the queue and retrieve the flushed items
     $requests = $batch->flush();
     // Log any exceptions
     foreach ($batch->getExceptions() as $e) {
         Craft::log('CacheMonster: an exception occurred: ' . $e->getMessage(), LogLevel::Error);
     }
     // Clear any exceptions
     $batch->clearExceptions();
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Increasing the max Asset file size in “assetfiles” table.', LogLevel::Info, true);
     $this->alterColumn('assetfiles', 'size', array('column' => ColumnType::BigInt, 'unsigned' => true));
     Craft::log('Increasing the max Asset file size in “assetindexdata” table.', LogLevel::Info, true);
     $this->alterColumn('assetindexdata', 'size', array('column' => ColumnType::BigInt, 'unsigned' => true));
     return true;
 }
 public function actionDeleteToken()
 {
     Craft::log(__METHOD__, LogLevel::Info, true);
     $id = craft()->request->getRequiredParam('id');
     craft()->oauth->tokenDeleteById($id);
     craft()->userSession->setNotice(Craft::t('Token deleted.'));
     $this->redirect($_SERVER['HTTP_REFERER']);
 }
 /**
  * Get Profile
  */
 public function getProfile()
 {
     try {
         return craft()->analytics->getProfile();
     } catch (\Exception $e) {
         Craft::log('Couldn’t get profile: ' . $e->getMessage(), LogLevel::Info, true);
     }
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Altering craft_users photo column to be varchar(100)...', LogLevel::Info, true);
     $this->alterColumn('users', 'photo', array(ColumnType::Varchar, 'maxLength' => 100));
     $this->alterColumn('users', 'weekStartDay', array(ColumnType::TinyInt, 'unsigned', 'required' => true, 'default' => '0'));
     Craft::log('Done altering craft_users photo column to be varchar(100)...', LogLevel::Info, true);
     return true;
 }