Example #1
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // validate fields
         $this->frm->getField('title')->isFilled(BL::err('TitleIsRequired'));
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item['title'] = $this->frm->getField('title')->getValue();
             $item['language'] = BL::getWorkingLanguage();
             $item['publish_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             $item['hidden'] = $this->frm->getField('hidden')->getValue();
             // get the highest sequence available
             $item['sequence'] = BackendGalleryModel::getMaximumCategorySequence() + 1;
             // insert the item
             $item['id'] = BackendGalleryModel::insertCategory($item);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add_category', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('categories') . '&report=added-category&var=' . urlencode($item['title']) . '&highlight=row-' . $item['id']);
         }
     }
 }
Example #2
0
 /**
  * Create the XML based on the locale items.
  */
 public function getContent()
 {
     $charset = BackendModel::getContainer()->getParameter('kernel.charset');
     // create XML
     $xmlOutput = BackendLocaleModel::createXMLForExport($this->locale);
     return new Response($xmlOutput, Response::HTTP_OK, ['Content-Disposition' => 'attachment; filename="locale_' . BackendModel::getUTCDate('d-m-Y') . '.xml"', 'Content-Type' => 'application/octet-stream;charset=' . $charset, 'Content-Length' => '' . mb_strlen($xmlOutput)]);
 }
Example #3
0
 /**
  * Builds the query for this datagrid
  *
  * @return array An array with two arguments containing the query and its parameters.
  */
 private function buildQuery()
 {
     $parameters = array($this->id);
     // start query, as you can see this query is build in the wrong place,
     // because of the filter it is a special case
     // wherein we allow the query to be in the actionfile itself
     $query = 'SELECT i.id, UNIX_TIMESTAMP(i.sent_on) AS sent_on
          FROM forms_data AS i
          WHERE i.form_id = ?';
     // add start date
     if ($this->filter['start_date'] !== '') {
         // explode date parts
         $chunks = explode('/', $this->filter['start_date']);
         // add condition
         $query .= ' AND i.sent_on >= ?';
         $parameters[] = BackendModel::getUTCDate(null, gmmktime(23, 59, 59, $chunks[1], $chunks[0], $chunks[2]));
     }
     // add end date
     if ($this->filter['end_date'] !== '') {
         // explode date parts
         $chunks = explode('/', $this->filter['end_date']);
         // add condition
         $query .= ' AND i.sent_on <= ?';
         $parameters[] = BackendModel::getUTCDate(null, gmmktime(23, 59, 59, $chunks[1], $chunks[0], $chunks[2]));
     }
     // new query
     return array($query, $parameters);
 }
Example #4
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     if ($this->frm->isSubmitted()) {
         $this->frm->cleanupFields();
         $fields = $this->frm->getFields();
         // validate fields
         $fields['title']->isFilled(BL::err('TitleIsRequired'));
         if ($this->frm->isCorrect()) {
             // build item
             $item['id'] = BackendContentBlocksModel::getMaximumId() + 1;
             $item['user_id'] = BackendAuthentication::getUser()->getUserId();
             $item['template'] = count($this->templates) > 1 ? $fields['template']->getValue() : $this->templates[0];
             $item['language'] = BL::getWorkingLanguage();
             $item['title'] = $fields['title']->getValue();
             $item['text'] = $fields['text']->getValue();
             $item['hidden'] = $fields['hidden']->getValue() ? 'N' : 'Y';
             $item['status'] = 'active';
             $item['created_on'] = BackendModel::getUTCDate();
             $item['edited_on'] = BackendModel::getUTCDate();
             // insert the item
             $item['revision_id'] = BackendContentBlocksModel::insert($item);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('Index') . '&report=added&var=' . urlencode($item['title']) . '&highlight=row-' . $item['id']);
         }
     }
 }
