/**
  * Handles all of the routine tasks that go along with saving elements.
  *
  * Those tasks include:
  *
  * - Validating its content (if $validateContent is `true`, or it’s left as `null` and the element is enabled)
  * - Ensuring the element has a title if its type {@link BaseElementType::hasTitles() has titles}, and giving it a
  *   default title in the event that $validateContent is set to `false`
  * - Saving a row in the `elements` table
  * - Assigning the element’s ID on the element model, if it’s a new element
  * - Assigning the element’s ID on the element’s content model, if there is one and it’s a new set of content
  * - Updating the search index with new keywords from the element’s content
  * - Setting a unique URI on the element, if it’s supposed to have one.
  * - Saving the element’s row(s) in the `elements_i18n` and `content` tables
  * - Deleting any rows in the `elements_i18n` and `content` tables that no longer need to be there
  * - Calling the field types’ {@link BaseFieldType::onAfterElementSave() onAfterElementSave()} methods
  * - Cleaing any template caches that the element was involved in
  *
  * This method should be called by a service’s “saveX()” method, _after_ it is done validating any attributes on
  * the element that are of particular concern to its element type. For example, if the element were an entry,
  * saveElement() should be called only after the entry’s sectionId and typeId attributes had been validated to
  * ensure that they point to valid section and entry type IDs.
  *
  * @param BaseElementModel $element         The element that is being saved
  * @param bool|null        $validateContent Whether the element's content should be validated. If left 'null', it
  *                                          will depend on whether the element is enabled or not.
  *
  * @throws Exception|\Exception
  * @return bool
  */
 public function saveElement(BaseElementModel $element, $validateContent = null)
 {
     $elementType = $this->getElementType($element->getElementType());
     $isNewElement = !$element->id;
     // Validate the content first
     if ($elementType->hasContent()) {
         if ($validateContent === null) {
             $validateContent = (bool) $element->enabled;
         }
         if ($validateContent && !craft()->content->validateContent($element)) {
             $element->addErrors($element->getContent()->getErrors());
             return false;
         } else {
             // Make sure there's a title
             if ($elementType->hasTitles()) {
                 $fields = array('title');
                 $content = $element->getContent();
                 $content->setRequiredFields($fields);
                 if (!$content->validate($fields) && $content->hasErrors('title')) {
                     // Just set *something* on it
                     if ($isNewElement) {
                         $content->title = 'New ' . $element->getClassHandle();
                     } else {
                         $content->title = $element->getClassHandle() . ' ' . $element->id;
                     }
                 }
             }
         }
     }
     // Get the element record
     if (!$isNewElement) {
         $elementRecord = ElementRecord::model()->findByAttributes(array('id' => $element->id, 'type' => $element->getElementType()));
         if (!$elementRecord) {
             throw new Exception(Craft::t('No element exists with the ID “{id}”.', array('id' => $element->id)));
         }
     } else {
         $elementRecord = new ElementRecord();
         $elementRecord->type = $element->getElementType();
     }
     // Set the attributes
     $elementRecord->enabled = (bool) $element->enabled;
     $elementRecord->archived = (bool) $element->archived;
     $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
     try {
         // Fire an 'onBeforeSaveElement' event
         $event = new Event($this, array('element' => $element, 'isNewElement' => $isNewElement));
         $this->onBeforeSaveElement($event);
         // Is the event giving us the go-ahead?
         if ($event->performAction) {
             // Save the element record first
             $success = $elementRecord->save(false);
             if ($success) {
                 if ($isNewElement) {
                     // Save the element id on the element model, in case {id} is in the URL format
                     $element->id = $elementRecord->id;
                     if ($elementType->hasContent()) {
                         $element->getContent()->elementId = $element->id;
                     }
                 }
                 // Save the content
                 if ($elementType->hasContent()) {
                     craft()->content->saveContent($element, false, (bool) $element->id);
                 }
                 // Update the search index
                 craft()->search->indexElementAttributes($element);
                 // Update the locale records and content
                 // We're saving all of the element's locales here to ensure that they all exist and to update the URI in
                 // the event that the URL format includes some value that just changed
                 $localeRecords = array();
                 if (!$isNewElement) {
                     $existingLocaleRecords = ElementLocaleRecord::model()->findAllByAttributes(array('elementId' => $element->id));
                     foreach ($existingLocaleRecords as $record) {
                         $localeRecords[$record->locale] = $record;
                     }
                 }
                 $mainLocaleId = $element->locale;
                 $locales = $element->getLocales();
                 $localeIds = array();
                 if (!$locales) {
                     throw new Exception('All elements must have at least one locale associated with them.');
                 }
                 foreach ($locales as $localeId => $localeInfo) {
                     if (is_numeric($localeId) && is_string($localeInfo)) {
                         $localeId = $localeInfo;
                         $localeInfo = array();
                     }
                     $localeIds[] = $localeId;
                     if (!isset($localeInfo['enabledByDefault'])) {
                         $localeInfo['enabledByDefault'] = true;
                     }
                     if (isset($localeRecords[$localeId])) {
                         $localeRecord = $localeRecords[$localeId];
                     } else {
                         $localeRecord = new ElementLocaleRecord();
                         $localeRecord->elementId = $element->id;
                         $localeRecord->locale = $localeId;
                         $localeRecord->enabled = $localeInfo['enabledByDefault'];
                     }
                     // Is this the main locale?
                     $isMainLocale = $localeId == $mainLocaleId;
                     if ($isMainLocale) {
                         $localizedElement = $element;
                     } else {
                         // Copy the element for this locale
                         $localizedElement = $element->copy();
                         $localizedElement->locale = $localeId;
                         if ($localeRecord->id) {
                             // Keep the original slug
                             $localizedElement->slug = $localeRecord->slug;
                         } else {
                             // Default to the main locale's slug
                             $localizedElement->slug = $element->slug;
                         }
                     }
                     if ($elementType->hasContent()) {
                         if (!$isMainLocale) {
                             $content = null;
                             if (!$isNewElement) {
                                 // Do we already have a content row for this locale?
                                 $content = craft()->content->getContent($localizedElement);
                             }
                             if (!$content) {
                                 $content = craft()->content->createContent($localizedElement);
                                 $content->setAttributes($element->getContent()->getAttributes());
                                 $content->id = null;
                                 $content->locale = $localeId;
                             }
                             $localizedElement->setContent($content);
                         }
                         if (!$localizedElement->getContent()->id) {
                             craft()->content->saveContent($localizedElement, false, false);
                         }
                     }
                     // Capture the original slug, in case it's entirely composed of invalid characters
                     $originalSlug = $localizedElement->slug;
                     // Clean up the slug
                     ElementHelper::setValidSlug($localizedElement);
                     // If the slug was entirely composed of invalid characters, it will be blank now.
                     if ($originalSlug && !$localizedElement->slug) {
                         $localizedElement->slug = $originalSlug;
                         $element->addError('slug', Craft::t('{attribute} is invalid.', array('attribute' => Craft::t('Slug'))));
                         // Don't bother with any of the other locales
                         $success = false;
                         break;
                     }
                     ElementHelper::setUniqueUri($localizedElement);
                     $localeRecord->slug = $localizedElement->slug;
                     $localeRecord->uri = $localizedElement->uri;
                     if ($isMainLocale) {
                         $localeRecord->enabled = (bool) $element->localeEnabled;
                     }
                     $success = $localeRecord->save();
                     if (!$success) {
                         // Pass any validation errors on to the element
                         $element->addErrors($localeRecord->getErrors());
                         // Don't bother with any of the other locales
                         break;
                     }
                 }
                 if ($success) {
                     if (!$isNewElement) {
                         // Delete the rows that don't need to be there anymore
                         craft()->db->createCommand()->delete('elements_i18n', array('and', 'elementId = :elementId', array('not in', 'locale', $localeIds)), array(':elementId' => $element->id));
                         if ($elementType->hasContent()) {
                             craft()->db->createCommand()->delete($element->getContentTable(), array('and', 'elementId = :elementId', array('not in', 'locale', $localeIds)), array(':elementId' => $element->id));
                         }
                     }
                     // Call the field types' onAfterElementSave() methods
                     $fieldLayout = $element->getFieldLayout();
                     if ($fieldLayout) {
                         foreach ($fieldLayout->getFields() as $fieldLayoutField) {
                             $field = $fieldLayoutField->getField();
                             if ($field) {
                                 $fieldType = $field->getFieldType();
                                 if ($fieldType) {
                                     $fieldType->element = $element;
                                     $fieldType->onAfterElementSave();
                                 }
                             }
                         }
                     }
                     // Finally, delete any caches involving this element. (Even do this for new elements, since they
                     // might pop up in a cached criteria.)
                     craft()->templateCache->deleteCachesByElement($element);
                 }
             }
         } else {
             $success = false;
         }
         // Commit the transaction regardless of whether we saved the user, in case something changed
         // in onBeforeSaveElement
         if ($transaction !== null) {
             $transaction->commit();
         }
     } catch (\Exception $e) {
         if ($transaction !== null) {
             $transaction->rollback();
         }
         throw $e;
     }
     if ($success) {
         // Fire an 'onSaveElement' event
         $this->onSaveElement(new Event($this, array('element' => $element, 'isNewElement' => $isNewElement)));
     } else {
         if ($isNewElement) {
             $element->id = null;
             if ($elementType->hasContent()) {
                 $element->getContent()->id = null;
                 $element->getContent()->elementId = null;
             }
         }
     }
     return $success;
 }
 /**
  * Saves an entry.
  *
  * @param EntryModel $entry
  * @throws Exception
  * @return bool
  */
 public function saveEntry(EntryModel $entry)
 {
     $isNewEntry = !$entry->id;
     // Entry data
     if (!$isNewEntry) {
         $entryRecord = EntryRecord::model()->with('element')->findById($entry->id);
         if (!$entryRecord) {
             throw new Exception(Craft::t('No entry exists with the ID “{id}”', array('id' => $entry->id)));
         }
         $elementRecord = $entryRecord->element;
         // if entry->sectionId is null and there is an entryRecord sectionId, we assume this is a front-end edit.
         if ($entry->sectionId === null && $entryRecord->sectionId) {
             $entry->sectionId = $entryRecord->sectionId;
         }
     } else {
         $entryRecord = new EntryRecord();
         $elementRecord = new ElementRecord();
         $elementRecord->type = ElementType::Entry;
     }
     $section = craft()->sections->getSectionById($entry->sectionId);
     if (!$section) {
         throw new Exception(Craft::t('No section exists with the ID “{id}”', array('id' => $entry->sectionId)));
     }
     $sectionLocales = $section->getLocales();
     if (!isset($sectionLocales[$entry->locale])) {
         throw new Exception(Craft::t('The section “{section}” is not enabled for the locale {locale}', array('section' => $section->name, 'locale' => $entry->locale)));
     }
     $entryRecord->sectionId = $entry->sectionId;
     $entryRecord->authorId = $entry->authorId;
     $entryRecord->postDate = $entry->postDate;
     $entryRecord->expiryDate = $entry->expiryDate;
     if ($entry->enabled && !$entryRecord->postDate) {
         // Default the post date to the current date/time
         $entryRecord->postDate = $entry->postDate = DateTimeHelper::currentUTCDateTime();
     }
     $entryRecord->validate();
     $entry->addErrors($entryRecord->getErrors());
     $elementRecord->enabled = $entry->enabled;
     $elementRecord->validate();
     $entry->addErrors($elementRecord->getErrors());
     // Entry locale data
     if ($entry->id) {
         $entryLocaleRecord = EntryLocaleRecord::model()->findByAttributes(array('entryId' => $entry->id, 'locale' => $entry->locale));
         // If entry->slug is null and there is an entryLocaleRecord slug, we assume this is a front-end edit.
         if ($entry->slug === null && $entryLocaleRecord->slug) {
             $entry->slug = $entryLocaleRecord->slug;
         }
     }
     if (empty($entryLocaleRecord)) {
         $entryLocaleRecord = new EntryLocaleRecord();
         $entryLocaleRecord->sectionId = $entry->sectionId;
         $entryLocaleRecord->locale = $entry->locale;
     }
     if ($entryLocaleRecord->isNewRecord() || $entry->slug != $entryLocaleRecord->slug) {
         $this->_generateEntrySlug($entry);
         $entryLocaleRecord->slug = $entry->slug;
     }
     $entryLocaleRecord->validate();
     $entry->addErrors($entryLocaleRecord->getErrors());
     // Element locale data
     if ($entry->id) {
         $elementLocaleRecord = ElementLocaleRecord::model()->findByAttributes(array('elementId' => $entry->id, 'locale' => $entry->locale));
     }
     if (empty($elementLocaleRecord)) {
         $elementLocaleRecord = new ElementLocaleRecord();
         $elementLocaleRecord->locale = $entry->locale;
     }
     if ($section->hasUrls && $entry->enabled) {
         // Make sure the section's URL format is valid. This shouldn't be possible due to section validation,
         // but it's not enforced by the DB, so anything is possible.
         $urlFormat = $sectionLocales[$entry->locale]->urlFormat;
         if (!$urlFormat || strpos($urlFormat, '{slug}') === false) {
             throw new Exception(Craft::t('The section “{section}” doesn’t have a valid URL Format.', array('section' => Craft::t($section->name))));
         }
         $elementLocaleRecord->uri = craft()->templates->renderObjectTemplate($urlFormat, $entry);
     } else {
         $elementLocaleRecord->uri = null;
     }
     $elementLocaleRecord->validate();
     $entry->addErrors($elementLocaleRecord->getErrors());
     // Entry content
     $fieldLayout = $section->getFieldLayout();
     $content = craft()->content->prepElementContentForSave($entry, $fieldLayout);
     $content->validate();
     $entry->addErrors($content->getErrors());
     if (!$entry->hasErrors()) {
         // Save the element record first
         $elementRecord->save(false);
         // Now that we have an element ID, save it on the other stuff
         if (!$entry->id) {
             $entry->id = $elementRecord->id;
             $entryRecord->id = $entry->id;
         }
         $entryRecord->save(false);
         $entryLocaleRecord->entryId = $entry->id;
         $elementLocaleRecord->elementId = $entry->id;
         $content->elementId = $entry->id;
         // Save the other records
         $entryLocaleRecord->save(false);
         $elementLocaleRecord->save(false);
         craft()->content->saveContent($content, false);
         // Update the search index
         craft()->search->indexElementAttributes($entry, $entry->locale);
         // Save a new version
         if (Craft::hasPackage(CraftPackage::PublishPro)) {
             craft()->entryRevisions->saveVersion($entry);
         }
         // Perform some post-save operations
         craft()->content->postSaveOperations($entry, $content);
         // Fire an 'onSaveEntry' event
         $this->onSaveEntry(new Event($this, array('entry' => $entry, 'isNewEntry' => $isNewEntry)));
         return true;
     } else {
         return false;
     }
 }
 /**
  * Stores a file.
  *
  * @param AssetFileModel $file
  * @return bool
  */
 public function storeFile(AssetFileModel $file)
 {
     if ($file->id) {
         $fileRecord = AssetFileRecord::model()->findById($file->id);
         if (!$fileRecord) {
             throw new Exception(Craft::t("No asset exists with the ID “{id}”", array('id' => $file->id)));
         }
     } else {
         $elementRecord = new ElementRecord();
         $elementRecord->type = ElementType::Asset;
         $elementRecord->enabled = 1;
         $elementRecord->save();
         $fileRecord = new AssetFileRecord();
         $fileRecord->id = $elementRecord->id;
     }
     $fileRecord->sourceId = $file->sourceId;
     $fileRecord->folderId = $file->folderId;
     $fileRecord->filename = $file->filename;
     $fileRecord->kind = $file->kind;
     $fileRecord->size = $file->size;
     $fileRecord->width = $file->width;
     $fileRecord->height = $file->height;
     $fileRecord->dateModified = $file->dateModified;
     if ($fileRecord->save()) {
         if (!$file->id) {
             // Save the ID on the model now that we have it
             $file->id = $fileRecord->id;
             // Give it a default title based on the file name
             $file->getContent()->title = str_replace('_', ' ', IOHelper::getFileName($file->filename, false));
             $this->saveFileContent($file, false);
         }
         // Update the search index
         craft()->search->indexElementAttributes($file);
         return true;
     } else {
         $file->addErrors($fileRecord->getErrors());
         return false;
     }
 }
 /**
  * Creates a new ElementRecord, saves and returns it.
  *
  * @access private
  * @return ElementRecord
  */
 private function _createNewElementRecord()
 {
     $elementRecord = new ElementRecord();
     $elementRecord->type = 'Charge';
     $elementRecord->enabled = 1;
     $elementRecord->save();
     return $elementRecord;
 }
 /**
  * Saves a user, or registers a new one.
  *
  * @param UserModel $user
  * @throws Exception
  * @return bool
  */
 public function saveUser(UserModel $user)
 {
     if (($isNewUser = !$user->id) == false) {
         $userRecord = $this->_getUserRecordById($user->id);
         if (!$userRecord) {
             throw new Exception(Craft::t('No user exists with the ID “{id}”', array('id' => $user->id)));
         }
         $oldUsername = $userRecord->username;
     } else {
         $userRecord = new UserRecord();
     }
     // Set the user record attributes
     $userRecord->username = $user->username;
     $userRecord->firstName = $user->firstName;
     $userRecord->lastName = $user->lastName;
     $userRecord->email = $user->email;
     $userRecord->admin = $user->admin;
     $userRecord->passwordResetRequired = $user->passwordResetRequired;
     $userRecord->preferredLocale = $user->preferredLocale;
     $userRecord->validate();
     $user->addErrors($userRecord->getErrors());
     // If newPassword is set at all, even to an empty string, validate & set it.
     if ($user->newPassword !== null) {
         $this->_setPasswordOnUserRecord($user, $userRecord);
     }
     if (!$user->hasErrors()) {
         if ($user->verificationRequired) {
             $userRecord->status = $user->status = UserStatus::Pending;
             $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord);
         }
         // Fire an 'onBeforeSaveUser' event
         $this->onBeforeSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser)));
         if ($isNewUser) {
             // Create the entry record
             $elementRecord = new ElementRecord();
             $elementRecord->type = ElementType::User;
             $elementRecord->save();
             // Now that we have the entry ID, save it on everything else
             $user->id = $elementRecord->id;
             $userRecord->id = $elementRecord->id;
         }
         $userRecord->save(false);
         if (!$isNewUser) {
             // Has the username changed?
             if ($user->username != $oldUsername) {
                 // Rename the user's photo directory
                 $oldFolder = craft()->path->getUserPhotosPath() . $oldUsername;
                 $newFolder = craft()->path->getUserPhotosPath() . $user->username;
                 if (IOHelper::folderExists($newFolder)) {
                     IOHelper::deleteFolder($newFolder);
                 }
                 if (IOHelper::folderExists($oldFolder)) {
                     IOHelper::rename($oldFolder, $newFolder);
                 }
             }
         }
         // Update the search index
         craft()->search->indexElementAttributes($user);
         if ($isNewUser && $user->verificationRequired) {
             craft()->templates->registerTwigAutoloader();
             craft()->email->sendEmailByKey($user, 'account_activation', array('link' => new \Twig_Markup(craft()->config->getActivateAccountPath($unhashedVerificationCode, $userRecord->uid), craft()->templates->getTwig()->getCharset())));
         }
         // Fire an 'onSaveUser' event
         $this->onSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser)));
         return true;
     } else {
         return false;
     }
 }
 /**
  * Saves a tag.
  *
  * @param TagModel $tag
  * @throws Exception
  * @return bool
  */
 public function saveTag(TagModel $tag)
 {
     $isNewTag = !$tag->id;
     // Tag data
     if (!$isNewTag) {
         $tagRecord = TagRecord::model()->with('element')->findById($tag->id);
         if (!$tagRecord) {
             throw new Exception(Craft::t('No tag exists with the ID “{id}”', array('id' => $tag->id)));
         }
         $elementRecord = $tagRecord->element;
         // If tag->setId is null and there is an tagRecord setId, we assume this is a front-end edit.
         if ($tag->setId === null && $tagRecord->setId) {
             $tag->setId = $tagRecord->setId;
         }
     } else {
         $tagRecord = new TagRecord();
         $elementRecord = new ElementRecord();
         $elementRecord->type = ElementType::Tag;
     }
     $tagRecord->setId = $tag->setId;
     $tagRecord->name = $tag->name;
     $tagRecord->validate();
     $tag->addErrors($tagRecord->getErrors());
     $elementRecord->validate();
     $tag->addErrors($elementRecord->getErrors());
     if (!$tag->hasErrors()) {
         // Save the element record first
         $elementRecord->save(false);
         // Now that we have an element ID, save it on the other stuff
         if (!$tag->id) {
             $tag->id = $elementRecord->id;
             $tagRecord->id = $tag->id;
         }
         $tagRecord->save(false);
         // Update the search index
         craft()->search->indexElementAttributes($tag, $tag->locale);
         // Fire an 'onSaveTag' event
         $this->onSaveTag(new Event($this, array('tag' => $tag, 'isNewTag' => $isNewTag)));
         return true;
     } else {
         return false;
     }
 }
