/**
  * @param SproutSeo_SitemapModel $attributes
  *
  * @return mixed|null|string
  */
 public function saveSitemap(SproutSeo_SitemapModel $attributes)
 {
     $row = array();
     $isNew = false;
     if (isset($attributes->id) && substr($attributes->id, 0, 3) === "new") {
         $isNew = true;
     }
     if (!$isNew) {
         $row = craft()->db->createCommand()->select('*')->from('sproutseo_sitemap')->where('id=:id', array(':id' => $attributes->id))->queryRow();
     }
     $model = SproutSeo_SitemapModel::populateModel($row);
     $model->id = !$isNew ? $attributes->id : null;
     $model->sectionId = isset($attributes->sectionId) ? $attributes->sectionId : null;
     $model->url = isset($attributes->url) ? $attributes->url : null;
     $model->priority = $attributes->priority;
     $model->changeFrequency = $attributes->changeFrequency;
     $model->enabled = $attributes->enabled == 'true' ? 1 : 0;
     $model->ping = $attributes->ping == 'true' ? 1 : 0;
     $model->dateUpdated = DateTimeHelper::currentTimeForDb();
     $model->uid = StringHelper::UUID();
     if ($isNew) {
         $model->dateCreated = DateTimeHelper::currentTimeForDb();
         craft()->db->createCommand()->insert('sproutseo_sitemap', $model->getAttributes());
         return craft()->db->lastInsertID;
     } else {
         $result = craft()->db->createCommand()->update('sproutseo_sitemap', $model->getAttributes(), 'id=:id', array(':id' => $model->id));
         return $model->id;
     }
 }
 /**
  * Logs a new deprecation error.
  *
  * @param string $key
  * @param string $message
  *
  * @return bool
  */
 public function log($key, $message)
 {
     $log = new DeprecationErrorModel();
     $log->key = $key;
     $log->message = $message;
     $log->lastOccurrence = DateTimeHelper::currentTimeForDb();
     $log->template = craft()->request->isSiteRequest() ? craft()->templates->getRenderingTemplate() : null;
     // Everything else requires the stack trace
     $this->_populateLogWithStackTraceData($log);
     // Don't log the same key/fingerprint twice in the same request
     if (!isset($this->_fingerprints[$log->key]) || !in_array($log->fingerprint, $this->_fingerprints[$log->key])) {
         craft()->db->createCommand()->insertOrUpdate(static::$_tableName, array('key' => $log->key, 'fingerprint' => $log->fingerprint), array('lastOccurrence' => DateTimeHelper::formatTimeForDb($log->lastOccurrence), 'file' => $log->file, 'line' => $log->line, 'class' => $log->class, 'method' => $log->method, 'template' => $log->template, 'templateLine' => $log->templateLine, 'message' => $log->message, 'traces' => JsonHelper::encode($log->traces)));
         $this->_fingerprints[$key][] = $log->fingerprint;
     }
     return true;
 }
