protected function initAttachments($feedAutoId, Form $form) { $attachmentInputId = $form->getElement('attachment')->getId(); $attachmentId = 'nfa-' . $feedAutoId; $inputId = $form->getElement('status')->getId(); $js = 'OWLinkObserver.observeInput("' . $inputId . '", function(link){ var ac = $("#attachment_preview_' . $attachmentId . '"); ac.show().html("<div class=\\"ow_preloader\\" style=\\"height: 30px;\\"></div>"); this.requestResult(function( r ) { ac.html(r); }); this.onResult = function( r ) { $("#' . $attachmentInputId . '").val(JSON.stringify(r)); }; });'; OW::getDocument()->addOnloadScript($js); $this->assign('uniqId', $attachmentId); $attachment = new BASE_CLASS_Attachment($attachmentId); $this->addComponent('attachment', $attachment); $js = 'owForms[{$form}].bind("success", function(data){ OW.trigger("base.init_attachment", {$uniqId}); owForms[{$form}].getElement("attachment").setValue(""); OWLinkObserver.getObserver("' . $inputId . '").resetObserver(); }); owForms[{$form}].reset = false; OW.bind("base.attachment_added", function(data){ if( data.uid == {$uniqId} ){ owForms[{$form}].getElement("attachment").setValue(JSON.stringify(data)); } } ); OW.bind("base.attachment_deleted", function(data){ if( data.uid == {$uniqId} ){ owForms[{$form}].getElement("attachment").setValue(""); OWLinkObserver.getObserver("' . $inputId . '").resetObserver(); } } );'; $js = UTIL_JsGenerator::composeJsString($js, array('form' => $form->getName(), 'uniqId' => $attachmentId)); OW::getDocument()->addOnloadScript($js); }
function testShouldListPossibleParents() { $mapper = new DataMapper($this->db); $parent1_id = $mapper->save(array('name' => 'Parent 1')); $mapper = new DataMapper($this->db); $parent2_id = $mapper->save(array('name' => 'Parent 1a', 'paths' => array($parent1_id))); $form = new Form($mapper); $expected = array($parent1_id => 'Parent 1', $parent1_id . '/' . $parent2_id => 'Parent 1a'); $this->assertEquals($expected, $form->getElement('paths')->getMultiOptions()); }
function testShouldListPossibleCategories() { $mapper = new \Metator\Category\DataMapper($this->db); $parent1_id = $mapper->save(array('name' => 'Parent 1')); $mapper = new \Metator\Category\DataMapper($this->db); $parent2_id = $mapper->save(array('name' => 'Parent 2', 'paths' => array($parent1_id))); $mapper = new \Metator\Category\DataMapper($this->db); $parent3_id = $mapper->save(array('name' => 'Parent 3', 'paths' => array($parent1_id . '/' . $parent2_id))); $form = new Form($mapper); $expected = array($parent1_id => 'Parent 1', $parent2_id => '-Parent 2', $parent3_id => '--Parent 3'); $this->assertEquals($expected, $form->getElement('categories')->getMultiOptions()); }
public static function setLabels(Form $form, array $questions) { foreach ($questions as $question) { if (!empty($question['required'])) { /* @var $element FormElement */ $element = $form->getElement($question['name']); if (empty($element)) { continue; } $label = $element->getLabel(); $label .= '<span class="owm_required_star">*<span>'; $element->setLabel($label); if ($question['name'] == 'password') { $element = $form->getElement('repeatPassword'); $label = $element->getLabel(); $label .= '<span class="owm_required_star">*<span>'; $element->setLabel($label); } } } }
public function __construct($entityType, $entityId, $displayType, $pluginKey, $ownerId, $commentCountOnPage, $id, $cmpContextId, $formName) { parent::__construct(); $language = OW::getLanguage(); //comment form init $form = new Form($formName); $textArea = new Textarea('commentText'); $form->addElement($textArea); $entityTypeField = new HiddenField('entityType'); $form->addElement($entityTypeField); $entityIdField = new HiddenField('entityId'); $form->addElement($entityIdField); $displayTypeField = new HiddenField('displayType'); $form->addElement($displayTypeField); $pluginKeyField = new HiddenField('pluginKey'); $form->addElement($pluginKeyField); $ownerIdField = new HiddenField('ownerId'); $form->addElement($ownerIdField); $attch = new HiddenField('attch'); $form->addElement($attch); $cid = new HiddenField('cid'); $form->addElement($cid); $commentsOnPageField = new HiddenField('commentCountOnPage'); $form->addElement($commentsOnPageField); $submit = new Submit('comment-submit'); $submit->setValue($language->text('base', 'comment_add_submit_label')); $form->addElement($submit); $form->getElement('entityType')->setValue($entityType); $form->getElement('entityId')->setValue($entityId); $form->getElement('displayType')->setValue($displayType); $form->getElement('pluginKey')->setValue($pluginKey); $form->getElement('ownerId')->setValue($ownerId); $form->getElement('cid')->setValue($id); $form->getElement('commentCountOnPage')->setValue($commentCountOnPage); $form->setAjax(true); $form->setAction(OW::getRouter()->urlFor('BASE_CTRL_Comments', 'addComment')); $form->bindJsFunction(Form::BIND_SUBMIT, "function(){ \$('#comments-" . $id . " .comments-preloader').show();}"); $form->bindJsFunction(Form::BIND_SUCCESS, "function(){ \$('#comments-" . $id . " .comments-preloader').hide();}"); $this->addForm($form); if (BOL_TextFormatService::getInstance()->isCommentsRichMediaAllowed()) { $attachmentCmp = new BASE_CLASS_Attachment($id); $this->addComponent('attachment', $attachmentCmp); } OW::getDocument()->addOnloadScript("owCommentCmps['{$id}'].initForm('" . $form->getElement('commentText')->getId() . "', '" . $form->getElement('attch')->getId() . "');"); $this->assign('form', true); $this->assign('id', $id); if (OW::getUser()->isAuthenticated()) { $currentUserInfo = BOL_AvatarService::getInstance()->getDataForUserAvatars(array(OW::getUser()->getId())); $this->assign('currentUserInfo', $currentUserInfo[OW::getUser()->getId()]); } }
public static function SaveWidgetHandler(Form $form) { $id = $form->getElement('id')->get('value'); // ID can be null, that just means it's a new widget! if (!$id) { // Generate an id! $id = Core::GenerateUUID(); } $model = new WidgetModel('/gallery/view/' . $id); $model->set('editurl', '/gallerywidget/update/' . $id); $model->set('deleteurl', '/gallerywidget/delete/' . $id); $model->set('title', $form->getElement('title')->get('value')); $model->setSetting('album', $form->getElement('album')->get('value')); $model->setSetting('count', $form->getElement('count')->get('value')); $model->setSetting('order', $form->getElement('order')->get('value')); $model->setSetting('dimensions', $form->getElement('dimensions')->get('value')); $model->setSetting('uselightbox', $form->getElement('uselightbox')->get('value')); $model->save(); return 'back'; }
/** * Get the form for article creation and updating. * * @param BlogArticleModel $article * * @return Form */ public static function GetArticleForm(BlogArticleModel $article) { $page = $article->getLink('Page'); $blog = $article->getLink('Blog'); $page->set('parenturl', $blog->get('baseurl')); $form = new Form(); $form->set('callsmethod', 'BlogHelper::BlogArticleFormHandler'); $form->addModel($page, 'page'); $form->addModel($article, 'model'); if (Core::IsComponentAvailable('facebook') && Core::IsLibraryAvailable('jquery')) { // Is this article already posted? if ($article->get('fb_post_id')) { $form->addElement('select', ['disabled' => true, 'title' => 'Post to Facebook', 'options' => ['' => 'Posted!'], 'group' => 'Publish Settings']); } else { $form->addElement('select', ['class' => 'facebook-post-to-select', 'title' => 'Post to Facebook', 'name' => 'facebook_post', 'options' => ['' => '-- Please enable javascript --'], 'group' => 'Publish Settings']); } } // Lock in some elements for this blog article page. $form->getElement('page[parenturl]')->setFromArray(array('value' => $blog->get('baseurl'), 'readonly' => 'readonly')); // And remove a few other elements. $form->removeElement('model[title]'); return $form; }
public static function UpdateHandler(\Form $form){ /** @var \UserModel $user */ $user = $form->getElement('user')->get('value'); $userid = $user->get('id'); $usermanager = \Core\user()->checkAccess('p:/user/users/manage'); // Only allow this if the user is either the same user or has the user manage permission. if(!($userid == \Core\user()->get('id') || $usermanager)){ \Core\set_message('t:MESSAGE_ERROR_INSUFFICIENT_ACCESS_PERMISSIONS'); return false; } if(!$user->exists()){ \Core\set_message('t:MESSAGE_ERROR_REQUESTED_RESOURCE_NOT_FOUND'); return false; } $userisactive = $user->get('active'); $user->setFromForm($form); if($userisactive == 1 && $user->get('active') == 0){ // User was set from active to inactive. // Instead of setting to a new account, set to deactivated. $user->set('active', '-1'); } elseif($userisactive == -1 && $user->get('active') == 0){ // User was deactivated before, reset back to that. // This is because the active form element is simply an on/off checkbox. $user->set('active', '-1'); } $user->save(); if($userisactive == 0 && $user->get('active') == 1){ // If the user wasn't active before, but is now.... // Send an activation notice email to the user. try{ $email = new \Email(); $email->templatename = 'emails/user/activation.tpl'; $email->assign('user', $user); $email->assign('sitename', SITENAME); $email->assign('rooturl', ROOT_URL); $email->assign('loginurl', \Core\resolve_link('/user/login')); $email->setSubject('Welcome to ' . SITENAME); $email->to($user->get('email')); // TESTING //error_log($email->renderBody()); $email->send(); } catch(\Exception $e){ \Core\ErrorManagement\exception_handler($e); } } // If this was the current user, update the session data too! if($user->get('id') == \core\user()->get('id')){ Session::SetUser($user); if(\ConfigHandler::Get('/user/profileedits/requireapproval') && \Core::IsComponentAvailable('model-audit')){ \Core\set_message('t:MESSAGE_SUCCESS_UPDATED_OWN_USER_ACCOUNT_PENDING_APPROVAL'); } else{ \Core\set_message('t:MESSAGE_SUCCESS_UPDATED_OWN_USER_ACCOUNT'); } } else{ \Core\set_message('t:MESSAGE_SUCCESS_UPDATED_USER_ACCOUNT'); } return true; }
protected function initAttachments($feedAutoId, Form $form) { $attachmentInputId = $form->getElement('attachment')->getId(); $attachmentId = uniqid('nfa-' . $feedAutoId); $attachmentBtnId = $attachmentId . "-btn"; $inputId = $form->getElement('status')->getId(); $js = 'OWLinkObserver.observeInput("' . $inputId . '", function(link){ var ac = $("#attachment_preview_' . $attachmentId . '-oembed"); if ( ac.data("sleep") ) return; ac.show().html("<div class=\\"ow_preloader\\" style=\\"height: 30px;\\"></div>"); this.requestResult(function( r ) { ac.show().html(r); }); this.onResult = function( r ) { $("#' . $attachmentInputId . '").val(JSON.stringify(r)); }; });'; OW::getDocument()->addOnloadScript($js); $this->assign('uniqId', $attachmentId); $attachment = new BASE_CLASS_Attachment("newsfeed", $attachmentId, $attachmentBtnId); $this->addComponent('attachment', $attachment); $js = 'var attUid = {$uniqId}, uidUniq = 0; owForms[{$form}].bind("success", function(data){ OW.trigger("base.photo_attachment_reset", {pluginKey:"newsfeed", uid:attUid}); owForms[{$form}].getElement("attachment").setValue(""); OWLinkObserver.getObserver("' . $inputId . '").resetObserver(); $("#attachment_preview_" + {$uniqId} + "-oembed").data("sleep", false).empty(); var attOldUid = attUid; attUid = {$uniqId} + (uidUniq++); OW.trigger("base.photo_attachment_uid_update", { uid: attOldUid, newUid: attUid }); }); owForms[{$form}].reset = false; OW.bind("base.add_photo_attachment_submit", function(data){ if( data.uid == attUid ) { $("#attachment_preview_" + {$uniqId} + "-oembed").hide().empty(); $("#attachment_preview_" + {$uniqId} + "-oembed").data("sleep", true); } } ); OW.bind("base.attachment_hide_button_cont", function(data){ if( data.uid == attUid ) { $("#" + {$uniqId} + "-btn-cont").hide(); } } ); OW.bind("base.attachment_show_button_cont", function(data){ if( data.uid == attUid ) { $("#" + {$uniqId} + "-btn-cont").show(); } } ); OW.bind("base.attachment_added", function(data){ if( data.uid == attUid ) { data.type = "photo"; owForms[{$form}].getElement("attachment").setValue(JSON.stringify(data)); } } ); OW.bind("base.attachment_deleted", function(data){ if( data.uid == attUid ){ $("#attachment_preview_" + {$uniqId} + "-oembed").data("sleep", false).empty(); owForms[{$form}].getElement("attachment").setValue(""); OWLinkObserver.getObserver("' . $inputId . '").resetObserver(); } } );'; $js = UTIL_JsGenerator::composeJsString($js, array('form' => $form->getName(), 'uniqId' => $attachmentId)); OW::getDocument()->addOnloadScript($js); }
public static function _UploadHandler(Form $form) { $localfile = \Core\Filestore\Factory::File($form->getElement('upload')->get('value')); $localobj = $localfile->getContentsObject(); if(!$localobj instanceof Core\Filestore\Contents\ContentTGZ){ $localfile->delete(); \Core\set_message('Invalid file uploaded', 'error'); return false; } $tmpdir = $localobj->extract('tmp/installer-' . Core::RandomHex(4)); // There should now be a package.xml metafile inside that temporary directory. // Parse it to get the necessary information for this package. $metafile = \Core\Filestore\Factory::File($tmpdir->getPath() . 'package.xml'); if(!$metafile->exists()){ $localfile->delete(); $tmpdir->delete(); \Core\set_message('Invalid package, package does not contain a "package.xml" file.'); return false; } $pkg = new PackageXML($metafile->getFilename()); $key = str_replace(' ', '-', strtolower($pkg->getName())); $name = $pkg->getName(); $type = $pkg->getType(); $version = $pkg->getVersion(); // Validate the contents of the package. if(!( $type == 'component' || $type == 'theme' || $type == 'core' )){ $localfile->delete(); $tmpdir->delete(); \Core\set_message('Invalid package, package does not appear to be a valid Core package.'); return false; } // Now that the data is extracted in a temporary directory, extract every file in the destination. /** @var $datadir \Core\Filestore\Directory */ $datadir = $tmpdir->get('data/'); if(!$datadir){ \Core\set_message('Invalid package, package does not contain a "data" directory.'); return false; } if($type == 'component'){ $destdir = ROOT_PDIR . 'components/' . $key . '/'; } elseif($type == 'theme'){ $destdir = ROOT_PDIR . 'themes/' . $key . '/'; } else{ $destdir = ROOT_PDIR . '/'; } try{ // Will give me an array of Files in the data directory. $files = $datadir->ls(null, true); // Used to get the relative path for each contained file. $datalen = strlen($datadir->getPath()); foreach($files as $file){ if(!$file instanceof \Core\Filestore\Backends\FileLocal) continue; // It's a file, copy it over. // To do so, resolve the directory path inside the temp data dir. $dest = \Core\Filestore\Factory::File($destdir . substr($file->getFilename(), $datalen)); /** @var $dest \Core\Filestore\Backends\FileLocal */ $dest->copyFrom($file, true); } } catch(Exception $e){ // OH NOES! $localfile->delete(); $tmpdir->delete(); \Core\set_message($e->getMessage(), 'error'); return false; } // Cleanup everything $localfile->delete(); $tmpdir->delete(); // Clear the cache so the next pageload will pick up on the new components and goodies. \Core\Cache::Flush(); \Core\Templates\Backends\Smarty::FlushCache(); // Print a nice message to the user that it completed. \Core\set_message('Successfully installed ' . $name . ' ' . $version, 'success'); return '/updater'; }
public static function _UpdateFormHandler(Form $form){ try{ /** @var UserGroupModel $model */ $model = $form->getModel(); if(\Core\user()->checkAccess('p:/user/permissions/manage')){ // hehe... this is kind of a hack that works. // it's a hack because "getElement" returns only 1 element, but it works // because all those elements share the same POST name. // As such, the value from all permission[] checkboxes actually get transposed to all // form elements with that same base name. $model->setPermissions($form->getElement('permissions[]')->get('value')); } if($model->get('context') != ''){ // Non-global context groups can never be default! $model->set('default', 0); } $model->save(); } catch(ModelValidationException $e){ \Core\set_message($e->getMessage(), 'error'); return false; } catch(Exception $e){ \Core\set_message($e->getMessage(), 'error'); return false; } return '/usergroupadmin'; }
/** * Form Handler for logging in. * * @static * * @param \Form $form * * @return bool|null|string */ public static function LoginHandler(\Form $form){ /** @var \FormElement $e */ $e = $form->getElement('email'); /** @var \FormElement $p */ $p = $form->getElement('pass'); /** @var \UserModel $u */ $u = \UserModel::Find(array('email' => $e->get('value')), 1); if(!$u){ // Log this as a login attempt! $logmsg = 'Failed Login. Email not registered' . "\n" . 'Email: ' . $e->get('value') . "\n"; \SystemLogModel::LogSecurityEvent('/user/login', $logmsg); $e->setError('t:MESSAGE_ERROR_USER_LOGIN_EMAIL_NOT_FOUND'); return false; } if($u->get('active') == 0){ // The model provides a quick cut-off for active/inactive users. // This is the control managed with in the admin. $logmsg = 'Failed Login. User tried to login before account activation' . "\n" . 'User: '******'email') . "\n"; \SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id')); $e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_NOT_ACTIVE'); return false; } elseif($u->get('active') == -1){ // The model provides a quick cut-off for active/inactive users. // This is the control managed with in the admin. $logmsg = 'Failed Login. User tried to login after account deactivation.' . "\n" . 'User: '******'email') . "\n"; \SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id')); $e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_DEACTIVATED'); return false; } try{ /** @var \Core\User\AuthDrivers\datastore $auth */ $auth = $u->getAuthDriver('datastore'); } catch(Exception $e){ $e->setError('t:MESSAGE_ERROR_USER_LOGIN_PASSWORD_AUTH_DISABLED'); return false; } // This is a special case if the password isn't set yet. // It can happen with imported users or if a password is invalidated. if($u->get('password') == ''){ // Use the Nonce system to generate a one-time key with this user's data. $nonce = \NonceModel::Generate( '20 minutes', ['type' => 'password-reset', 'user' => $u->get('id')] ); $link = '/datastoreauth/forgotpassword?e=' . urlencode($u->get('email')) . '&n=' . $nonce; $email = new \Email(); $email->setSubject('Initial Password Request'); $email->to($u->get('email')); $email->assign('link', \Core\resolve_link($link)); $email->assign('ip', REMOTE_IP); $email->templatename = 'emails/user/initialpassword.tpl'; try{ $email->send(); \SystemLogModel::LogSecurityEvent('/user/initialpassword/send', 'Initial password request sent successfully', null, $u->get('id')); \Core\set_message('t:MESSAGE_INFO_USER_LOGIN_MUST_SET_NEW_PASSWORD_INSTRUCTIONS_HAVE_BEEN_EMAILED'); return true; } catch(\Exception $e){ \Core\ErrorManagement\exception_handler($e); \Core\set_message('t:MESSAGE_ERROR_USER_LOGIN_MUST_SET_NEW_PASSWORD_UNABLE_TO_SEND_EMAIL'); return false; } } if(!$auth->checkPassword($p->get('value'))){ // Log this as a login attempt! $logmsg = 'Failed Login. Invalid password' . "\n" . 'Email: ' . $e->get('value') . "\n"; \SystemLogModel::LogSecurityEvent('/user/login/failed_password', $logmsg, null, $u->get('id')); // Also, I want to look up and see how many login attempts there have been in the past couple minutes. // If there are too many, I need to start slowing the attempts. $time = new \CoreDateTime(); $time->modify('-5 minutes'); $securityfactory = new \ModelFactory('SystemLogModel'); $securityfactory->where('code = /user/login/failed_password'); $securityfactory->where('datetime > ' . $time->getFormatted(\Time::FORMAT_EPOCH, \Time::TIMEZONE_GMT)); $securityfactory->where('ip_addr = ' . REMOTE_IP); $attempts = $securityfactory->count(); if($attempts > 4){ // Start slowing down the response. This should help deter brute force attempts. // (x+((x-7)/4)^3)-4 sleep( ($attempts+(($attempts-7)/4)^3)-4 ); // This makes a nice little curve with the following delays: // 5th attempt: 0.85 // 6th attempt: 2.05 // 7th attempt: 3.02 // 8th attempt: 4.05 // 9th attempt: 5.15 // 10th attempt: 6.52 // 11th attempt: 8.10 // 12th attempt: 10.05 } $e->setError('t:MESSAGE_ERROR_USER_LOGIN_INCORRECT_PASSWORD'); $p->set('value', ''); return false; } if($form->getElementValue('redirect')){ // The page was set via client-side javascript on the login page. // This is the most reliable option. $url = $form->getElementValue('redirect'); } elseif(REL_REQUEST_PATH == '/user/login'){ // If the user came from the registration page, get the page before that. $url = $form->referrer; } else{ // else the registration link is now on the same page as the 403 handler. $url = REL_REQUEST_PATH; } // Well, record this too! \SystemLogModel::LogSecurityEvent('/user/login', 'Login successful (via password)', null, $u->get('id')); // yay... $u->set('last_login', \CoreDateTime::Now('U', \Time::TIMEZONE_GMT)); $u->save(); \Core\Session::SetUser($u); // Allow an external script to override the redirecting URL. $overrideurl = \HookHandler::DispatchHook('/user/postlogin/getredirecturl'); if($overrideurl){ $url = $overrideurl; } return $url; }
public function google($params) { $this->addComponent('menu', new CONTACTIMPORTER_CMP_AdminTabs()); $clientId = OW::getConfig()->getValue('contactimporter', 'google_client_id'); $clientSecret = OW::getConfig()->getValue('contactimporter', 'google_client_secret'); $form = new Form('google_settings'); $element = new TextField('clientId'); $element->setLabel(OW::getLanguage()->text('contactimporter', 'google_client_id')); $element->setRequired(true); $element->setValue($clientId); $form->addElement($element); $element = new TextField('clientSecret'); $element->setLabel(OW::getLanguage()->text('contactimporter', 'google_client_secret')); $element->setRequired(true); $element->setValue($clientSecret); $form->addElement($element); $element = new Submit('save'); $element->setValue(OW::getLanguage()->text('contactimporter', 'save_btn_label')); $form->addElement($element); if (OW::getRequest()->isPost() && $form->isValid($_POST)) { OW::getConfig()->saveConfig('contactimporter', 'google_client_id', trim($form->getElement('clientId')->getValue())); OW::getConfig()->saveConfig('contactimporter', 'google_client_secret', trim($form->getElement('clientSecret')->getValue())); OW::getFeedback()->info(OW::getLanguage()->text('contactimporter', 'admin_settings_updated')); $this->redirect(); } $this->addForm($form); $manualUrl = 'http://docs.oxwall.org/plugin-tuts:contact-importer#google'; if (defined('OW_PLUGIN_XP')) { $manualUrl = 'http://docs.wall.fm/faq:site_configuration:contact_importer_setup#google_application_configuration'; } $this->assign('manualUrl', $manualUrl); }
/** * Update an existing blog page */ public function update() { if (!$this->setAccess('p:/blog/manage_all')) { return View::ERROR_ACCESSDENIED; } $view = $this->getView(); $request = $this->getPageRequest(); $blog = new BlogModel($request->getParameter(0)); if (!$blog->exists()) { return View::ERROR_NOTFOUND; } $form = new Form(); $form->set('callsmethod', 'BlogHelper::BlogFormHandler'); $form->addModel($blog->getLink('Page'), 'page'); $form->addModel($blog, 'model'); $form->addElement('submit', array('value' => 'Update')); // Some elements of the form need to be readonly. $form->getElement('model[type]')->set('disabled', true); $view->addBreadcrumb($blog->get('title'), $blog->get('rewriteurl')); $view->mastertemplate = 'admin'; $view->title = 'Update Blog Listing'; $view->assignVariable('form', $form); }
function getElement($short_name, $obligatory = true) { if ($short_name == 'Save') { $this->addSubmit('Save'); } return parent::getElement($short_name, $obligatory); }
/** * Add or edit an existing directory. * * @return int */ public function update() { $view = $this->getView(); $request = $this->getPageRequest(); if (!$this->setAccess('p:/content/manage_all')) { return View::ERROR_ACCESSDENIED; } $info = $this->_resolveInfoFromURL(); if ($info['status'] !== 200) { return $info['status']; } /** @var \Core\Filestore\File $file */ $file = $info['file']; /** @var PageModel $page */ $page = $info['page']; $contents = $file->getContents(); // Convert these contents from markdown to HTML. $processor = new \Core\MarkdownProcessor(); $html = $processor->transform($contents); // Pre-populate this page with information from the rendered markdown document. // If this page exists, then it'll be updated and kept in sync. // Else, it'll still be set with what's in the document and kept in sync. $page->set('title', $processor->getMeta('title')); $page->set('body', $html); if (!$page->exists()) { $page->set('baseurl', '/markdownbrowser/view' . $info['url']); $page->set('rewriteurl', '/markdownbrowser/view' . $info['url']); $page->set('editurl', '/markdownbrowser/update' . $info['url']); $page->set('component', 'markdown-browser'); $page->set('selectable', 1); $page->set('published', $file->getMTime()); $page->set('updated', $file->getMTime()); $page->set('created', $file->getMTime()); } $form = new Form(); $form->set('callsmethod', 'MarkdownBrowserController::_SaveHandler'); $form->addModel($page, 'page'); // Many of these elements are readonly! $form->getElement('page[title]')->set('readonly', true); $form->removeElement('page[indexable]'); $form->removeElement('page[metas][title]'); $form->removeElement('page[metas][image]'); $form->removeElement('page[metas][author]'); $form->removeElement('page[metas][keywords]'); $form->removeElement('page[metas][description]'); $form->removeElement('page[published_status]'); $form->removeElement('page[published]'); $form->removeElement('page[published_expires]'); // Tack on a submit button $form->addElement('submit', ['value' => $page->exists() ? t('STRING_UPDATE') : t('STRING_REGISTER_PAGE')]); // Give some useful instructions on why everything on this page is disabled! \Core\set_message('t:MESSAGE_TUTORIAL_MARKDOWNBROWSER_REGISTER_UPDATE_PAGE_NOTICE'); $view->templatename = '/pages/markdownbrowser/update.tpl'; //$view->addBreadcrumb('Markdown Directory Listings', '/markdownbrowser'); $view->title = ($page->exists() ? t('STRING_UPDATE') : t('STRING_REGISTER_PAGE')) . ' ' . $info['relative_file']; $view->assignVariable('page', $page); $view->assignVariable('form', $form); }
/** * Save the site password. * * @param Form $form * * @return bool */ public static function SitePasswordSave(Form $form) { $pass = $form->getElement('config[/security/site_password]')->get('value'); \ConfigHandler::Set('/security/site_password', $pass); return true; }
/** * Save handler for the form_metadata page. * * @param Form $form */ public static function FileMetadataSaveHandler(Form $form) { $filename = $form->getElement('file')->get('value'); $file = \Core\Filestore\Factory::File($filename); $helper = new \Core\Filestore\FileMetaHelper($file); // Run through each element and save its metadata to the table. foreach ($form->getElements() as $el) { /** @var $el FormElement */ $name = $el->get('name'); if ($name == 'file') { continue; } if ($name == '___formid') { continue; } if ($name == 'submit') { continue; } $helper->setMeta($name, $el->get('value')); } return true; }
public static function _CreateUpdateHandler(Form $form){ $baseurl = $form->getElement('baseurl')->get('value'); $model = new WidgetModel($baseurl); $model->set('editurl', '/admin/widget/update?baseurl=' . $baseurl); $model->set('deleteurl', '/admin/widget/delete?baseurl=' . $baseurl); $model->set('title', $form->getElement('title')->get('value')); $elements = $form->getElements(); foreach($elements as $el){ /** @var FormElement $el */ if(strpos($el->get('name'), 'setting[') === 0){ $name = substr($el->get('name'), 8, -1); $model->setSetting($name, $el->get('value')); } } $model->save(); return 'back'; }
<?php require_once '../defaults.php'; require_once 'class/LoginUser.class.php'; $formelements = array("username" => array('required' => true, 'label' => 'Username or Email'), "password" => array('required' => true)); $form = new Form($formelements); $status = ""; if (isset($_REQUEST['status'])) { $status = $_REQUEST["status"]; } if ($form->valid()) { // Basic form validation $username = $form->getElement("username"); $unvalue = $username->value; $unmatches = db_get("SELECT 1 FROM login_user WHERE upper(username) = upper('{$unvalue}')", 'column'); $emailmatches = db_get("SELECT 1 FROM login_user WHERE upper(email) = upper('{$unvalue}')", 'column'); if (!empty($unmatches[1])) { $field = 'username'; } else { if (!empty($emailmatches[1])) { $field = 'email'; } else { $form->errors[] = "No user found with username or email <strong>" . $unvalue . "</strong>"; $form->valid = false; } } if (isset($field)) { $userrow = db_get("SELECT * FROM login_user WHERE upper({$field}) = upper('{$unvalue}')", 'row'); $passhashvalue = $userrow[0]['PASS']; $bcrypt = new Bcrypt(15); $isGood = $bcrypt->verify($_REQUEST['password'], $passhashvalue);
public function __construct($entityType, $entityId, $displayType, $pluginKey, $ownerId, $commentCountOnPage, $id, $cmpContextId, $formName) { parent::__construct(); $language = OW::getLanguage(); //comment form init $form = new Form($formName); $textArea = new Textarea('commentText'); $form->addElement($textArea); $entityTypeField = new HiddenField('entityType'); $form->addElement($entityTypeField); $entityIdField = new HiddenField('entityId'); $form->addElement($entityIdField); $displayTypeField = new HiddenField('displayType'); $form->addElement($displayTypeField); $pluginKeyField = new HiddenField('pluginKey'); $form->addElement($pluginKeyField); $ownerIdField = new HiddenField('ownerId'); $form->addElement($ownerIdField); $attch = new HiddenField('attch'); $form->addElement($attch); $cid = new HiddenField('cid'); $form->addElement($cid); $commentsOnPageField = new HiddenField('commentCountOnPage'); $form->addElement($commentsOnPageField); $submit = new Submit('comment-submit'); $submit->setValue($language->text('base', 'comment_add_submit_label')); $form->addElement($submit); $form->getElement('entityType')->setValue($entityType); $form->getElement('entityId')->setValue($entityId); $form->getElement('displayType')->setValue($displayType); $form->getElement('pluginKey')->setValue($pluginKey); $form->getElement('ownerId')->setValue($ownerId); $form->getElement('commentCountOnPage')->setValue($commentCountOnPage); $form->setAjax(true); $form->setAction(OW::getRouter()->urlFor('BASE_CTRL_Comments', 'addComment')); $form->bindJsFunction(Form::BIND_SUBMIT, "function(){ \$('#comments-" . $id . " .comments-preloader').show();}"); $form->bindJsFunction(Form::BIND_SUCCESS, "function(){ \$('#comments-" . $id . " .comments-preloader').hide();}"); $this->addForm($form); $attachmentsId = null; if (BOL_TextFormatService::getInstance()->isCommentsRichMediaAllowed()) { $attachmentsId = $this->initAttachments(); $attControlUniq = uniqid('attpControl'); $js = UTIL_JsGenerator::newInstance()->newObject(array('ATTP.CORE.ObjectRegistry', $attControlUniq), 'ATTP.AttachmentsControl', array($cmpContextId, array('attachmentId' => $attachmentsId, 'attachmentInputId' => $attch->getId(), 'inputId' => $textArea->getId(), 'formName' => $form->getName()))); ATTACHMENTS_Plugin::getInstance()->addJs($js); } OW::getDocument()->addOnloadScript("owCommentCmps['{$id}'].initForm('" . $form->getElement('commentText')->getId() . "', '" . $form->getElement('attch')->getId() . "');"); OW::getDocument()->addOnloadScript(UTIL_JsGenerator::composeJsString(' owForms[{$formName}].bind("success", function(data) { var attachId = {$attcachmentId}; if ( attachId && ATTP.CORE.ObjectRegistry[attachId] ) { ATTP.CORE.ObjectRegistry[attachId].reset(); } }); ', array('formName' => $form->getName(), 'attcachmentId' => $attachmentsId))); $this->assign('form', true); $this->assign('id', $id); if (OW::getUser()->isAuthenticated()) { $currentUserInfo = BOL_AvatarService::getInstance()->getDataForUserAvatars(array(OW::getUser()->getId())); $this->assign('currentUserInfo', $currentUserInfo[OW::getUser()->getId()]); } }
/** * Handler to actually perform the import. * * @param \Form $form * @return bool */ public static function FormHandler2(\Form $form) { $filename = Session::Get('user-import/file'); $file = Factory::File($filename); /** @var $contents \Core\Filestore\Contents\ContentCSV */ $contents = $file->getContentsObject(); // If the user checked that it has a header... do that. $contents->_hasheader = $form->getElement('has_header')->get('checked'); // Merge $merge = $form->getElement('merge_duplicates')->get('checked'); // Handle the map-to directives. $maptos = array(); foreach($form->getElements() as $el){ if(strpos($el->get('name'), 'mapto[') === 0 && $el->get('value')){ $k = substr($el->get('name'), 6, -1); $maptos[$k] = $el->get('value'); } } // Handle the group mappings $groups = $form->getElement('groups[]')->get('value'); // And keep a log of the bad transfers and some other data. $counts = ['created' => 0, 'updated' => 0, 'failed' => 0, 'skipped' => 0]; Session::Set('user-import/fails', []); $incoming = $contents->parse(); foreach($incoming as $record){ try{ // Create a data map of this record for fields to actually map over. $dat = array(); foreach($maptos as $recordkey => $userkey){ $dat[$userkey] = $record[$recordkey]; } // No email, NO IMPORT! if(!$dat['email']){ $counts['skipped']++; continue; } // Try to find this record by email, since that's a primary key. $existing = \UserModel::Find(['email = ' . $dat['email'] ], 1); if($existing && !$merge){ // Skip existing records. $counts['skipped']++; } elseif($existing){ // Update! $existing->setFromArray($dat); $existing->setGroups($groups); if($existing->save()){ $counts['updated']++; } else{ $counts['skipped']++; } } else{ $new = new \UserModel(); $new->setFromArray($dat); $new->setGroups($groups); $new->save(); $counts['created']++; } } catch(\Exception $e){ // @todo Handle this die($e->getMessage()); } // } Session::Set('user-import/counts', $counts); return true; }
public static function _SaveEditorHandler(Form $form) { $newmodel = $form->getModel(); $file = $form->getElement('file')->get('value'); $activefile = $form->getElement('filetype')->get('value'); // The inbound file types depends on how to read the file. switch ($activefile) { case 'template': $filename = \Core\Templates\Template::ResolveFile($file); $customfilename = ROOT_PDIR . 'themes/custom/' . $file; break; case 'file': $filename = $file; // It'll get transposed. $customfilename = ROOT_PDIR . 'themes/custom/' . $file; break; default: \Core\set_message('Unsupported file type: ' . $activefile, 'error'); return false; } $customfh = \Core\Filestore\Factory::File($customfilename); if ($customfh->exists()) { // If the custom one exists... this will be the source file too! $sourcefh = $customfh; } else { $sourcefh = \Core\Filestore\Factory::File($filename); } // Check and see if they're the same, ie: no change. I don't want to create a bunch of moot revisions. if ($newmodel->get('content') == $sourcefh->getContents()) { \Core\set_message('No changes performed.', 'info'); return '/theme'; } // Before I overwrite this file, check and see if the original has been snapshot first! $c = ThemeTemplateChangeModel::Count(['filename = ' . $file]); if (!$c) { $original = new ThemeTemplateChangeModel(); $original->setFromArray(['comment' => 'Original File', 'filename' => $file, 'content' => $sourcefh->getContents(), 'content_md5' => $sourcefh->getHash(), 'updated' => $sourcefh->getMTime()]); $original->save(); } // All destination files get written to the custom directory! $customfh->putContents($newmodel->get('content')); $hash = $customfh->getHash(); /* // What happens now is based on the type of the inbound file. switch($activefile){ case 'skin': // Just replace the contents of that file. $fh->putContents($newmodel->get('content')); $hash = $fh->getHash(); break; case 'template': // This gets written into the current theme directory. $themefh = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/' . ConfigHandler::Get('/theme/selected') . '/' . $file); $themefh->putContents($newmodel->get('content')); $hash = $themefh->getHash(); break; case 'style': case 'file': // This gets written into the current theme directory. $themefh = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/' . ConfigHandler::Get('/theme/selected') . '/' . $file); $themefh->putContents($newmodel->get('content')); $hash = $themefh->getHash(); // This is required to get assets updated to the CDN correctly. $theme = ThemeHandler::GetTheme(); $hash = $themefh->getHash(); $theme->addAssetFile(array('file' => $file, 'md5' => $hash)); $theme->save(); $theme->reinstall(); default: } */ // Make a record of this change too! $change = new ThemeTemplateChangeModel(); $change->setFromArray(['comment' => $newmodel->get('comment'), 'filename' => $file, 'content' => $newmodel->get('content'), 'content_md5' => $hash]); $change->save(); if ($activefile == 'file') { // Reinstall all assets too! foreach (Core::GetComponents() as $component) { $component->reinstall(); } // And the current theme. ThemeHandler::GetTheme(ConfigHandler::Get('/theme/selected'))->reinstall(); } \Core\set_message('Updated file successfully', 'success'); return '/theme'; }
public static function _i18nSaveHandler(Form $form) { // NEW IDEA! // Instead of setting the override for keys, (possibly useful, just somewhere else)... // Set the enabled languages for this site. // This allows site administrators to NOT have every language under the sun appear if they're running SuSE. $selected = $form->getElement('languages[]')->get('value'); // Implode them into a single string. $enabled = implode('|', $selected); // Strip out any invalid character. $enabled = preg_replace('/[^a-zA-Z_|]/', '', $enabled); // And save! ConfigHandler::Set('/core/language/languages_enabled', $enabled); return true; // Create a custom ini for just these options. // This will allow the site admin to change a string without worrying about it getting overridden from an update. $lang = $form->getElementValue('lang'); $ini = "[$lang]\n; Custom locale strings set by the site manager!\n\n"; foreach($form->getElements() as $el){ /** @var FormElement $el */ $name = $el->get('name'); $val = $el->get('value'); if(strpos($name, 'MESSAGE') === 0 || strpos($name, 'FORMAT') === 0 || strpos($name, 'STRING') === 0){ $ini .= $name . ' = "' . str_replace('"', '\\"', $val) . '";' . "\n"; } } // Save this ini out to a custom i18n file. $fileout = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/custom/i18n/' . $lang . '.ini'); $fileout->putContents($ini); \Core\set_message('t:MESSAGE_SUCCESS_UPDATED_TRANSLATION_STRINGS'); return true; }
/** * Populate this user object from a form * * @param Form $form * @param null $prefix * * @return bool * @throws ModelValidationException */ public function setFromForm(Form $form, $prefix = null) { foreach($form->getElements() as $el) { /** @var $el FormElement */ $name = $el->get('name'); $value = $el->get('value'); // If a prefix was requested and it doesn't match, skip this element. if($prefix && strpos($name, $prefix . '[') !== 0){ continue; } // Otherwise if there is a prefix, trim it off from the name. if($prefix) { // Some of the options may be nested arrays, they'll need to be treated differently since the format is different, // prefix[option][phone] vs prefix[email] if(strpos($name, '][')) { $name = str_replace('][', '[', substr($name, strlen($prefix) + 1)); } else { $name = substr($name, strlen($prefix) + 1, -1); } } if($name == 'groups[]') { $this->setGroups($value); } elseif($name == 'contextgroup[]') { // This is a two-part system with data pulling from contextgroup and contextgroupcontext. $gids = $value; $contextpks = $form->getElement('contextgroupcontext[]')->get('value'); $groups = []; foreach($gids as $key => $gid) { // Skip blank group selections. if(!$gid) continue; // Pull the group information for this gid since that will contain the context. $group = UserGroupModel::Construct($gid); $context = $group->get('context'); $contextpk = $contextpks[ $key ]; $groups[] = [ 'group_id' => $gid, 'context' => $context, 'context_pk' => $contextpk, ]; } $this->setContextGroups($groups); } elseif($name == 'active'){ $current = $this->get('active'); // The incoming value will probably be 'on' or NULL. // This is because the form displays as a BOOL even though the backend field is an ENUM. $new = ($value) ? '1' : '0'; // -1 => 0 = -1 (Disabled to unchecked, no change) // -1 => 1 = 1 (Disabled to checked, activate) // 0 => 0 = 0 (New to unchecked, wot?) // 0 => 1 = 1 (New to checked, activate... still shouldn't happen though) // 1 => 0 = -1 (Enabled to unchecked, disable) // 1 => 1 = 1 (Enabled to checked, no change) if($current == '1' && $new == '0'){ // User was set from active to inactive. // Instead of setting to a new account, set to deactivated. $this->set('active', '-1'); } elseif($current == '-1' && $new == '0'){ // No change! } else{ // Otherwise, allow the change to go through. $this->set('active', $new); } } elseif($name != 'user'){ // Skip the user record, // otherwise Default behaviour $this->set($name, $value); } } // foreach(elements) }