Example #5
0
 /**
  * Execute the action
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // action to execute
     $id = \SpoonFilter::getGetValue('id', null, 0);
     // no id's provided
     if (empty($id) || !BackendMailmotorModel::existsMailing($id)) {
         $this->redirect(BackendModel::createURLForAction('Index') . '&error=mailing-does-not-exist');
     } else {
         // get the mailing and reset some fields
         $mailing = BackendMailmotorModel::getMailing($id);
         $mailing['status'] = 'concept';
         $mailing['send_on'] = null;
         $mailing['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
         $mailing['edited_on'] = $mailing['created_on'];
         unset($mailing['recipients'], $mailing['id'], $mailing['cm_id'], $mailing['send_on_raw']);
         // set groups
         $groups = $mailing['groups'];
         unset($mailing['groups']);
         // create a new mailing based on the old one
         $newId = BackendMailmotorModel::insertMailing($mailing);
         // update groups for this mailing
         BackendMailmotorModel::updateGroupsForMailing($newId, $groups);
         // trigger event
         BackendModel::triggerEvent($this->getModule(), 'after_copy_mailing', array('item' => $mailing));
     }
     // redirect
     $this->redirect(BackendModel::createURLForAction('Index') . '&report=mailing-copied&var=' . $mailing['name']);
 }
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // Get api key
     $this->apiKey = BackendModel::getModuleSetting($this->getModule(), 'api_key', null);
     // Get uncompressed images list
     $this->images = BackendCompressionModel::getImagesFromFolders();
     if (!empty($this->images)) {
         // Compress each image from each folder
         $output = 'Compressing ' . count($this->images) . ' images...' . "<br />\r\n";
         BackendCompressionModel::writeToCacheFile($output, true);
         foreach ($this->images as $image) {
             $tinyPNGApi = new TinyPNGApi($this->apiKey);
             // Shrink the image and check if succesful
             if ($tinyPNGApi->shrink($image['full_path'])) {
                 // Check if the file was successfully downloaded.
                 if ($tinyPNGApi->download($image['full_path'])) {
                     $output = 'Compression succesful for image ' . $image['filename'] . '. Saved ' . number_format($tinyPNGApi->getSavingSize() / 1024, 2) . ' KB' . ' bytes. (' . $tinyPNGApi->getSavingPercentage() . '%)';
                     BackendCompressionModel::writeToCacheFile($output);
                     // Save to db
                     $imageInfo = array('filename' => $image['filename'], 'path' => $image['full_path'], 'original_size' => $tinyPNGApi->getInputSize(), 'compressed_size' => $tinyPNGApi->getOutputSize(), 'saved_bytes' => $tinyPNGApi->getSavingSize(), 'saved_percentage' => $tinyPNGApi->getSavingPercentage(), 'checksum_hash' => sha1_file($image['full_path']), 'compressed_on' => BackendModel::getUTCDate());
                     BackendCompressionModel::insertImageHistory($imageInfo, $image['file_compressed_before']);
                 }
             } else {
                 BackendCompressionModel::writeToCacheFile($tinyPNGApi->getErrorMessage());
             }
         }
         BackendCompressionModel::writeToCacheFile("...Done!");
     } else {
         BackendCompressionModel::writeToCacheFile('There are no images that can be compressed.', true);
     }
     // Print the output for debug purposes
     $output = BackendCompressionModel::readCacheFile();
     print $output;
 }
Example #7
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // get parameters
     $id = \SpoonFilter::getPostValue('id', null, '', 'int');
     $name = trim(\SpoonFilter::getPostValue('value', null, '', 'string'));
     // validate
     if ($name == '') {
         $this->output(self::BAD_REQUEST, null, 'no name provided');
     } else {
         // get existing id
         $existingId = BackendMailmotorModel::getCampaignId($name);
         // validate
         if ($existingId !== 0 && $id !== $existingId) {
             $this->output(self::ERROR, array('id' => $existingId, 'error' => true), BL::err('CampaignExists', $this->getModule()));
         } else {
             // build array
             $item = array();
             $item['id'] = $id;
             $item['name'] = $name;
             $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             // get page
             $rows = BackendMailmotorModel::updateCampaign($item);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'edited_campaign', array('item' => $item));
             // output
             if ($rows !== 0) {
                 $this->output(self::OK, array('id' => $id), BL::msg('CampaignEdited', $this->getModule()));
             } else {
                 $this->output(self::ERROR, null, BL::err('CampaignNotEdited', $this->getModule()));
             }
         }
     }
 }
Example #8
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // shorten fields
         $txtName = $this->frm->getField('name');
         $rbtDefaultForLanguage = $this->frm->getField('default');
         // validate fields
         if ($txtName->isFilled(BL::err('NameIsRequired'))) {
             // check if the group exists by name
             if (BackendMailmotorModel::existsGroupByName($txtName->getValue())) {
                 $txtName->addError(BL::err('GroupAlreadyExists'));
             }
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item['name'] = $txtName->getValue();
             $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             $item['language'] = $rbtDefaultForLanguage->getValue() === '0' ? null : $rbtDefaultForLanguage->getValue();
             $item['is_default'] = $rbtDefaultForLanguage->getChecked() ? 'Y' : 'N';
             // insert the item
             $item['id'] = BackendMailmotorCMHelper::insertGroup($item);
             // check if all default groups were set
             BackendMailmotorModel::checkDefaultGroups();
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add_group', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('Groups') . '&report=added&var=' . urlencode($item['name']) . '&highlight=id-' . $item['id']);
         }
     }
 }
 /**
  * Export the templates as XML.
  */
 protected function parse()
 {
     $xml = Model::createTemplateXmlForExport($this->selectedTheme);
     $filename = 'templates_' . BackendModel::getUTCDate('d-m-Y') . '.xml';
     header('Content-type: text/xml');
     header('Content-disposition: attachment; filename="' . $filename . '"');
     echo $xml;
     exit;
 }
Example #10
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     $isGod = BackendAuthentication::getUser()->isGod();
     // get possible languages
     if ($isGod) {
         $possibleLanguages = array_unique(array_merge(BL::getWorkingLanguages(), BL::getInterfaceLanguages()));
     } else {
         $possibleLanguages = BL::getWorkingLanguages();
     }
     // get parameters
     $language = \SpoonFilter::getPostValue('language', array_keys($possibleLanguages), null, 'string');
     $module = \SpoonFilter::getPostValue('module', BackendModel::getModules(), null, 'string');
     $name = \SpoonFilter::getPostValue('name', null, null, 'string');
     $type = \SpoonFilter::getPostValue('type', BackendModel::getContainer()->get('database')->getEnumValues('locale', 'type'), null, 'string');
     $application = \SpoonFilter::getPostValue('application', array('Backend', 'Frontend'), null, 'string');
     $value = \SpoonFilter::getPostValue('value', null, null, 'string');
     // validate values
     if (trim($value) == '' || $language == '' || $module == '' || $type == '' || $application == '' || $application == 'Frontend' && $module != 'Core') {
         $error = BL::err('InvalidValue');
     }
     // in case this is a 'act' type, there are special rules concerning possible values
     if ($type == 'act' && !isset($error)) {
         if (urlencode($value) != CommonUri::getUrl($value)) {
             $error = BL::err('InvalidActionValue', $this->getModule());
         }
     }
     // no error?
     if (!isset($error)) {
         // build item
         $item['language'] = $language;
         $item['module'] = $module;
         $item['name'] = $name;
         $item['type'] = $type;
         $item['application'] = $application;
         $item['value'] = $value;
         $item['edited_on'] = BackendModel::getUTCDate();
         $item['user_id'] = BackendAuthentication::getUser()->getUserId();
         // does the translation exist?
         if (BackendLocaleModel::existsByName($name, $type, $module, $language, $application)) {
             // add the id to the item
             $item['id'] = (int) BackendLocaleModel::getByName($name, $type, $module, $language, $application);
             // update in db
             BackendLocaleModel::update($item);
         } else {
             // insert in db
             BackendLocaleModel::insert($item);
         }
         // output OK
         $this->output(self::OK);
     } else {
         $this->output(self::ERROR, null, $error);
     }
 }