Beispiel #3
0
 /**
  * @inheritDoc BaseModel::defineAttributes()
  *
  * @return array
  */
 protected function defineAttributes()
 {
     // The client license key.
     $attributes['licenseKey'] = AttributeType::String;
     // The license key status.  Set by the server response.
     $attributes['licenseKeyStatus'] = AttributeType::String;
     // The edition that Craft is licensed to use
     $attributes['licensedEdition'] = array(AttributeType::Enum, 'values' => array(Craft::Personal, Craft::Client, Craft::Pro));
     // The domain that the license is associated with
     $attributes['licensedDomain'] = AttributeType::String;
     // Whether Craft is running for a domain that's eligible to be used in Edition Test Mode
     $attributes['editionTestableDomain'] = AttributeType::Bool;
     // The installed plugin license keys.
     $attributes['pluginLicenseKeys'] = AttributeType::Mixed;
     // The plugins' license key statuses.  Set by the server response.
     $attributes['pluginLicenseKeyStatuses'] = AttributeType::Mixed;
     // Extra arbitrary data to send to the server.
     $attributes['data'] = AttributeType::Mixed;
     // The url making the request.
     $attributes['requestUrl'] = array(AttributeType::String, 'default' => '');
     // The IP address making the request.
     $attributes['requestIp'] = array(AttributeType::String, 'default' => '1.1.1.1');
     // The time the request was made.
     $attributes['requestTime'] = array(AttributeType::DateTime, 'default' => DateTimeHelper::currentTimeForDb());
     // The port number the request comes from.
     $attributes['requestPort'] = AttributeType::String;
     // The local version number.
     $attributes['localVersion'] = array(AttributeType::String, 'required' => true);
     // The local build number.
     $attributes['localBuild'] = array(AttributeType::Number, 'required' => true);
     // The local edition.
     $attributes['localEdition'] = array(AttributeType::String, 'required' => true);
     // The currently logged in user's email address.
     $attributes['userEmail'] = AttributeType::Email;
     // The track this install is on.  Not required for backwards compatibility.
     $attributes['track'] = array(AttributeType::String);
     // Whether or not to show beta releases.
     $attributes['showBeta'] = AttributeType::Bool;
     // Any errors to return;
     $attributes['errors'] = AttributeType::Mixed;
     // Any additional server info to include.
     $attributes['serverInfo'] = AttributeType::Mixed;
     // The context of the request. Either 'craft' or a plugin handle.
     $attributes['handle'] = array(AttributeType::String, 'default' => 'craft', 'required' => true);
     return $attributes;
 }