Beispiel #7
0
function freshports_Parse404URI($REQUEST_URI, $db)
{
    #
    # we have a pending 404
    # if we can parse it, then do so and return a false value;
    # otherwise, return a non-false value.
    global $User;
    $Debug = 0;
    $result = '';
    $IsPort = false;
    $IsCategory = false;
    $IsElement = false;
    if ($Debug) {
        echo "Debug is turned on.  Only 404 will be returned now because we cannot alter the headers at this time.<br>\n";
    }
    $CategoryID = 0;
    define('FRESHPORTS_PORTS_TREE_PREFIX', '/ports/head/');
    $URLParts = parse_url($_SERVER['SCRIPT_URI']);
    if ($Debug) {
        echo 'the URI is <pre>' . $_SERVER['SCRIPT_URI'] . "</pre><br>\n";
        echo 'the url parts are <pre>' . print_r($URLParts) . "</pre><br>\n";
    }
    $pathname = $URLParts['path'];
    if ($Debug) {
        echo "The pathname is '{$pathname}'<br>";
    }
    require_once $_SERVER['DOCUMENT_ROOT'] . '/../classes/element_record.php';
    $ElementRecord = new ElementRecord($db);
    # first goal, remove leading / and leading ports/
    if (substr($pathname, 0, 1) == '/') {
        $pathname = substr($pathname, 1);
    }
    if (preg_match('|^ports/|', $pathname)) {
        $pathname = substr($pathname, 6);
    }
    define('PATH_NAME', $pathname);
    if ($Debug) {
        echo "PATH_NAME='" . FRESHPORTS_PORTS_TREE_PREFIX . PATH_NAME . "'<br>";
    }
    if ($ElementRecord->FetchByName(FRESHPORTS_PORTS_TREE_PREFIX . $pathname)) {
        $IsElement = true;
        if ($Debug) {
            echo 'Yes, we found an element for that path!<br>';
            echo '<pre>';
            echo print_r($ElementRecord, true);
            echo '</pre>';
        }
        if ($ElementRecord->IsCategory()) {
            $IsCategory = true;
            if ($Debug) {
                echo 'This is a category<br>';
            }
            require_once $_SERVER['DOCUMENT_ROOT'] . '/../classes/categories.php';
            $Category = new Category($db);
            $CategoryID = $Category->FetchByElementID($ElementRecord->id);
        } else {
            if ($Debug) {
                echo 'That path does not point at a category!<br>';
            }
        }
        if ($ElementRecord->IsPort()) {
            $IsPort = true;
            # we don't use list($category, $port) so we don't have to worry
            # about extra bits
            $PathParts = explode('/', PATH_NAME);
            $category = $PathParts[0];
            $port = $PathParts[1];
            if ($Debug) {
                echo "This is a port!<br>";
            }
            if ($Debug) {
                echo "Category='{$category}'<br>";
            }
            if ($Debug) {
                echo "Port='{$port}'<br>";
            }
        } else {
            if ($Debug) {
                echo 'The call to ElementRecord indicates this is not a port<br>';
            }
        }
    } else {
        if ($Debug) {
            echo 'not an element<br>';
        }
        # let's see if this is a virtual category!
        $result = $REQUEST_URI;
        $PathParts = explode('/', PATH_NAME);
        if ($Debug) {
            echo '<pre>';
            print_r($PathParts);
            echo '</pre>';
        }
        # start with nothing.
        unset($category);
        unset($port);
        # if the URL looks like /afterstep/, then we'll get two elements
        # in the array.  The second will be empty.  Hence the != ''
        #
        # grab whatever we have
        #
        if (isset($PathParts[0]) && $PathParts[0] != '') {
            $category = $PathParts[0];
            if ($Debug) {
                echo "Category is '{$category}'<br>";
            }
        }
        if (isset($PathParts[1]) && $PathParts[1] != '') {
            $port = $PathParts[1];
            if ($Debug) {
                echo "Port is '{$port}'<br>";
            }
        }
        if (isset($port)) {
            $IsPort = true;
            $IsPort = false;
            $result = $REQUEST_URI;
            if ($Debug) {
                echo 'This is a Port but there is no element for it.<br>';
            }
        }
        if (isset($category) && !$IsPort) {
            # we have a valid category, but no valid port.
            # we will display the category only if they did *try* to speciy a port.
            # i.e. they suuplied an invalid port name
            if ($Debug) {
                echo 'This is a category<br>';
            }
            if (isset($port)) {
                if ($Debug) {
                    'Invalid port supplied for a valid category<br>';
                }
            } else {
                require_once $_SERVER['DOCUMENT_ROOT'] . '/../classes/categories.php';
                $Category = new Category($db);
                $CategoryID = $Category->FetchByName($category);
                if ($CategoryID) {
                    $IsCategory = true;
                }
            }
        }
    }
    if ($Debug) {
        echo 'let us see what we will include now....<br>';
    }
    if ($IsPort) {
        if ($Debug) {
            echo 'including missing-port ' . $Debug . '<BR>';
        }
        require_once $_SERVER['DOCUMENT_ROOT'] . '/missing-port.php';
        if ($Debug) {
            echo 'including missing-port ' . $Debug . '<BR>';
        }
        # if zero is returned, all is well, otherwise, we can't display that category/port.
        if (freshports_PortDisplay($db, $category, $port)) {
            echo 'freshports_PortDisplay returned non-zero';
            exit;
        }
    }
    if ($IsCategory && !$IsPort) {
        if ($Debug) {
            echo 'This is a category<br>';
        }
        require_once $_SERVER['DOCUMENT_ROOT'] . '/missing-category.php';
        freshports_CategoryByID($db, $CategoryID, 1, $User->page_size);
        exit;
    }
    if ($IsElement && !$IsPort) {
        if ($Debug) {
            echo 'This is an element<br>';
        }
        require_once $_SERVER['DOCUMENT_ROOT'] . '/missing-non-port.php';
        freshports_NonPortDescription($db, $ElementRecord);
        exit;
    }
    return $result;
}
Beispiel #8
0
 $files = isset($query_parts['files']) ? $query_parts['files'] : 'n';
 $ShowAllFilesURL = '<a href="' . htmlspecialchars($_SERVER['SCRIPT_URL'] . '?message_id=' . $message_id . '&files=yes') . '">show all files</a>';
 $HideAllFilesURL = '<a href="' . htmlspecialchars($_SERVER['SCRIPT_URL'] . '?message_id=' . $message_id) . '">hide all files</a>';
 if ($FilesForJustOnePort) {
     // TODO need to validate category/port here!
     $clean['category'] = $query_parts['category'];
     $clean['port'] = $query_parts['port'];
     require_once $_SERVER['DOCUMENT_ROOT'] . '/../classes/categories.php';
     $Category = new Category($database);
     $CategoryID = $Category->FetchByName($clean['category']);
     if (!$CategoryID) {
         die('I don\'t know that category: . ' . htmlentities($clean['category']));
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . '/../classes/element_record.php';
     $elementName = '/ports/head/' . $clean['category'] . '/' . $clean['port'];
     $Element = new ElementRecord($database);
     $ElementID = $Element->FetchByName($elementName);
     if (!$ElementID) {
         die('I don\'t know that port.');
     }
     if (!$Element->IsPort()) {
         die('That is not a port.');
     }
     $PortURL = '<a href="/' . $clean['category'] . '/' . $clean['port'] . '/">' . $clean['category'] . '/' . $clean['port'] . '</a>';
     echo '<p>Showing files for just one port: <big><b>' . $PortURL . '</b></big></p>';
     echo "<p>{$ShowAllFilesURL}</p>";
 }
 # if we ask for files=yes or files=y
 if (!strcasecmp($files, 'yes') || !strcasecmp($files, 'y')) {
     echo "<p>{$HideAllFilesURL}</p>";
     $WhichRepo = freshports_MessageIdToRepoName($message_id);
 /**
  * Saves a global set.
  *
  * @param GlobalSetModel $globalSet
  * @throws \Exception
  * @return bool
  */
 public function saveSet(GlobalSetModel $globalSet)
 {
     $isNewSet = empty($globalSet->id);
     if (!$isNewSet) {
         $globalSetRecord = GlobalSetRecord::model()->with('element')->findById($globalSet->id);
         if (!$globalSetRecord) {
             throw new Exception(Craft::t('No global set exists with the ID “{id}”', array('id' => $globalSet->id)));
         }
         $oldSet = GlobalSetModel::populateModel($globalSetRecord);
         $elementRecord = $globalSetRecord->element;
     } else {
         $globalSetRecord = new GlobalSetRecord();
         $elementRecord = new ElementRecord();
         $elementRecord->type = ElementType::GlobalSet;
     }
     $globalSetRecord->name = $globalSet->name;
     $globalSetRecord->handle = $globalSet->handle;
     $globalSetRecord->validate();
     $globalSet->addErrors($globalSetRecord->getErrors());
     $elementRecord->enabled = $globalSet->enabled;
     $elementRecord->validate();
     $globalSet->addErrors($elementRecord->getErrors());
     if (!$globalSet->hasErrors()) {
         $transaction = craft()->db->beginTransaction();
         try {
             if (!$isNewSet && $oldSet->fieldLayoutId) {
                 // Drop the old field layout
                 craft()->fields->deleteLayoutById($oldSet->fieldLayoutId);
             }
             // Save the new one
             $fieldLayout = $globalSet->getFieldLayout();
             craft()->fields->saveLayout($fieldLayout, false);
             // Update the set record/model with the new layout ID
             $globalSet->fieldLayoutId = $fieldLayout->id;
             $globalSetRecord->fieldLayoutId = $fieldLayout->id;
             // Save the element record first
             $elementRecord->save(false);
             // Now that we have an element ID, save it on the other stuff
             if (!$globalSet->id) {
                 $globalSet->id = $elementRecord->id;
                 $globalSetRecord->id = $globalSet->id;
             }
             $globalSetRecord->save(false);
             $transaction->commit();
         } catch (\Exception $e) {
             $transaction->rollBack();
             throw $e;
         }
         return true;
     } else {
         return false;
     }
 }