Example #11
0
 /**
  * Copy content blocks
  *
  * @param string $from The language code to copy the content blocks from.
  * @param string $to The language code we want to copy the content blocks to.
  *
  * @return array
  *
  * @deprecated use the CopyContentBlocksToOtherLocale command
  */
 public static function copy($from, $to)
 {
     trigger_error('Backend\\Modules\\ContentBlocks\\Engine::copy is deprecated.
          Switch the CopyContentBlocksToOtherLocale command instead.', E_USER_DEPRECATED);
     // get db
     $db = BackendModel::getContainer()->get('database');
     // init variables
     $contentBlockIds = $oldIds = $newIds = array();
     // copy the contentblocks
     $contentBlocks = (array) $db->getRecords('SELECT * FROM content_blocks WHERE language = ? AND status = "active"', array($from));
     // define counter
     $i = 1;
     // loop existing content blocks
     foreach ($contentBlocks as $contentBlock) {
         // define old id
         $oldId = $contentBlock['extra_id'];
         // init new block
         $newBlock = array();
         // build new block
         $newBlock['id'] = self::getMaximumId() + $i;
         $newBlock['language'] = $to;
         $newBlock['created_on'] = BackendModel::getUTCDate();
         $newBlock['edited_on'] = BackendModel::getUTCDate();
         $newBlock['status'] = $contentBlock['status'];
         $newBlock['user_id'] = BackendAuthentication::getUser()->getUserId();
         $newBlock['template'] = $contentBlock['template'];
         $newBlock['title'] = $contentBlock['title'];
         $newBlock['text'] = $contentBlock['text'];
         $newBlock['hidden'] = $contentBlock['hidden'];
         // inset content block
         $newId = self::insert($newBlock);
         // save ids for later
         $oldIds[] = $oldId;
         $newIds[$oldId] = $newId;
         // redefine counter
         ++$i;
     }
     // get the extra Ids for the content blocks
     if (!empty($newIds)) {
         // get content block extra ids
         $contentBlockExtraIds = (array) $db->getRecords('SELECT revision_id, extra_id FROM content_blocks WHERE revision_id IN (' . implode(',', $newIds) . ')');
         // loop new ids
         foreach ($newIds as $oldId => $newId) {
             foreach ($contentBlockExtraIds as $extraId) {
                 if ($extraId['revision_id'] == $newId) {
                     $contentBlockIds[$oldId] = $extraId['extra_id'];
                 }
             }
         }
     }
     // return contentBlockIds
     return $contentBlockIds;
 }
Example #12
0
 /**
  * Create the XML based on the locale items.
  */
 private function createXML()
 {
     $charset = BackendModel::getContainer()->getParameter('kernel.charset');
     // create XML
     $xmlOutput = BackendLocaleModel::createXMLForExport($this->locale);
     // xml headers
     header('Content-Disposition: attachment; filename="locale_' . BackendModel::getUTCDate('d-m-Y') . '.xml"');
     header('Content-Type: application/octet-stream;charset=' . $charset);
     header('Content-Length: ' . strlen($xmlOutput));
     // output XML
     echo $xmlOutput;
     exit;
 }
 /**
  * Validate the form add image
  *
  * @return void
  */
 private function validateForm()
 {
     //--Check if the add-image form is submitted
     if ($this->frm->isSubmitted()) {
         //--Clean up fields in the form
         $this->frm->cleanupFields();
         //--Get image field
         $filImage = $this->frm->getField('images');
         //--Check if the field is filled in
         if ($filImage->isFilled()) {
             //--Image extension and mime type
             $filImage->isAllowedExtension(array('jpg', 'png', 'gif', 'jpeg'), BL::err('JPGGIFAndPNGOnly'));
             $filImage->isAllowedMimeType(array('image/jpg', 'image/png', 'image/gif', 'image/jpeg'), BL::err('JPGGIFAndPNGOnly'));
             //--Check if there are no errors.
             $strError = $filImage->getErrors();
             if ($strError === null) {
                 //--Get the filename
                 $strFilename = BackendGalleriaModel::checkFilename(substr($filImage->getFilename(), 0, 0 - (strlen($filImage->getExtension()) + 1)), $filImage->getExtension());
                 //--Fill in the item
                 $item = array();
                 $item["album_id"] = (int) $this->id;
                 $item["user_id"] = BackendAuthentication::getUser()->getUserId();
                 $item["language"] = BL::getWorkingLanguage();
                 $item["filename"] = $strFilename;
                 $item["description"] = "";
                 $item["publish_on"] = BackendModel::getUTCDate();
                 $item["hidden"] = "N";
                 $item["sequence"] = BackendGalleriaModel::getMaximumImageSequence($this->id) + 1;
                 //--the image path
                 $imagePath = FRONTEND_FILES_PATH . '/Galleria/Images';
                 //--create folders if needed
                 if (!\SpoonDirectory::exists($imagePath . '/Source')) {
                     \SpoonDirectory::create($imagePath . '/Source');
                 }
                 if (!\SpoonDirectory::exists($imagePath . '/128x128')) {
                     \SpoonDirectory::create($imagePath . '/128x128');
                 }
                 if (!\SpoonDirectory::exists($imagePath . '/800x')) {
                     \SpoonDirectory::create($imagePath . '/800x');
                 }
                 //--image provided?
                 if ($filImage->isFilled()) {
                     //--upload the image & generate thumbnails
                     $filImage->generateThumbnails($imagePath, $item["filename"]);
                 }
                 //--Add item to the database
                 BackendGalleriaModel::insert($item);
             }
         }
     }
 }
Example #14
0
 /**
  * Execute the action.
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // action to execute
     $action = \SpoonFilter::getGetValue('action', array('addToGroup', 'delete'), '');
     $ids = isset($_GET['id']) ? (array) $_GET['id'] : array();
     $newGroupId = \SpoonFilter::getGetValue('newGroup', array_keys(BackendProfilesModel::getGroups()), '');
     // no ids provided
     if (empty($ids)) {
         $this->redirect(BackendModel::createURLForAction('Index') . '&error=no-profiles-selected');
     }
     // delete the given profiles
     if ($action === 'delete') {
         BackendProfilesModel::delete($ids);
         $report = 'deleted';
     } elseif ($action === 'addToGroup') {
         // add the profiles to the given group
         // no group id provided
         if ($newGroupId == '') {
             $this->redirect(BackendModel::createURLForAction('Index') . '&error=no-group-selected');
         }
         // set new status
         foreach ($ids as $id) {
             // profile must exist
             if (BackendProfilesModel::exists($id)) {
                 // make sure the user is not already part of this group without an expiration date
                 foreach (BackendProfilesModel::getProfileGroups($id) as $existingGroup) {
                     // if he is, skip to the next user
                     if ($existingGroup['group_id'] === $newGroupId) {
                         continue 2;
                     }
                 }
                 // OK, it's safe to add the user to this group
                 BackendProfilesModel::insertProfileGroup(array('profile_id' => $id, 'group_id' => $newGroupId, 'starts_on' => BackendModel::getUTCDate()));
             }
         }
         // report
         $report = 'added-to-group';
     } else {
         // unknown action
         $this->redirect(BackendModel::createURLForAction('Index') . '&error=unknown-action');
     }
     // report
     $report = (count($ids) > 1 ? 'profiles-' : 'profile-') . $report;
     // redirect
     $this->redirect(BackendModel::createURLForAction('Index', null, null, array('offset' => \SpoonFilter::getGetValue('offset', null, ''), 'order' => \SpoonFilter::getGetValue('order', null, ''), 'sort' => \SpoonFilter::getGetValue('sort', null, ''), 'email' => \SpoonFilter::getGetValue('email', null, ''), 'status' => \SpoonFilter::getGetValue('status', null, ''), 'group' => \SpoonFilter::getGetValue('group', null, ''))) . '&report=' . $report);
 }
Example #15
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // get parameters
     $mailingId = \SpoonFilter::getPostValue('mailing_id', null, '', 'int');
     $sendOnDate = \SpoonFilter::getPostValue('send_on_date', null, BackendModel::getUTCDate('d/m/Y'));
     $sendOnTime = \SpoonFilter::getPostValue('send_on_time', null, BackendModel::getUTCDate('H:i'));
     $messageDate = $sendOnDate;
     // validate mailing ID
     if ($mailingId == '') {
         $this->output(self::BAD_REQUEST, null, 'Provide a valid mailing ID');
     } else {
         // validate date & time
         if ($sendOnDate == '' || $sendOnTime == '') {
             $this->output(self::BAD_REQUEST, null, 'Provide a valid send date date provided');
         } else {
             // record is empty
             if (!BackendMailmotorModel::existsMailing($mailingId)) {
                 $this->output(self::BAD_REQUEST, null, BL::err('MailingDoesNotExist', $this->getModule()));
             } else {
                 // reverse the date and make it a proper
                 $explodedDate = explode('/', $sendOnDate);
                 $sendOnDate = $explodedDate[2] . '-' . $explodedDate[1] . '-' . $explodedDate[0];
                 // calc full send timestamp
                 $sendTimestamp = strtotime($sendOnDate . ' ' . $sendOnTime);
                 // build data
                 $item['id'] = $mailingId;
                 $item['send_on'] = BackendModel::getUTCDate('Y-m-d H:i:s', $sendTimestamp);
                 $item['edited_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
                 // update mailing
                 BackendMailmotorModel::updateMailing($item);
                 // trigger event
                 BackendModel::triggerEvent($this->getModule(), 'after_edit_mailing_step4', array('item' => $item));
                 // output
                 $this->output(self::OK, array('mailing_id' => $mailingId, 'timestamp' => $sendTimestamp), sprintf(BL::msg('SendOn', $this->getModule()), $messageDate, $sendOnTime));
             }
         }
     }
 }
Example #16
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // shorten fields
         $txtName = $this->frm->getField('name');
         // validate fields
         $txtName->isFilled(BL::err('NameIsRequired'));
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item['name'] = $txtName->getValue();
             $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             // insert the item
             $item['id'] = BackendMailmotorModel::insertCampaign($item);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add_campaign', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('Campaigns') . '&report=added&var=' . urlencode($item['name']) . '&highlight=id-' . $item['id']);
         }
     }
 }
Example #17
0
 private function uploadFile()
 {
     //--Check if the file is an image or file
     if ($this->isImage()) {
         // the image path
         $path = FRONTEND_FILES_PATH . '/Media/Images';
         if (!\SpoonDirectory::exists($path . '/Source')) {
             \SpoonDirectory::create($path . '/Source');
         }
     } else {
         // the file path
         $path = FRONTEND_FILES_PATH . '/Media/Files';
     }
     // create folders if needed
     // build the filename
     $filename = $this->checkFilename();
     $item = array();
     $item["filename"] = $filename;
     $item["extension"] = $this->field->getExtension();
     $item["created_on"] = BackendModel::getUTCDate('Y-m-d H:i:s');
     $item["filesize"] = $this->field->getFileSize("b");
     $data = array();
     //--Check if file is an image to specify data
     if ($this->isImage()) {
         $item["filetype"] = $this->fieldTypeImage;
         //--Put file on disk
         $this->field->moveFile($path . "/Source/" . $filename);
         // create folders if needed
         if (!\SpoonDirectory::exists($path . '/128x128')) {
             \SpoonDirectory::create($path . '/128x128');
         }
         //--Create all tumbs/resizes of file
         $thumbnail = new \SpoonThumbnail($path . "/Source/" . $filename);
         $thumbnail->setAllowEnlargement(true);
         \Common\Core\Model::generateThumbnails($path, $path . '/Source/' . $filename);
     } else {
         $item["filetype"] = $this->fieldTypeFile;
         // move the source file
         $this->field->moveFile($path . "/" . $filename);
     }
     //--Serialize data
     $item["data"] = serialize($data);
     //--Store item so we can access it
     $this->item = $item;
     //--Insert into media
     return BackendModel::getContainer()->get('database')->insert("media", $item);
 }
Example #18
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     if ($this->frm->isSubmitted()) {
         $this->frm->cleanupFields();
         // redefine fields
         $txtName = $this->frm->getField('name');
         $txtValue = $this->frm->getField('value');
         // name checks
         if ($txtName->isFilled(BL::err('FieldIsRequired'))) {
             // allowed regex (a-z and 0-9)
             if ($txtName->isValidAgainstRegexp('|^([a-z0-9])+$|i', BL::err('InvalidName'))) {
                 // first letter does not seem to be a capital one
                 if (!in_array(substr($txtName->getValue(), 0, 1), range('A', 'Z'))) {
                     $txtName->setError(BL::err('InvalidName'));
                 } else {
                     // this name already exists in this language
                     if (BackendLocaleModel::existsByName($txtName->getValue(), $this->frm->getField('type')->getValue(), $this->frm->getField('module')->getValue(), $this->frm->getField('language')->getValue(), $this->frm->getField('application')->getValue())) {
                         $txtName->setError(BL::err('AlreadyExists'));
                     }
                 }
             }
         }
         // value checks
         if ($txtValue->isFilled(BL::err('FieldIsRequired'))) {
             // in case this is a 'act' type, there are special rules concerning possible values
             if ($this->frm->getField('type')->getValue() == 'act') {
                 if (urlencode($txtValue->getValue()) != CommonUri::getUrl($txtValue->getValue())) {
                     $txtValue->addError(BL::err('InvalidValue'));
                 }
             }
         }
         // module should be 'core' for any other application than backend
         if ($this->frm->getField('application')->getValue() != 'Backend' && $this->frm->getField('module')->getValue() != 'Core') {
             $this->frm->getField('module')->setError(BL::err('ModuleHasToBeCore'));
         }
         if ($this->frm->isCorrect()) {
             // build item
             $item['user_id'] = BackendAuthentication::getUser()->getUserId();
             $item['language'] = $this->frm->getField('language')->getValue();
             $item['application'] = $this->frm->getField('application')->getValue();
             $item['module'] = $this->frm->getField('module')->getValue();
             $item['type'] = $this->frm->getField('type')->getValue();
             $item['name'] = $this->frm->getField('name')->getValue();
             $item['value'] = $this->frm->getField('value')->getValue();
             $item['edited_on'] = BackendModel::getUTCDate();
             // update item
             $item['id'] = BackendLocaleModel::insert($item);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('Index', null, null, null) . '&report=added&var=' . urlencode($item['name']) . '&highlight=row-' . $item['id'] . $this->filterQuery);
         }
     }
 }
Example #19
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     if ($this->frm->isSubmitted()) {
         $this->frm->cleanupFields();
         // shorten the fields
         $txtName = $this->frm->getField('name');
         $txtEmail = $this->frm->getField('email');
         $ddmMethod = $this->frm->getField('method');
         $txtSuccessMessage = $this->frm->getField('success_message');
         $txtIdentifier = $this->frm->getField('identifier');
         $emailAddresses = (array) explode(',', $txtEmail->getValue());
         // validate fields
         $txtName->isFilled(BL::getError('NameIsRequired'));
         $txtSuccessMessage->isFilled(BL::getError('SuccessMessageIsRequired'));
         if ($ddmMethod->isFilled(BL::getError('NameIsRequired')) && $ddmMethod->getValue() == 'database_email') {
             $error = false;
             // check the addresses
             foreach ($emailAddresses as $address) {
                 $address = trim($address);
                 if (!\SpoonFilter::isEmail($address)) {
                     $error = true;
                     break;
                 }
             }
             // add error
             if ($error) {
                 $txtEmail->addError(BL::getError('EmailIsInvalid'));
             }
         }
         // identifier
         if ($txtIdentifier->isFilled()) {
             // invalid characters
             if (!\SpoonFilter::isValidAgainstRegexp('/^[a-zA-Z0-9\\.\\_\\-]+$/', $txtIdentifier->getValue())) {
                 $txtIdentifier->setError(BL::getError('InvalidIdentifier'));
             } elseif (BackendFormBuilderModel::existsIdentifier($txtIdentifier->getValue())) {
                 // unique identifier
                 $txtIdentifier->setError(BL::getError('UniqueIdentifier'));
             }
         }
         if ($this->frm->isCorrect()) {
             // build array
             $values['language'] = BL::getWorkingLanguage();
             $values['user_id'] = BackendAuthentication::getUser()->getUserId();
             $values['name'] = $txtName->getValue();
             $values['method'] = $ddmMethod->getValue();
             $values['email'] = $ddmMethod->getValue() == 'database_email' ? serialize($emailAddresses) : null;
             $values['success_message'] = $txtSuccessMessage->getValue(true);
             $values['identifier'] = $txtIdentifier->isFilled() ? $txtIdentifier->getValue() : BackendFormBuilderModel::createIdentifier();
             $values['created_on'] = BackendModel::getUTCDate();
             $values['edited_on'] = BackendModel::getUTCDate();
             // insert the item
             $id = BackendFormBuilderModel::insert($values);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add', array('item' => $values));
             // set frontend locale
             FL::setLocale(BL::getWorkingLanguage(), true);
             // create submit button
             $field['form_id'] = $id;
             $field['type'] = 'submit';
             $field['settings'] = serialize(array('values' => \SpoonFilter::ucfirst(FL::getLabel('Send'))));
             BackendFormBuilderModel::insertField($field);
             // everything is saved, so redirect to the editform
             $this->redirect(BackendModel::createURLForAction('Edit') . '&id=' . $id . '&report=added&var=' . urlencode($values['name']) . '#tabFields');
         }
     }
 }
Example #20
0
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     //--Get the mailings which are ready to send
     $mails = BackendMailengineModel::getWaitingMailings();
     if (!empty($mails)) {
         //--Loop the mails
         foreach ($mails as $mail) {
             //--Get mailer-email to send the mail to
             $arrFrom = BackendModel::getModuleSetting('Core', 'mailer_from');
             //--Create variables array
             $variables = array();
             $variables['sentOn'] = time();
             $variables['dateFormatLong'] = BackendModel::getModuleSetting('Core', 'date_format_long') . " " . BackendModel::getModuleSetting('Core', 'time_format');
             $variables['subject'] = $mail['subject'];
             //--Send start mail
             /* $message = \Common\Mailer\Message::newInstance(
                    'Mailing started "' . $mail['subject'] . '"'
                )
                    ->setFrom(array($arrFrom['email'] => $arrFrom['name']))
                    ->setTo(array($arrFrom['email']))
                    ->parseHtml(
                        BACKEND_MODULES_PATH . '/Modules/Mailengine/Layout/Templates/Mails/MailingStart.tpl',
                        $variables
                    )
                ;
                $this->get('mailer')->send($message);*/
             //				$this->get('mailer')->addEmail('Mailing started "' . $mail['subject'] . '"', BACKEND_PATH . '/Modules/Mailengine/Layout/Templates/Mails/MailingStart.tpl', $variables, $arrFrom["email"], $arrFrom["name"]);
             //--Insert mail in stats
             $data = array();
             $data['id'] = $mail['id'];
             $data['mail_id'] = $mail['mail_id'];
             $data['domain'] = $mail['domain'];
             $data['subject'] = $mail['subject'];
             $data['text'] = $mail['text'];
             $data['start_time'] = $mail['start_time'];
             $data['end_time'] = $mail['end_time'];
             $data['from_name'] = $mail['from_name'];
             $data['from_email'] = $mail['from_email'];
             $data['reply_name'] = $mail['reply_name'];
             $data['reply_email'] = $mail['reply_email'];
             BackendMailengineModel::insertMailToStats($data);
             $mail['from_name'] = html_entity_decode($mail['from_name']);
             $mail['reply_name'] = html_entity_decode($mail['reply_name']);
             //--Update status
             BackendMailengineModel::updateStatusMailing($mail['id'], array('status' => 'busy'));
             //--Get the users for the mailing
             $users = BackendMailengineModel::getUsersForWaitingMail($mail['id']);
             if (!empty($users)) {
                 $count = 0;
                 //--Loop the users
                 foreach ($users as $user) {
                     //--Translate the text and subject with the user-vars
                     $text = BackendMailengineModel::translateUserVars($mail['text'], $user);
                     $subject = BackendMailengineModel::translateUserVars($mail['subject'], $user);
                     //--Send the mail
                     if (BackendMailengineModel::sendMail(html_entity_decode($subject), $text, $user['email'], $user['name'], $mail)) {
                         $data = array();
                         $data['send_id'] = $mail['id'];
                         $data['user_id'] = $user['id'];
                         //--Save the send-data for the mails
                         BackendMailengineModel::insertMailUsers($data);
                     }
                     //--Add count
                     $count++;
                     //--Let the script sleep for an instant after sending x-numbers of mails
                     if ($count % 50 == 0) {
                         sleep(5);
                         set_time_limit(120);
                     }
                 }
                 //--Update status
                 BackendMailengineModel::updateStatusMailing($mail['id'], array('status' => 'finished', 'end_time' => BackendModel::getUTCDate()));
                 //--Create variables array
                 $variables = array();
                 $variables['sentOn'] = time();
                 $variables['dateFormatLong'] = BackendModel::getModuleSetting('Core', 'date_format_long') . " " . BackendModel::getModuleSetting('Core', 'time_format');
                 $variables['subject'] = $mail['subject'];
                 $variables['users'] = count($users);
                 /*$message = \Common\Mailer\Message::newInstance(
                       'Mailing ended "' . $mail['subject'] . '"'
                   )
                       ->setFrom(array($arrFrom['email'] => $arrFrom['name']))
                       ->setTo(array($arrFrom['email']))
                       ->parseHtml(
                           BACKEND_MODULES_PATH . '/Modules/Mailengine/Layout/Templates/Mails/MailingEnd.tpl',
                           $variables
                       )
                   ;
                   $this->get('mailer')->send($message);*/
                 //--Send start mail
                 //					$this->get('mailer')->addEmail('Mailing ended "' . $mail['subject'] . '"', BACKEND_PATH . '/Modules/Mailengine/Layout/Templates/Mails/MailingEnd.tpl', $variables, $arrFrom["email"], $arrFrom["name"]);
             }
         }
     }
 }