Beispiel #4
0
 /**
  * @access protected
  * @return array
  */
 protected function defineAttributes()
 {
     // The client license key.
     $attributes['licenseKey'] = AttributeType::String;
     // The license key status.  Set by the server response.
     $attributes['licenseKeyStatus'] = AttributeType::String;
     // The domain that the license is associated with
     $attributes['licensedDomain'] = AttributeType::String;
     // Extra arbitrary data to send to the server.
     $attributes['data'] = AttributeType::Mixed;
     // The url making the request.
     $attributes['requestUrl'] = array(AttributeType::String, 'default' => '');
     // The IP address making the request.
     $attributes['requestIp'] = array(AttributeType::String, 'default' => '1.1.1.1');
     // The time the request was made.
     $attributes['requestTime'] = array(AttributeType::DateTime, 'default' => DateTimeHelper::currentTimeForDb());
     // The port number the request comes from.
     $attributes['requestPort'] = AttributeType::String;
     // Any packages installed on the client.
     $attributes['installedPackages'] = array(AttributeType::Mixed, 'default' => array());
     // All the packages that are actually licensed.
     $attributes['licensedPackages'] = array(AttributeType::Mixed, 'default' => array());
     // Any packages that are in trial mode.
     $attributes['packageTrials'] = array(AttributeType::Mixed, 'default' => array());
     // The local version number.
     $attributes['localVersion'] = array(AttributeType::String, 'required' => true);
     // The local build number.
     $attributes['localBuild'] = array(AttributeType::Number, 'required' => true);
     // The currently logged in user's email address.
     $attributes['userEmail'] = AttributeType::String;
     // The track this install is on.  Not required for backwards compatibility.
     $attributes['track'] = array(AttributeType::String);
     // Any errors to return;
     $attributes['errors'] = AttributeType::Mixed;
     return $attributes;
 }
 /**
  * Deletes any expired caches.
  *
  * @return bool
  */
 public function deleteExpiredCaches()
 {
     if ($this->_deletedAllCaches || $this->_deletedExpiredCaches) {
         return false;
     }
     $affectedRows = craft()->db->createCommand()->delete(static::$_templateCachesTable, 'expiryDate <= :now', array('now' => DateTimeHelper::currentTimeForDb()));
     $this->_deletedExpiredCaches = true;
     return (bool) $affectedRows;
 }
 /**
  * @inheritDoc IElementType::getElementQueryStatusCondition()
  *
  * @param DbCommand $query
  * @param string    $status
  *
  * @return array|false|string|void
  */
 public function getElementQueryStatusCondition(DbCommand $query, $status)
 {
     $currentTimeDb = DateTimeHelper::currentTimeForDb();
     switch ($status) {
         case EntryModel::LIVE:
             return array('and', 'elements.enabled = 1', 'elements_i18n.enabled = 1', "entries.postDate <= '{$currentTimeDb}'", array('or', 'entries.expiryDate is null', "entries.expiryDate > '{$currentTimeDb}'"));
         case EntryModel::PENDING:
             return array('and', 'elements.enabled = 1', 'elements_i18n.enabled = 1', "entries.postDate > '{$currentTimeDb}'");
         case EntryModel::EXPIRED:
             return array('and', 'elements.enabled = 1', 'elements_i18n.enabled = 1', 'entries.expiryDate is not null', "entries.expiryDate <= '{$currentTimeDb}'");
     }
 }
 /**
  * @param string $table
  * @param array  $columns
  * @param mixed  $conditions
  * @param array  $params
  * @param bool   $includeAuditColumns
  *
  * @return int
  */
 public function update($table, $columns, $conditions = '', $params = array(), $includeAuditColumns = true)
 {
     $table = $this->getConnection()->addTablePrefix($table);
     $conditions = $this->_normalizeConditions($conditions, $params);
     if ($includeAuditColumns) {
         $columns['dateUpdated'] = DateTimeHelper::currentTimeForDb();
     }
     return parent::update($table, $columns, $conditions, $params);
 }
 /**
  * Defines this model's attributes.
  *
  * @return array
  */
 protected function defineAttributes()
 {
     return array_merge(parent::defineAttributes(), array('redirectSrcUrl' => array(AttributeType::String, 'default' => ''), 'referrerUrl' => array(AttributeType::String, 'default' => ''), 'hitCount' => array(AttributeType::Number, 'default' => 0), 'hitLastTime' => array(AttributeType::DateTime, 'default' => DateTimeHelper::currentTimeForDb()), 'handledByRetour' => array(AttributeType::Bool, 'default' => false)));
 }
 /**
  * Deletes any expired tokens.
  *
  * @return bool
  */
 public function deleteExpiredTokens()
 {
     // Ignore if we've already done this once during the request
     if ($this->_deletedExpiredTokens) {
         return false;
     }
     $affectedRows = craft()->db->createCommand()->delete('tokens', 'expiryDate <= :now', array('now' => DateTimeHelper::currentTimeForDb()));
     $this->_deletedExpiredTokens = true;
     return (bool) $affectedRows;
 }
 /**
  * Installs a plugin.
  *
  * @param $handle
  * @throws Exception
  * @throws \Exception
  * @return bool
  */
 public function installPlugin($handle)
 {
     $plugin = $this->getPlugin($handle, false);
     $lcPluginHandle = strtolower($plugin->getClassHandle());
     if (!$plugin) {
         $this->_noPluginExists($handle);
     }
     if ($plugin->isInstalled) {
         throw new Exception(Craft::t('“{plugin}” is already installed.', array('plugin' => $plugin->getName())));
     }
     $transaction = craft()->db->beginTransaction();
     try {
         // Add the plugins as a record to the database.
         craft()->db->createCommand()->insert('plugins', array('class' => $plugin->getClassHandle(), 'version' => $plugin->version, 'enabled' => true, 'installDate' => DateTimeHelper::currentTimeForDb()));
         $plugin->isInstalled = true;
         $plugin->isEnabled = true;
         $this->_enabledPlugins[$lcPluginHandle] = $plugin;
         $this->_importPluginComponents($plugin);
         $plugin->createTables();
         $transaction->commit();
     } catch (\Exception $e) {
         $transaction->rollBack();
         throw $e;
     }
     $plugin->onAfterInstall();
     return true;
 }