Example #21
0
 /**
  * Validate the form.
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // get fields
         $ddmGroup = $this->frm->getField('group');
         $txtExpirationDate = $this->frm->getField('expiration_date');
         $txtExpirationTime = $this->frm->getField('expiration_time');
         // fields filled?
         $ddmGroup->isFilled(BL::getError('FieldIsRequired'));
         if ($txtExpirationDate->isFilled()) {
             $txtExpirationDate->isValid(BL::getError('DateIsInvalid'));
         }
         if ($txtExpirationTime->isFilled()) {
             $txtExpirationTime->isValid(BL::getError('TimeIsInvalid'));
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $values['profile_id'] = $this->id;
             $values['group_id'] = $ddmGroup->getSelected();
             $values['starts_on'] = BackendModel::getUTCDate();
             // only format date if not empty
             if ($txtExpirationDate->isFilled() && $txtExpirationTime->isFilled()) {
                 // format date
                 $values['expires_on'] = BackendModel::getUTCDate(null, BackendModel::getUTCTimestamp($txtExpirationDate, $txtExpirationTime));
             }
             // insert values
             $id = BackendProfilesModel::insertProfileGroup($values);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_profile_add_to_group', array('item' => $values));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('Edit') . '&id=' . $values['profile_id'] . '&report=membership-added&highlight=row-' . $id . '#tabGroups');
         }
     }
 }
Example #22
0
 /**
  * Update an existing item
  *
  * @param array $item The new data.
  *
  * @return int
  */
 public static function update(array $item)
 {
     $db = BackendModel::getContainer()->get('database');
     // check if new version is active
     if ($item['status'] == 'active') {
         // archive all older active versions
         $db->update('blog_posts', array('status' => 'archived'), 'id = ? AND status = ?', array($item['id'], $item['status']));
         // get the record of the exact item we're editing
         $revision = self::getRevision($item['id'], $item['revision_id']);
         // assign values
         $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s', $revision['created_on']);
         $item['num_comments'] = $revision['num_comments'];
         // if it used to be a draft that we're now publishing, remove drafts
         if ($revision['status'] == 'draft') {
             $db->delete('blog_posts', 'id = ? AND status = ?', array($item['id'], $revision['status']));
         }
     }
     // don't want revision id
     unset($item['revision_id']);
     // how many revisions should we keep
     $rowsToKeep = (int) BackendModel::get('fork.settings')->get('Blog', 'max_num_revisions', 20);
     // set type of archive
     $archiveType = $item['status'] == 'active' ? 'archived' : $item['status'];
     // get revision-ids for items to keep
     $revisionIdsToKeep = (array) $db->getColumn('SELECT i.revision_id
          FROM blog_posts AS i
          WHERE i.id = ? AND i.status = ? AND i.language = ?
          ORDER BY i.edited_on DESC
          LIMIT ?', array($item['id'], $archiveType, BL::getWorkingLanguage(), $rowsToKeep));
     // delete other revisions
     if (!empty($revisionIdsToKeep)) {
         // get meta-ids that will be deleted
         $metasIdsToRemove = (array) $db->getColumn('SELECT i.meta_id
              FROM blog_posts AS i
              WHERE i.id = ? AND revision_id NOT IN (' . implode(', ', $revisionIdsToKeep) . ')', array($item['id']));
         // get all the images of the revisions that will NOT be deleted
         $imagesToKeep = $db->getColumn('SELECT image FROM blog_posts
              WHERE id = ? AND revision_id IN (' . implode(', ', $revisionIdsToKeep) . ')', array($item['id']));
         // get the images of the revisions that will be deleted
         $imagesOfDeletedRevisions = $db->getColumn('SELECT image FROM blog_posts
             WHERE id = ? AND status = ? AND revision_id NOT IN (' . implode(', ', $revisionIdsToKeep) . ')', array($item['id'], $archiveType));
         // make sure that an image that will be deleted, is not used by a revision that is not to be deleted
         foreach ($imagesOfDeletedRevisions as $imageOfDeletedRevision) {
             if (!in_array($imageOfDeletedRevision, $imagesToKeep)) {
                 BackendModel::deleteThumbnails(FRONTEND_FILES_PATH . '/blog/images', $imageOfDeletedRevision);
             }
         }
         $db->delete('blog_posts', 'id = ? AND status = ? AND revision_id NOT IN (' . implode(', ', $revisionIdsToKeep) . ')', array($item['id'], $archiveType));
         if (!empty($metasIdsToRemove)) {
             $db->delete('meta', 'id IN (' . implode(', ', $metasIdsToRemove) . ')');
         }
     }
     // insert new version
     $item['revision_id'] = BackendModel::getContainer()->get('database')->insert('blog_posts', $item);
     // return the new revision id
     return $item['revision_id'];
 }
Example #23
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // validate fields
         $this->frm->getField('email')->isFilled(BL::err('EmailIsRequired'));
         // get addresses
         $addresses = (array) explode(',', $this->frm->getField('email')->getValue());
         // loop addresses
         foreach ($addresses as $email) {
             // validate email
             if (!\SpoonFilter::isEmail(trim($email))) {
                 // add error if needed
                 $this->frm->getField('email')->addError(BL::err('ContainsInvalidEmail'));
                 // stop looking
                 break;
             }
         }
         $this->frm->getField('groups')->isFilled(BL::err('ChooseAtLeastOneGroup'));
         // no errors?
         if ($this->frm->isCorrect()) {
             // build item
             $item = $this->frm->getValues();
             $item['source'] = BL::lbl('Manual');
             $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
             // loop the groups
             foreach ($item['groups'] as $group) {
                 foreach ($addresses as $email) {
                     BackendMailmotorCMHelper::subscribe(trim($email), $group);
                 }
             }
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add_address', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('Addresses') . (!empty($this->groupId) ? '&group_id=' . $this->groupId : '') . '&report=added');
         }
     }
 }
Example #24
0
 /**
  * Unsubscribes an e-mail address from CampaignMonitor and our database
  *
  * @param string $email   The emailaddress to unsubscribe.
  * @param string $groupId The group wherefrom the emailaddress should be unsubscribed.
  * @return bool
  */
 public static function unsubscribe($email, $groupId = null)
 {
     $groupId = !empty($groupId) ? $groupId : BackendMailmotorModel::getDefaultGroupID();
     $groupCMId = self::getCampaignMonitorID('list', $groupId);
     // group exists
     if (BackendMailmotorModel::existsGroup($groupId)) {
         self::getCM()->unsubscribe($email, $groupCMId);
         $subscriber = array();
         $subscriber['status'] = 'unsubscribed';
         $subscriber['unsubscribed_on'] = BackendModel::getUTCDate('Y-m-d H:i:s');
         BackendModel::getContainer()->get('database')->update('mailmotor_addresses_groups', $subscriber, 'email = ? AND group_id = ?', array($email, $groupId));
         return true;
     }
     return false;
 }
Example #25
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // get fields
         $txtEmail = $this->frm->getField('email');
         $txtDisplayName = $this->frm->getField('display_name');
         $txtPassword = $this->frm->getField('password');
         $txtFirstName = $this->frm->getField('first_name');
         $txtLastName = $this->frm->getField('last_name');
         $txtCity = $this->frm->getField('city');
         $ddmGender = $this->frm->getField('gender');
         $ddmDay = $this->frm->getField('day');
         $ddmMonth = $this->frm->getField('month');
         $ddmYear = $this->frm->getField('year');
         $ddmCountry = $this->frm->getField('country');
         // email filled in?
         if ($txtEmail->isFilled(BL::getError('EmailIsRequired'))) {
             // valid email?
             if ($txtEmail->isEmail(BL::getError('EmailIsInvalid'))) {
                 // email already exists?
                 if (BackendProfilesModel::existsByEmail($txtEmail->getValue())) {
                     // set error
                     $txtEmail->addError(BL::getError('EmailExists'));
                 }
             }
         }
         // display name filled in?
         if ($txtDisplayName->isFilled(BL::getError('DisplayNameIsRequired'))) {
             // display name already exists?
             if (BackendProfilesModel::existsDisplayName($txtDisplayName->getValue())) {
                 // set error
                 $txtDisplayName->addError(BL::getError('DisplayNameExists'));
             }
         }
         // profile must not be notified, password must not be empty
         if (!$this->notifyProfile) {
             $txtPassword->isFilled(BL::err('FieldIsRequired'));
         }
         // one of the birthday fields are filled in
         if ($ddmDay->isFilled() || $ddmMonth->isFilled() || $ddmYear->isFilled()) {
             // valid date?
             if (!checkdate($ddmMonth->getValue(), $ddmDay->getValue(), $ddmYear->getValue())) {
                 // set error
                 $ddmYear->addError(BL::getError('DateIsInvalid'));
             }
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             $salt = BackendProfilesModel::getRandomString();
             $password = $txtPassword->isFilled() ? $txtPassword->getValue() : BackendModel::generatePassword(8);
             // build item
             $values = array('email' => $txtEmail->getValue(), 'registered_on' => BackendModel::getUTCDate(), 'display_name' => $txtDisplayName->getValue(), 'url' => BackendProfilesModel::getUrl($txtDisplayName->getValue()), 'last_login' => BackendModel::getUTCDate(null, 0), 'password' => BackendProfilesModel::getEncryptedString($password, $salt));
             $this->id = BackendProfilesModel::insert($values);
             // update salt
             BackendProfilesModel::setSetting($this->id, 'salt', $salt);
             // bday is filled in
             if ($ddmYear->isFilled()) {
                 // mysql format
                 $birthDate = $ddmYear->getValue() . '-';
                 $birthDate .= str_pad($ddmMonth->getValue(), 2, '0', STR_PAD_LEFT) . '-';
                 $birthDate .= str_pad($ddmDay->getValue(), 2, '0', STR_PAD_LEFT);
             } else {
                 // not filled in
                 $birthDate = null;
             }
             // update settings
             BackendProfilesModel::setSetting($this->id, 'first_name', $txtFirstName->getValue());
             BackendProfilesModel::setSetting($this->id, 'last_name', $txtLastName->getValue());
             BackendProfilesModel::setSetting($this->id, 'gender', $ddmGender->getValue());
             BackendProfilesModel::setSetting($this->id, 'birth_date', $birthDate);
             BackendProfilesModel::setSetting($this->id, 'city', $txtCity->getValue());
             BackendProfilesModel::setSetting($this->id, 'country', $ddmCountry->getValue());
             // notify values
             $notifyValues = array_merge($values, array('id' => $this->id, 'first_name' => $txtFirstName->getValue(), 'last_name' => $txtLastName->getValue(), 'unencrypted_password' => $password));
             $redirectUrl = BackendModel::createURLForAction('Edit') . '&id=' . $this->id . '&var=' . rawurlencode($values['display_name']) . '&report=';
             // notify new profile user
             if ($this->notifyProfile) {
                 BackendProfilesModel::notifyProfile($notifyValues);
                 $redirectUrl .= 'saved-and-notified';
             } else {
                 $redirectUrl .= 'saved';
             }
             // notify admin
             if ($this->notifyAdmin) {
                 BackendProfilesModel::notifyAdmin($notifyValues);
             }
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add', array('item' => $values));
             // everything is saved, so redirect to the overview
             $this->redirect($redirectUrl);
         }
     }
 }
Example #26
0
 /**
  * Insert an item in the database
  *
  * @param array $data
  * @return int
  */
 public static function insert(array $data)
 {
     $data['created_on'] = BackendModel::getUTCDate();
     return (int) BackendModel::get('database')->insert('media', $data);
 }
Example #27
0
 /**
  * Import CSV data
  *
  * @param array $data The array from the .csv file
  * @param int[optional] $groupId Adding these profiles to a group
  * @param bool[optional] $overwriteExisting If set to true, this will overwrite existing profiles
  * @param return array('count' => array('exists' => 0, 'inserted' => 0));
  */
 public static function importCsv($data, $groupId = null, $overwriteExisting = false)
 {
     // init statistics
     $statistics = array('count' => array('exists' => 0, 'inserted' => 0));
     // loop data
     foreach ($data as $item) {
         // field checking
         if (!isset($item['email']) || !isset($item['display_name']) || !isset($item['password'])) {
             throw new BackendException('The .csv file should have the following columns; "email", "password" and "display_name".');
         }
         // init $insert
         $values = array();
         // define exists
         $exists = self::existsByEmail($item['email']);
         // do not overwrite existing profiles
         if ($exists && !$overwriteExisting) {
             // adding to exists
             $statistics['count']['exists'] += 1;
             // skip this item
             continue;
         }
         // build item
         $values = array('email' => $item['email'], 'registered_on' => BackendModel::getUTCDate(), 'display_name' => $item['display_name'], 'url' => self::getUrl($item['display_name']));
         // does not exists
         if (!$exists) {
             // import
             $id = self::insert($values);
             // update counter
             $statistics['count']['inserted'] += 1;
             // already exists
         } else {
             // get profile
             $profile = self::getByEmail($item['email']);
             $id = $profile['id'];
             // exists
             $statistics['count']['exists'] += 1;
         }
         // new password filled in?
         if ($item['password']) {
             // get new salt
             $salt = self::getRandomString();
             // update salt
             self::setSetting($id, 'salt', $salt);
             // build password
             $values['password'] = self::getEncryptedString($item['password'], $salt);
         }
         // update values
         self::update($id, $values);
         // we have a group id
         if ($groupId) {
             // init values
             $values = array();
             // build item
             $values['profile_id'] = $id;
             $values['group_id'] = $groupId;
             $values['starts_on'] = BackendModel::getUTCDate();
             // insert values
             $id = self::insertProfileGroup($values);
         }
     }
     return $statistics;
 }