Beispiel #11
0
 /**
  * @param  $url The 404 url
  */
 public function incrementStatistics($url, $handled = false)
 {
     $handled = (int) $handled;
     $url = substr($url, 0, 255);
     $referrer = craft()->request->getUrlReferrer();
     if (is_null($referrer)) {
         $referrer = "";
     }
     /* -- See if a stats record exists already */
     $result = craft()->db->createCommand()->select('*')->from('retour_stats')->where('redirectSrcUrl =' . craft()->db->quoteValue($url))->queryAll();
     if (empty($result)) {
         $stats = new Retour_StatsRecord();
         $stats->redirectSrcUrl = $url;
         $stats->referrerUrl = $referrer;
         $stats->hitCount = 1;
         $stats->hitLastTime = DateTimeHelper::currentUTCDateTime();
         $stats->handledByRetour = $handled;
         $stats->save();
     } else {
         /* -- Update the stats table */
         foreach ($result as $stat) {
             $stat['hitCount'] = $stat['hitCount'] + 1;
             $stat['hitLastTime'] = DateTimeHelper::currentTimeForDb();
             $stat['referrerUrl'] = $referrer;
             $result = craft()->db->createCommand()->update('retour_stats', array('hitCount' => $stat['hitCount'], 'hitLastTime' => $stat['hitLastTime'], 'handledByRetour' => $handled, 'referrerUrl' => $stat['referrerUrl']), 'id=:id', array(':id' => $stat['id']));
         }
     }
 }