Example #28
0
 public function AddVideo($type, $id)
 {
     //--Check if the file is an image or file
     $item = array();
     $item["filename"] = $id;
     $item["extension"] = $type;
     $item["created_on"] = BackendModel::getUTCDate('Y-m-d H:i:s');
     $item["filesize"] = 0;
     $item["filetype"] = 3;
     //--Serialize data
     //$item["data"] = serialize($data);
     //--Store item so we can access it
     $this->item = $item;
     //--Insert into media
     $media_id = BackendModel::getContainer()->get('database')->insert("media", $item);
     $this->item['media_id'] = $media_id;
     $this->item["text"] = "";
     //--Link the
     $this->item['id'] = $this->linkMediaToModule($media_id);
     return $media_id;
 }
Example #29
0
 /**
  * Login the user with the given credentials.
  * Will return a boolean that indicates if the user is logged in.
  *
  * @param string $login    The users login.
  * @param string $password The password provided by the user.
  *
  * @return bool
  */
 public static function loginUser($login, $password)
 {
     $login = (string) $login;
     $password = (string) $password;
     $db = BackendModel::get('database');
     // fetch the encrypted password
     $passwordEncrypted = static::getEncryptedPassword($login, $password);
     // check in database (is the user active and not deleted, are the email and password correct?)
     $userId = (int) $db->getVar('SELECT u.id
          FROM users AS u
          WHERE u.email = ? AND u.password = ? AND u.active = ? AND u.deleted = ?
          LIMIT 1', array($login, $passwordEncrypted, 'Y', 'N'));
     // not 0 = valid user!
     if ($userId !== 0) {
         // cleanup old sessions
         self::cleanupOldSessions();
         // build the session array (will be stored in the database)
         $session = array();
         $session['user_id'] = $userId;
         $session['secret_key'] = static::getEncryptedString(\SpoonSession::getSessionId(), $userId);
         $session['session_id'] = \SpoonSession::getSessionId();
         $session['date'] = BackendModel::getUTCDate();
         // insert a new row in the session-table
         $db->insert('users_sessions', $session);
         // store some values in the session
         \SpoonSession::set('backend_logged_in', true);
         \SpoonSession::set('backend_secret_key', $session['secret_key']);
         // update/instantiate the value for the logged_in container.
         BackendModel::getContainer()->set('logged_in', true);
         self::$user = new User($userId);
         // return result
         return true;
     } else {
         // userId 0 will not exist, so it means that this isn't a valid combination
         // reset values for invalid users. We can't destroy the session
         // because session-data can be used on the site.
         \SpoonSession::set('backend_logged_in', false);
         \SpoonSession::set('backend_secret_key', '');
         // update/instantiate the value for the logged_in container.
         BackendModel::getContainer()->set('logged_in', false);
         // return result
         return false;
     }
 }
Example #30
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     if ($this->frm->isSubmitted()) {
         $this->frm->cleanupFields();
         // shorten the fields
         $txtName = $this->frm->getField('name');
         $txtEmail = $this->frm->getField('email');
         $ddmMethod = $this->frm->getField('method');
         $txtSuccessMessage = $this->frm->getField('success_message');
         $txtIdentifier = $this->frm->getField('identifier');
         $emailAddresses = (array) explode(',', $txtEmail->getValue());
         // validate fields
         $txtName->isFilled(BL::getError('NameIsRequired'));
         $txtSuccessMessage->isFilled(BL::getError('SuccessMessageIsRequired'));
         if ($ddmMethod->isFilled(BL::getError('NameIsRequired')) && $ddmMethod->getValue() == 'database_email') {
             $error = false;
             // check the addresses
             foreach ($emailAddresses as $address) {
                 $address = trim($address);
                 if (!\SpoonFilter::isEmail($address)) {
                     $error = true;
                     break;
                 }
             }
             // add error
             if ($error) {
                 $txtEmail->addError(BL::getError('EmailIsInvalid'));
             }
         }
         // identifier
         if ($txtIdentifier->isFilled()) {
             // invalid characters
             if (!\SpoonFilter::isValidAgainstRegexp('/^[a-zA-Z0-9\\.\\_\\-]+$/', $txtIdentifier->getValue())) {
                 $txtIdentifier->setError(BL::getError('InvalidIdentifier'));
             } elseif (BackendFormBuilderModel::existsIdentifier($txtIdentifier->getValue(), $this->id)) {
                 $txtIdentifier->setError(BL::getError('UniqueIdentifier'));
             }
         }
         if ($this->frm->isCorrect()) {
             // build array
             $values['name'] = $txtName->getValue();
             $values['method'] = $ddmMethod->getValue();
             $values['email'] = $ddmMethod->getValue() == 'database_email' ? serialize($emailAddresses) : null;
             $values['success_message'] = $txtSuccessMessage->getValue(true);
             $values['identifier'] = $txtIdentifier->isFilled() ? $txtIdentifier->getValue() : BackendFormBuilderModel::createIdentifier();
             $values['edited_on'] = BackendModel::getUTCDate();
             // insert the item
             $id = (int) BackendFormBuilderModel::update($this->id, $values);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_edit', array('item' => $values));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('Index') . '&report=edited&var=' . urlencode($values['name']) . '&highlight=row-' . $id);
         }
     }
 }