Beispiel #12
0
 /**
  * Prepares the model's attribute values to be saved to the database.
  *
  * @return null
  */
 public function prepAttributesForSave()
 {
     $attributes = $this->getAttributeConfigs();
     $attributes['dateUpdated'] = array('type' => AttributeType::DateTime, 'column' => ColumnType::DateTime, 'required' => true);
     $attributes['dateCreated'] = array('type' => AttributeType::DateTime, 'column' => ColumnType::DateTime, 'required' => true);
     foreach ($attributes as $name => $config) {
         $value = $this->getAttribute($name);
         if ($config['type'] == AttributeType::DateTime) {
             // Leaving this in because we want to allow plugin devs to save a timestamp or DateTime object.
             if (DateTimeHelper::isValidTimeStamp($value)) {
                 $value = new DateTime('@' . $value);
             }
         }
         $this->setAttribute($name, ModelHelper::packageAttributeValue($value, true));
     }
     // Populate dateCreated and uid if this is a new record
     if ($this->isNewRecord()) {
         $this->dateCreated = DateTimeHelper::currentTimeForDb();
         $this->uid = StringHelper::UUID();
     }
     // Update the dateUpdated
     $this->dateUpdated = DateTimeHelper::currentTimeForDb();
 }
 /**
  * @param      $class
  * @param null $plugin
  *
  * @return bool|null
  */
 public function migrateUp($class, $plugin = null)
 {
     if ($class === $this->getBaseMigration()) {
         return null;
     }
     if ($plugin) {
         Craft::log('Applying migration: ' . $class . ' for plugin: ' . $plugin->getClassHandle(), LogLevel::Info, true);
     } else {
         Craft::log('Applying migration: ' . $class, LogLevel::Info, true);
     }
     $start = microtime(true);
     $migration = $this->instantiateMigration($class, $plugin);
     if ($migration->up() !== false) {
         if ($plugin) {
             $pluginInfo = craft()->plugins->getPluginInfo($plugin);
             craft()->db->createCommand()->insert($this->_migrationTable, array('version' => $class, 'applyTime' => DateTimeHelper::currentTimeForDb(), 'pluginId' => $pluginInfo['id']));
         } else {
             craft()->db->createCommand()->insert($this->_migrationTable, array('version' => $class, 'applyTime' => DateTimeHelper::currentTimeForDb()));
         }
         $time = microtime(true) - $start;
         Craft::log('Applied migration: ' . $class . ' (time: ' . sprintf("%.3f", $time) . 's)', LogLevel::Info, true);
         return true;
     } else {
         $time = microtime(true) - $start;
         Craft::log('Failed to apply migration: ' . $class . ' (time: ' . sprintf("%.3f", $time) . 's)', LogLevel::Error);
         return false;
     }
 }
 /**
  * @inheritDoc IElementType::getElementQueryStatusCondition()
  *
  * @param DbCommand $query
  * @param string    $status
  *
  * @return array|false|string|void
  */
 public function getElementQueryStatusCondition(DbCommand $query, $status)
 {
     $currentTimeDb = DateTimeHelper::currentTimeForDb();
     switch ($status) {
         case PushNotifications_NotificationModel::SENT:
             return array("or", "pushnotifications_notifications.schedule IS NULL", "pushnotifications_notifications.schedule <= '{$currentTimeDb}'");
             break;
         case PushNotifications_NotificationModel::PENDING:
             return "pushnotifications_notifications.schedule > '{$currentTimeDb}'";
             break;
     }
 }
 /**
  * @inheritDoc IElementType::getElementQueryStatusCondition()
  *
  * @param DbCommand $query
  * @param string    $status
  *
  * @return array|false|string|void
  */
 public function getElementQueryStatusCondition(DbCommand $query, $status)
 {
     $currentTimeDb = DateTimeHelper::currentTimeForDb();
     switch ($status) {
         case Market_ProductModel::LIVE:
             return ['and', 'elements.enabled = 1', 'elements_i18n.enabled = 1', "products.availableOn <= '{$currentTimeDb}'", ['or', 'products.expiresOn is null', "products.expiresOn > '{$currentTimeDb}'"]];
         case Market_ProductModel::PENDING:
             return ['and', 'elements.enabled = 1', 'elements_i18n.enabled = 1', "products.availableOn > '{$currentTimeDb}'"];
         case Market_ProductModel::EXPIRED:
             return ['and', 'elements.enabled = 1', 'elements_i18n.enabled = 1', 'products.expiresOn is not null', "products.expiresOn <= '{$currentTimeDb}'"];
     }
 }
 /**
  * Saves a section.
  *
  * @param SectionModel $section
  *
  * @throws \Exception
  * @return bool
  */
 public function saveSection(SectionModel $section)
 {
     if ($section->id) {
         $sectionRecord = SectionRecord::model()->with('structure')->findById($section->id);
         if (!$sectionRecord) {
             throw new Exception(Craft::t('No section exists with the ID “{id}”.', array('id' => $section->id)));
         }
         $oldSection = SectionModel::populateModel($sectionRecord);
         $isNewSection = false;
     } else {
         $sectionRecord = new SectionRecord();
         $isNewSection = true;
     }
     // Shared attributes
     $sectionRecord->name = $section->name;
     $sectionRecord->handle = $section->handle;
     $sectionRecord->type = $section->type;
     $sectionRecord->enableVersioning = $section->enableVersioning;
     // Type-specific attributes
     if ($section->type == SectionType::Single) {
         $sectionRecord->hasUrls = $section->hasUrls = true;
     } else {
         $sectionRecord->hasUrls = $section->hasUrls;
     }
     if ($section->hasUrls) {
         $sectionRecord->template = $section->template;
     } else {
         $sectionRecord->template = $section->template = null;
     }
     $sectionRecord->validate();
     $section->addErrors($sectionRecord->getErrors());
     // Make sure that all of the URL formats are set properly
     $sectionLocales = $section->getLocales();
     if (!$sectionLocales) {
         $section->addError('localeErrors', Craft::t('At least one locale must be selected for the section.'));
     }
     $firstSectionLocale = null;
     foreach ($sectionLocales as $localeId => $sectionLocale) {
         // Is this the first one?
         if ($firstSectionLocale === null) {
             $firstSectionLocale = $sectionLocale;
         }
         if ($section->type == SectionType::Single) {
             $errorKey = 'urlFormat-' . $localeId;
             if (empty($sectionLocale->urlFormat)) {
                 $section->addError($errorKey, Craft::t('URI cannot be blank.'));
             } else {
                 if ($section) {
                     // Make sure no other elements are using this URI already
                     $query = craft()->db->createCommand()->from('elements_i18n elements_i18n')->where(array('and', 'elements_i18n.locale = :locale', 'elements_i18n.uri = :uri'), array(':locale' => $localeId, ':uri' => $sectionLocale->urlFormat));
                     if ($section->id) {
                         $query->join('entries entries', 'entries.id = elements_i18n.elementId')->andWhere('entries.sectionId != :sectionId', array(':sectionId' => $section->id));
                     }
                     $count = $query->count('elements_i18n.id');
                     if ($count) {
                         $section->addError($errorKey, Craft::t('This URI is already in use.'));
                     }
                 }
             }
             $sectionLocale->nestedUrlFormat = null;
         } else {
             if ($section->hasUrls) {
                 $urlFormatAttributes = array('urlFormat');
                 $sectionLocale->urlFormatIsRequired = true;
                 if ($section->type == SectionType::Structure && $section->maxLevels != 1) {
                     $urlFormatAttributes[] = 'nestedUrlFormat';
                     $sectionLocale->nestedUrlFormatIsRequired = true;
                 } else {
                     $sectionLocale->nestedUrlFormat = null;
                 }
                 foreach ($urlFormatAttributes as $attribute) {
                     if (!$sectionLocale->validate(array($attribute))) {
                         $section->addError($attribute . '-' . $localeId, $sectionLocale->getError($attribute));
                     }
                 }
             } else {
                 $sectionLocale->urlFormat = null;
                 $sectionLocale->nestedUrlFormat = null;
             }
         }
     }
     if (!$section->hasErrors()) {
         $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
         try {
             // Fire an 'onBeforeSaveSection' event
             $event = new Event($this, array('section' => $section, 'isNewSection' => $isNewSection));
             $this->onBeforeSaveSection($event);
             // Is the event giving us the go-ahead?
             if ($event->performAction) {
                 // Do we need to create a structure?
                 if ($section->type == SectionType::Structure) {
                     if (!$isNewSection && $oldSection->type == SectionType::Structure) {
                         $structure = craft()->structures->getStructureById($oldSection->structureId);
                         $isNewStructure = false;
                     }
                     if (empty($structure)) {
                         $structure = new StructureModel();
                         $isNewStructure = true;
                     }
                     $structure->maxLevels = $section->maxLevels;
                     craft()->structures->saveStructure($structure);
                     $sectionRecord->structureId = $structure->id;
                     $section->structureId = $structure->id;
                 } else {
                     if (!$isNewSection && $oldSection->structureId) {
                         // Delete the old one
                         craft()->structures->deleteStructureById($oldSection->structureId);
                         $sectionRecord->structureId = null;
                     }
                 }
                 $sectionRecord->save(false);
                 // Now that we have a section ID, save it on the model
                 if ($isNewSection) {
                     $section->id = $sectionRecord->id;
                 }
                 // Might as well update our cache of the section while we have it. (It's possible that the URL format
                 //includes {section.handle} or something...)
                 $this->_sectionsById[$section->id] = $section;
                 // Update the sections_i18n table
                 $newLocaleData = array();
                 if (!$isNewSection) {
                     // Get the old section locales
                     $oldSectionLocaleRecords = SectionLocaleRecord::model()->findAllByAttributes(array('sectionId' => $section->id));
                     $oldSectionLocales = SectionLocaleModel::populateModels($oldSectionLocaleRecords, 'locale');
                 }
                 foreach ($sectionLocales as $localeId => $locale) {
                     // Was this already selected?
                     if (!$isNewSection && isset($oldSectionLocales[$localeId])) {
                         $oldLocale = $oldSectionLocales[$localeId];
                         // Has anything changed?
                         if ($locale->enabledByDefault != $oldLocale->enabledByDefault || $locale->urlFormat != $oldLocale->urlFormat || $locale->nestedUrlFormat != $oldLocale->nestedUrlFormat) {
                             craft()->db->createCommand()->update('sections_i18n', array('enabledByDefault' => (int) $locale->enabledByDefault, 'urlFormat' => $locale->urlFormat, 'nestedUrlFormat' => $locale->nestedUrlFormat), array('id' => $oldLocale->id));
                         }
                     } else {
                         $newLocaleData[] = array($section->id, $localeId, (int) $locale->enabledByDefault, $locale->urlFormat, $locale->nestedUrlFormat);
                     }
                 }
                 // Insert the new locales
                 craft()->db->createCommand()->insertAll('sections_i18n', array('sectionId', 'locale', 'enabledByDefault', 'urlFormat', 'nestedUrlFormat'), $newLocaleData);
                 if (!$isNewSection) {
                     // Drop any locales that are no longer being used, as well as the associated entry/element locale
                     // rows
                     $droppedLocaleIds = array_diff(array_keys($oldSectionLocales), array_keys($sectionLocales));
                     if ($droppedLocaleIds) {
                         craft()->db->createCommand()->delete('sections_i18n', array('and', 'sectionId = :sectionId', array('in', 'locale', $droppedLocaleIds)), array(':sectionId' => $section->id));
                     }
                 }
                 // Make sure there's at least one entry type for this section
                 $entryTypeId = null;
                 if (!$isNewSection) {
                     // Let's grab all of the entry type IDs to save ourselves a query down the road if this is a Single
                     $entryTypeIds = craft()->db->createCommand()->select('id')->from('entrytypes')->where('sectionId = :sectionId', array(':sectionId' => $section->id))->queryColumn();
                     if ($entryTypeIds) {
                         $entryTypeId = array_shift($entryTypeIds);
                     }
                 }
                 if (!$entryTypeId) {
                     $entryType = new EntryTypeModel();
                     $entryType->sectionId = $section->id;
                     $entryType->name = $section->name;
                     $entryType->handle = $section->handle;
                     if ($section->type == SectionType::Single) {
                         $entryType->hasTitleField = false;
                         $entryType->titleLabel = null;
                         $entryType->titleFormat = '{section.name|raw}';
                     } else {
                         $entryType->hasTitleField = true;
                         $entryType->titleLabel = Craft::t('Title');
                         $entryType->titleFormat = null;
                     }
                     $this->saveEntryType($entryType);
                     $entryTypeId = $entryType->id;
                 }
                 // Now, regardless of whether the section type changed or not, let the section type make sure
                 // everything is cool
                 switch ($section->type) {
                     case SectionType::Single:
                         // Make sure that there is one and only one Entry Type and Entry for this section.
                         $singleEntryId = null;
                         if (!$isNewSection) {
                             // Make sure there's only one entry in this section
                             $entryIds = craft()->db->createCommand()->select('id')->from('entries')->where('sectionId = :sectionId', array(':sectionId' => $section->id))->queryColumn();
                             if ($entryIds) {
                                 $singleEntryId = array_shift($entryIds);
                                 // If there are any more, get rid of them
                                 if ($entryIds) {
                                     craft()->elements->deleteElementById($entryIds);
                                 }
                                 // Make sure it's enabled and all that.
                                 craft()->db->createCommand()->update('elements', array('enabled' => 1, 'archived' => 0), array('id' => $singleEntryId));
                                 craft()->db->createCommand()->update('entries', array('typeId' => $entryTypeId, 'authorId' => null, 'postDate' => DateTimeHelper::currentTimeForDb(), 'expiryDate' => null), array('id' => $singleEntryId));
                             }
                             // Make sure there's only one entry type for this section
                             if ($entryTypeIds) {
                                 $this->deleteEntryTypeById($entryTypeIds);
                             }
                         }
                         if (!$singleEntryId) {
                             // Create it, baby
                             $singleEntry = new EntryModel();
                             $singleEntry->locale = $firstSectionLocale->locale;
                             $singleEntry->sectionId = $section->id;
                             $singleEntry->typeId = $entryTypeId;
                             $singleEntry->getContent()->title = $section->name;
                             craft()->entries->saveEntry($singleEntry);
                         }
                         break;
                     case SectionType::Structure:
                         if (!$isNewSection && $isNewStructure) {
                             // Add all of the entries to the structure
                             $criteria = craft()->elements->getCriteria(ElementType::Entry);
                             $criteria->locale = ArrayHelper::getFirstKey($oldSectionLocales);
                             $criteria->sectionId = $section->id;
                             $criteria->status = null;
                             $criteria->localeEnabled = null;
                             $criteria->order = 'elements.id';
                             $criteria->limit = 25;
                             do {
                                 $batchEntries = $criteria->find();
                                 foreach ($batchEntries as $entry) {
                                     craft()->structures->appendToRoot($section->structureId, $entry, 'insert');
                                 }
                                 $criteria->offset += 25;
                             } while ($batchEntries);
                         }
                         break;
                 }
                 // Finally, deal with the existing entries...
                 if (!$isNewSection) {
                     $criteria = craft()->elements->getCriteria(ElementType::Entry);
                     // Get the most-primary locale that this section was already enabled in
                     $locales = array_values(array_intersect(craft()->i18n->getSiteLocaleIds(), array_keys($oldSectionLocales)));
                     if ($locales) {
                         $criteria->locale = $locales[0];
                         $criteria->sectionId = $section->id;
                         $criteria->status = null;
                         $criteria->localeEnabled = null;
                         $criteria->limit = null;
                         craft()->tasks->createTask('ResaveElements', Craft::t('Resaving {section} entries', array('section' => $section->name)), array('elementType' => ElementType::Entry, 'criteria' => $criteria->getAttributes()));
                     }
                 }
                 $success = true;
             } else {
                 $success = false;
             }
             // Commit the transaction regardless of whether we saved the section, in case something changed
             // in onBeforeSaveSection
             if ($transaction !== null) {
                 $transaction->commit();
             }
         } catch (\Exception $e) {
             if ($transaction !== null) {
                 $transaction->rollback();
             }
             throw $e;
         }
     } else {
         $success = false;
     }
     if ($success) {
         // Fire an 'onSaveSection' event
         $this->onSaveSection(new Event($this, array('section' => $section, 'isNewSection' => $isNewSection)));
     }
     return $success;
 }
Beispiel #17
0
 /**
  * Installs a plugin by its handle.
  *
  * @param string $handle The plugin’s handle.
  *
  * @throws Exception|\Exception
  * @return bool Whether the plugin was installed successfully.
  */
 public function installPlugin($handle)
 {
     $plugin = $this->getPlugin($handle, false);
     $lcPluginHandle = mb_strtolower($plugin->getClassHandle());
     if (!$plugin) {
         $this->_noPluginExists($handle);
     }
     if ($plugin->isInstalled) {
         throw new Exception(Craft::t('“{plugin}” is already installed.', array('plugin' => $plugin->getName())));
     }
     $plugin->onBeforeInstall();
     $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
     try {
         // Add the plugins as a record to the database.
         craft()->db->createCommand()->insert('plugins', array('class' => $plugin->getClassHandle(), 'version' => $plugin->version, 'enabled' => true, 'installDate' => DateTimeHelper::currentTimeForDb()));
         $plugin->isInstalled = true;
         $plugin->isEnabled = true;
         $this->_enabledPlugins[$lcPluginHandle] = $plugin;
         $this->_savePluginMigrations(craft()->db->getLastInsertID(), $plugin->getClassHandle());
         $this->_autoloadPluginClasses($plugin);
         $plugin->createTables();
         if ($transaction !== null) {
             $transaction->commit();
         }
     } catch (\Exception $e) {
         if ($transaction !== null) {
             $transaction->rollback();
         }
         throw $e;
     }
     $plugin->onAfterInstall();
     return true;
 }
 /**
  * Defines this model's attributes.
  *
  * @return array
  */
 protected function defineAttributes()
 {
     return array_merge(parent::defineAttributes(), array('redirectSrcUrl' => array(AttributeType::String, 'default' => ''), 'redirectSrcUrlParsed' => array(AttributeType::String, 'default' => ''), 'redirectMatchType' => array(AttributeType::String, 'default' => 'match'), 'redirectDestUrl' => array(AttributeType::String, 'default' => ''), 'redirectHttpCode' => array(AttributeType::Number, 'default' => 301), 'hitCount' => array(AttributeType::Number, 'default' => 0), 'hitLastTime' => array(AttributeType::DateTime, 'default' => DateTimeHelper::currentTimeForDb()), 'locale' => array(AttributeType::String, 'default' => ''), 'associatedElementId' => array(AttributeType::Number, 'default' => 0)));
 }