/** * Find available social plugins. * * @return array|mixed * @throws Exception */ protected function getConnections() { $this->fireEvent('GetConnections'); $connections = []; $addons = Gdn::addonManager()->lookupAllByType(\Vanilla\Addon::TYPE_ADDON); foreach ($addons as $addonName => $addon) { $addonInfo = $addon->getInfo(); // Limit to designated social addons. if (!array_key_exists('socialConnect', $addonInfo)) { continue; } // See if addon is enabled. $isEnabled = Gdn::addonManager()->isEnabled($addonName, \Vanilla\Addon::TYPE_ADDON); setValue('enabled', $addonInfo, $isEnabled); // See if we can detect whether connection is configured. $isConfigured = null; if ($isEnabled) { $pluginInstance = Gdn::pluginManager()->getPluginInstance($addonName, Gdn_PluginManager::ACCESS_PLUGINNAME); if (method_exists($pluginInstance, 'isConfigured')) { $isConfigured = $pluginInstance->isConfigured(); } } setValue('configured', $addonInfo, $isConfigured); // Add the connection. $connections[$addonName] = $addonInfo; } return $connections; }
/** * Callback function that sets values that expire and are refreshed by Connection. * * @param \Picqer\Financials\Exact\Connection $connection */ function tokenUpdateCallback(\Picqer\Financials\Exact\Connection $connection) { // Save the new tokens for next connections setValue('accesstoken', $connection->getAccessToken()); setValue('refreshtoken', $connection->getRefreshToken()); // Save expires time for next connections setValue('expires_in', $connection->getTokenExpires()); }
function parseXMLGetValues($path, $fields) { $sites = simplexml_load_file($path); foreach ($sites as $key => $value) { $fields = setValue($key, $value, $fields); } return $fields; }
function displayForm($camposPendientes) { if ($camposPendientes) { $error = '<p class="error">Hubo algunos problemas con el formulario que usted presentó. Por favor, complete correctamente los campos remarcados de abajo y haga clic en Enviar para volver a enviar el formulario.</p>'; } else { $error = '<p>por favor, rellene sus datos a continuación y haga clic en Enviar. Los campos marcados con un asterisco (*) son obligatorios.</p>'; } $datos = array("error" => $error, "scriptUrl" => "index.php", "validacionNombre" => validateField("nombre", $camposPendientes), "valorNombre" => setValue("nombre"), "valorComentario" => setValue("comentario"), "validacionClave" => validateField("clave", $camposPendientes), "valorClave" => setValue("clave"), "precio" => array("mas 14k" => setSelectedParaUno("precio", "mas 14k"), "14k" => setSelectedParaUno("precio", "14k"), "menos 14k" => setSelectedParaUno("precio", "menos 14k")), "color" => array("rojo" => setChecked1("color", "rojo"), "verde" => setChecked1("color", "verde"), "azul" => setChecked1("color", "azul")), "extras" => array("aireAcondicionado" => setChecked2("extras", "aireAcondicionado"), "Yantas" => setChecked2("extras", "Yantas"), "Tapiceria" => setChecked2("extras", "Tapiceria"))); $plantilla = "plantillas/encuestaForm.html"; $formulario = vista($datos, $plantilla); $datos = array("titulo" => TITULO, "formulario" => $formulario); $plantilla = "plantillas/plantilla.html"; $html = vista($datos, $plantilla); print $html; }
function displayForm($camposPendientes) { if ($camposPendientes) { $error = '<p class="error">Hubo algunos problemas con el formulario que usted presentó. Por favor, complete correctamente los campos remarcados de abajo y haga clic en Enviar para volver a enviar el formulario.</p>'; } else { $error = '<p>por favor, rellene sus datos a continuación y haga clic en Enviar. Los campos marcados con un asterisco (*) son obligatorios.</p>'; } $resultados = array("error" => $error, "scriptUrl" => "index.php", "validacionNombreUsuario" => validateField("nombreUsuario", $camposPendientes), "valorNombreUsuario" => setValue("nombreUsuario"), "validacionApellidos" => validateField("apellidos", $camposPendientes), "valorApellidos" => setValue("apellidos"), "tipoMusicaRock" => setSelected("tipoMusica", "Rock"), "tipoMusicaPop" => setSelected("tipoMusica", "Pop"), "tipoMusicaRegee" => setSelected("tipoMusica", "Regee"), "tipoMusicaClasica" => setSelected("tipoMusica", "Clasica"), "tipoLibrosNovelaNegra" => setChecked("tipoLibros", "Novela Negra"), "tipoLibrosCienciaFiccion" => setChecked("tipoLibros", "Ciencia Ficcion"), "tipoLibrosFantasia" => setChecked("tipoLibros", "Fantasia")); $plantilla = "plantillas/encuestaForm.html"; $formulario = vista($resultados, $plantilla); $datos = array("titulo" => TITULO, "formulario" => $formulario); $plantilla = "plantillas/plantilla.html"; $html = vista($datos, $plantilla); print $html; }
function displayForm1($camposPendientes = array(), $camposErroneos = array(), $mensajeErrorImagen = "correcto") { if ($camposPendientes || $camposErroneos || $mensajeErrorImagen != "correcto") { $error = '<p class="error1">Hubo algunos problemas con el formulario que usted presentó. Por favor, complete correctamente los campos remarcados de abajo y haga clic en Enviar para volver a enviar el formulario.</p>'; } else { $error = '<p>por favor, rellene sus datos a continuación y haga clic en Enviar. Los campos marcados con un asterisco (*) son obligatorios.</p>'; } if (count($camposPendientes) > 0) { $error .= "<p class='error2'>Faltan por rellenar campos en el formulario:"; foreach ($camposPendientes as $campo) { $error .= $campo . ", "; } $error = preg_replace("/, \$/", "", $error); $error .= "</p>"; } if (count($camposErroneos) > 0) { $error .= "<p class='error1'>Hay campos mal rellenados en el formulario:"; foreach ($camposErroneos as $campo) { $error .= $campo . ", "; } $error = preg_replace("/, \$/", "", $error); $error .= "</p>"; } if ($mensajeErrorImagen != "correcto") { $error .= "<p class='error3'>{$mensajeErrorImagen}</p>"; } $ciudades = array("Roma", "Paris", "Nueva York", "Londres", "Berlin", "Atenas"); $medios = array("correoPostal", "email"); $ocultosCiudades = ""; foreach ($ciudades as $ciudad) { $ocultosCiudades .= '<input type="hidden" name="ciudades[]" value="' . setValue("ciudades", $ciudad) . "\"/>\n"; } $ocultosMedios = ""; foreach ($medios as $medio) { $ocultosMedios .= '<input type="hidden" name="medios[]" value="' . setValue("medios", $medio) . "\"/>\n"; } $datos = array("error" => $error, "scriptUrl" => "index.php", "ocultosCiudades" => $ocultosCiudades, "ocultosMedios" => $ocultosMedios, "validacionNombre" => validateField("nombre", $camposPendientes, $camposErroneos), "valorNombre" => setValue("nombre"), "validacionApellidos" => validateField("apellidos", $camposPendientes, $camposErroneos), "valorApellidos" => setValue("apellidos"), "validacionDireccion" => validateField("direccion", $camposPendientes, $camposErroneos), "valorDireccion" => setValue("direccion"), "validacionTelefono" => validateField("telefono", $camposPendientes, $camposErroneos), "valorTelefono" => setValue("telefono"), "validacionEmail" => validateField("email", $camposPendientes, $camposErroneos), "valorEmail" => setValue("email"), "validacionFoto" => validateField("foto1", $camposPendientes, $camposErroneos, $mensajeErrorImagen)); $plantilla = "plantillas/formulario.html"; $formulario = vista($datos, $plantilla); $datos = array("titulo" => TITULO, "formulario" => $formulario); $plantilla = "plantillas/plantilla.html"; $html = vista($datos, $plantilla); print $html; }
/** * Build the Message's Location property and add it. * * @param array|object $Message Message data. * @return array|object Message data with Location property/key added. */ public function defineLocation($Message) { $Controller = val('Controller', $Message); $Application = val('Application', $Message); $Method = val('Method', $Message); if (in_array($Controller, $this->_SpecialLocations)) { setValue('Location', $Message, $Controller); } else { setValue('Location', $Message, $Application); if (!stringIsNullOrEmpty($Controller)) { setValue('Location', $Message, val('Location', $Message) . '/' . $Controller); } if (!stringIsNullOrEmpty($Method)) { setValue('Location', $Message, val('Location', $Message) . '/' . $Method); } } return $Message; }
/** * Function to connect to Moneybird, this creates the client and automatically retrieves oAuth tokens if needed * * @return \Picqer\Financials\Moneybird\Connection * @throws Exception */ function connect($redirectUrl, $clientId, $clientSecret) { $connection = new \Picqer\Financials\Moneybird\Connection(); $connection->setRedirectUrl($redirectUrl); $connection->setClientId($clientId); $connection->setClientSecret($clientSecret); // Retrieves authorizationcode from database if (getValue('authorizationcode')) { $connection->setAuthorizationCode(getValue('authorizationcode')); } // Retrieves accesstoken from database if (getValue('accesstoken')) { $connection->setAccessToken(getValue('accesstoken')); } // Make the client connect and exchange tokens try { $connection->connect(); } catch (\Exception $e) { throw new Exception('Could not connect to Moneybird: ' . $e->getMessage()); } // Save the new tokens for next connections setValue('accesstoken', $connection->getAccessToken()); return $connection; }
/** * * * @param $sender controller instance. * @param int|string $discussionID Identifier of the discussion. * * @throws notFoundException */ protected function _discussionOptions($sender, $discussionID) { $sender->Form = new Gdn_Form(); $Discussion = $sender->DiscussionModel->getID($discussionID); if (!$Discussion) { throw notFoundException('Discussion'); } $sender->permission('Vanilla.Discussions.Edit', true, 'Category', val('PermissionCategoryID', $Discussion)); // Both '' and 'Discussion' denote a discussion type of discussion. if (!val('Type', $Discussion)) { setValue('Type', $Discussion, 'Discussion'); } if ($sender->Form->isPostBack()) { $sender->DiscussionModel->setField($discussionID, 'Type', $sender->Form->getFormValue('Type')); // Update the QnA field. Default to "Unanswered" for questions. Null the field for other types. $qna = val('QnA', $Discussion); switch ($sender->Form->getFormValue('Type')) { case 'Question': $sender->DiscussionModel->setField($discussionID, 'QnA', $qna ? $qna : 'Unanswered'); break; default: $sender->DiscussionModel->setField($discussionID, 'QnA', null); } // $Form = new Gdn_Form(); $sender->Form->setValidationResults($sender->DiscussionModel->validationResults()); // if ($sender->DeliveryType() == DELIVERY_TYPE_ALL || $Redirect) // $sender->RedirectUrl = Gdn::Controller()->Request->PathAndQuery(); Gdn::controller()->jsonTarget('', '', 'Refresh'); } else { $sender->Form->setData($Discussion); } $sender->setData('Discussion', $Discussion); $sender->setData('_Types', array('Question' => '@' . t('Question Type', 'Question'), 'Discussion' => '@' . t('Discussion Type', 'Discussion'))); $sender->setData('Title', t('Q&A Options')); $sender->render('DiscussionOptions', '', 'plugins/QnA'); }
<?php if (isset($errors['username'])) { echo $errors['username']; } ?> </span> </div> </div> <!-- Password --> <div class="row"> <div class="label"> <label for="password">Password</label> <div class="control"> <input type="password" id="password" name="password" value="<?php setValue($formdata, 'password'); ?> "/> </div> <div class="errors"> <span id="passwordError"> <?php if (isset($errors['password'])) { echo $errors['password']; } ?> </span> </div> </div> <!--Date of Birth-->
/** * Inserts or updates the discussion via form values. * * Events: BeforeSaveDiscussion, AfterSaveDiscussion. * * @since 2.0.0 * @access public * * @param array $FormPostValues Data sent from the form model. * @param array $Settings Currently unused. * @return int $DiscussionID Unique ID of the discussion. */ public function save($FormPostValues, $Settings = false) { $Session = Gdn::session(); // Define the primary key in this model's table. $this->defineSchema(); // Add & apply any extra validation rules: $this->Validation->applyRule('Body', 'Required'); $this->Validation->addRule('MeAction', 'function:ValidateMeAction'); $this->Validation->applyRule('Body', 'MeAction'); $MaxCommentLength = Gdn::config('Vanilla.Comment.MaxLength'); if (is_numeric($MaxCommentLength) && $MaxCommentLength > 0) { $this->Validation->SetSchemaProperty('Body', 'Length', $MaxCommentLength); $this->Validation->applyRule('Body', 'Length'); } // Validate category permissions. $CategoryID = val('CategoryID', $FormPostValues); if ($CategoryID > 0) { $Category = CategoryModel::categories($CategoryID); if ($Category && !$Session->checkPermission('Vanilla.Discussions.Add', true, 'Category', val('PermissionCategoryID', $Category))) { $this->Validation->addValidationResult('CategoryID', 'You do not have permission to post in this category'); } } // Get the DiscussionID from the form so we know if we are inserting or updating. $DiscussionID = val('DiscussionID', $FormPostValues, ''); // See if there is a source ID. if (val('SourceID', $FormPostValues)) { $DiscussionID = $this->SQL->getWhere('Discussion', arrayTranslate($FormPostValues, array('Source', 'SourceID')))->value('DiscussionID'); if ($DiscussionID) { $FormPostValues['DiscussionID'] = $DiscussionID; } } elseif (val('ForeignID', $FormPostValues)) { $DiscussionID = $this->SQL->getWhere('Discussion', array('ForeignID' => $FormPostValues['ForeignID']))->value('DiscussionID'); if ($DiscussionID) { $FormPostValues['DiscussionID'] = $DiscussionID; } } $Insert = $DiscussionID == '' ? true : false; $this->EventArguments['Insert'] = $Insert; if ($Insert) { unset($FormPostValues['DiscussionID']); // If no categoryid is defined, grab the first available. if (!val('CategoryID', $FormPostValues) && !c('Vanilla.Categories.Use')) { $FormPostValues['CategoryID'] = val('CategoryID', CategoryModel::defaultCategory(), -1); } $this->addInsertFields($FormPostValues); // The UpdateUserID used to be required. Just add it if it still is. if (!$this->Schema->getProperty('UpdateUserID', 'AllowNull', true)) { $FormPostValues['UpdateUserID'] = $FormPostValues['InsertUserID']; } // $FormPostValues['LastCommentUserID'] = $Session->UserID; $FormPostValues['DateLastComment'] = $FormPostValues['DateInserted']; } else { // Add the update fields. $this->addUpdateFields($FormPostValues); } // Set checkbox values to zero if they were unchecked if (val('Announce', $FormPostValues, '') === false) { $FormPostValues['Announce'] = 0; } if (val('Closed', $FormPostValues, '') === false) { $FormPostValues['Closed'] = 0; } if (val('Sink', $FormPostValues, '') === false) { $FormPostValues['Sink'] = 0; } // Prep and fire event $this->EventArguments['FormPostValues'] =& $FormPostValues; $this->EventArguments['DiscussionID'] = $DiscussionID; $this->fireEvent('BeforeSaveDiscussion'); // Validate the form posted values $this->validate($FormPostValues, $Insert); $ValidationResults = $this->validationResults(); // If the body is not required, remove it's validation errors. $BodyRequired = c('Vanilla.DiscussionBody.Required', true); if (!$BodyRequired && array_key_exists('Body', $ValidationResults)) { unset($ValidationResults['Body']); } if (count($ValidationResults) == 0) { // If the post is new and it validates, make sure the user isn't spamming if (!$Insert || !$this->checkForSpam('Discussion')) { // Get all fields on the form that relate to the schema $Fields = $this->Validation->schemaValidationFields(); // Check for spam. $spam = SpamModel::isSpam('Discussion', $Fields); if ($spam) { return SPAM; } // Get DiscussionID if one was sent $DiscussionID = intval(val('DiscussionID', $Fields, 0)); // Remove the primary key from the fields for saving. unset($Fields['DiscussionID']); $StoredCategoryID = false; if ($DiscussionID > 0) { // Updating $Stored = $this->getID($DiscussionID, DATASET_TYPE_OBJECT); // Block Format change if we're forcing the formatter. if (c('Garden.ForceInputFormatter')) { unset($Fields['Format']); } // Clear the cache if necessary. $CacheKeys = array(); if (val('Announce', $Stored) != val('Announce', $Fields)) { $CacheKeys[] = $this->getAnnouncementCacheKey(); $CacheKeys[] = $this->getAnnouncementCacheKey(val('CategoryID', $Stored)); } if (val('CategoryID', $Stored) != val('CategoryID', $Fields)) { $CacheKeys[] = $this->getAnnouncementCacheKey(val('CategoryID', $Fields)); } foreach ($CacheKeys as $CacheKey) { Gdn::cache()->remove($CacheKey); } self::serializeRow($Fields); $this->SQL->put($this->Name, $Fields, array($this->PrimaryKey => $DiscussionID)); setValue('DiscussionID', $Fields, $DiscussionID); LogModel::logChange('Edit', 'Discussion', (array) $Fields, $Stored); if (val('CategoryID', $Stored) != val('CategoryID', $Fields)) { $StoredCategoryID = val('CategoryID', $Stored); } } else { // Inserting. if (!val('Format', $Fields) || c('Garden.ForceInputFormatter')) { $Fields['Format'] = c('Garden.InputFormatter', ''); } if (c('Vanilla.QueueNotifications')) { $Fields['Notified'] = ActivityModel::SENT_PENDING; } // Check for approval $ApprovalRequired = checkRestriction('Vanilla.Approval.Require'); if ($ApprovalRequired && !val('Verified', Gdn::session()->User)) { LogModel::insert('Pending', 'Discussion', $Fields); return UNAPPROVED; } // Create discussion $this->serializeRow($Fields); $DiscussionID = $this->SQL->insert($this->Name, $Fields); $Fields['DiscussionID'] = $DiscussionID; // Update the cache. if ($DiscussionID && Gdn::cache()->activeEnabled()) { $CategoryCache = array('LastDiscussionID' => $DiscussionID, 'LastCommentID' => null, 'LastTitle' => Gdn_Format::text($Fields['Name']), 'LastUserID' => $Fields['InsertUserID'], 'LastDateInserted' => $Fields['DateInserted'], 'LastUrl' => DiscussionUrl($Fields)); CategoryModel::setCache($Fields['CategoryID'], $CategoryCache); // Clear the cache if necessary. if (val('Announce', $Fields)) { Gdn::cache()->remove($this->getAnnouncementCacheKey(val('CategoryID', $Fields))); if (val('Announce', $Fields) == 1) { Gdn::cache()->remove($this->getAnnouncementCacheKey()); } } } // Update the user's discussion count. $InsertUser = Gdn::userModel()->getID($Fields['InsertUserID']); $this->updateUserDiscussionCount($Fields['InsertUserID'], val('CountDiscussions', $InsertUser, 0) > 100); // Mark the user as participated. $this->SQL->replace('UserDiscussion', array('Participated' => 1), array('DiscussionID' => $DiscussionID, 'UserID' => val('InsertUserID', $Fields))); // Assign the new DiscussionID to the comment before saving. $FormPostValues['IsNewDiscussion'] = true; $FormPostValues['DiscussionID'] = $DiscussionID; // Do data prep. $DiscussionName = val('Name', $Fields, ''); $Story = val('Body', $Fields, ''); $NotifiedUsers = array(); $UserModel = Gdn::userModel(); $ActivityModel = new ActivityModel(); if (val('Type', $FormPostValues)) { $Code = 'HeadlineFormat.Discussion.' . $FormPostValues['Type']; } else { $Code = 'HeadlineFormat.Discussion'; } $HeadlineFormat = t($Code, '{ActivityUserID,user} started a new discussion: <a href="{Url,html}">{Data.Name,text}</a>'); $Category = CategoryModel::categories(val('CategoryID', $Fields)); $Activity = array('ActivityType' => 'Discussion', 'ActivityUserID' => $Fields['InsertUserID'], 'HeadlineFormat' => $HeadlineFormat, 'RecordType' => 'Discussion', 'RecordID' => $DiscussionID, 'Route' => DiscussionUrl($Fields), 'Data' => array('Name' => $DiscussionName, 'Category' => val('Name', $Category))); // Allow simple fulltext notifications if (c('Vanilla.Activity.ShowDiscussionBody', false)) { $Activity['Story'] = $Story; } // Notify all of the users that were mentioned in the discussion. $Usernames = getMentions($DiscussionName . ' ' . $Story); // Use our generic Activity for events, not mentions $this->EventArguments['Activity'] = $Activity; // Notify everyone that has advanced notifications. if (!c('Vanilla.QueueNotifications')) { try { $Fields['DiscussionID'] = $DiscussionID; $this->notifyNewDiscussion($Fields, $ActivityModel, $Activity); } catch (Exception $Ex) { throw $Ex; } } // Notifications for mentions foreach ($Usernames as $Username) { $User = $UserModel->getByUsername($Username); if (!$User) { continue; } // Check user can still see the discussion. if (!$this->canView($Fields, $User->UserID)) { continue; } $Activity['HeadlineFormat'] = t('HeadlineFormat.Mention', '{ActivityUserID,user} mentioned you in <a href="{Url,html}">{Data.Name,text}</a>'); $Activity['NotifyUserID'] = val('UserID', $User); $ActivityModel->queue($Activity, 'Mention'); } // Throw an event for users to add their own events. $this->EventArguments['Discussion'] = $Fields; $this->EventArguments['NotifiedUsers'] = $NotifiedUsers; $this->EventArguments['MentionedUsers'] = $Usernames; $this->EventArguments['ActivityModel'] = $ActivityModel; $this->fireEvent('BeforeNotification'); // Send all notifications. $ActivityModel->saveQueue(); } // Get CategoryID of this discussion $Discussion = $this->getID($DiscussionID, DATASET_TYPE_OBJECT); $CategoryID = val('CategoryID', $Discussion, false); // Update discussion counter for affected categories. if ($Insert || $StoredCategoryID) { $this->incrementNewDiscussion($Discussion); } if ($StoredCategoryID) { $this->updateDiscussionCount($StoredCategoryID); } // Fire an event that the discussion was saved. $this->EventArguments['FormPostValues'] = $FormPostValues; $this->EventArguments['Fields'] = $Fields; $this->EventArguments['DiscussionID'] = $DiscussionID; $this->fireEvent('AfterSaveDiscussion'); } } return $DiscussionID; }
/** * Set fields that need additional manipulation after retrieval. * * @param array|object &$User * @throws Exception */ public function setCalculatedFields(&$User) { if ($v = val('Attributes', $User)) { if (is_string($v)) { setValue('Attributes', $User, dbdecode($v)); } } if ($v = val('Permissions', $User)) { if (is_string($v)) { setValue('Permissions', $User, dbdecode($v)); } } if ($v = val('Preferences', $User)) { if (is_string($v)) { setValue('Preferences', $User, dbdecode($v)); } } if ($v = val('Photo', $User)) { if (!isUrl($v)) { $PhotoUrl = Gdn_Upload::url(changeBasename($v, 'n%s')); } else { $PhotoUrl = $v; } setValue('PhotoUrl', $User, $PhotoUrl); } // We store IPs in the UserIP table. To avoid unnecessary queries, the full list is not built here. Shim for BC. setValue('AllIPAddresses', $User, [val('InsertIPAddress', $User), val('LastIPAddress', $User)]); setValue('_CssClass', $User, ''); if (val('Banned', $User)) { setValue('_CssClass', $User, 'Banned'); } $this->EventArguments['User'] =& $User; $this->fireEvent('SetCalculatedFields'); }
/** * Set fields that need additional manipulation after retrieval. * * @param $User * @throws Exception */ public function setCalculatedFields(&$User) { if ($v = val('Attributes', $User)) { if (is_string($v)) { setValue('Attributes', $User, @unserialize($v)); } } if ($v = val('Permissions', $User)) { if (is_string($v)) { setValue('Permissions', $User, @unserialize($v)); } } if ($v = val('Preferences', $User)) { if (is_string($v)) { setValue('Preferences', $User, @unserialize($v)); } } if ($v = val('Photo', $User)) { if (!isUrl($v)) { $PhotoUrl = Gdn_Upload::url(changeBasename($v, 'n%s')); } else { $PhotoUrl = $v; } setValue('PhotoUrl', $User, $PhotoUrl); } if ($v = val('AllIPAddresses', $User)) { if (is_string($v)) { $IPAddresses = explode(',', $v); foreach ($IPAddresses as $i => $IPAddress) { $IPAddresses[$i] = ForceIPv4($IPAddress); } setValue('AllIPAddresses', $User, $IPAddresses); } } setValue('_CssClass', $User, ''); if ($v = val('Banned', $User)) { setValue('_CssClass', $User, 'Banned'); } $this->EventArguments['User'] =& $User; $this->fireEvent('SetCalculatedFields'); }
function displayForm($missingFields) { ?> <h1>Membership Form</h1> <?php if ($missingFields) { ?> <p class="error">There were some problems with the form you submitted. Please complete the fields highlighted below and click Send Details to resend the form.</p> <?php } else { ?> <p>Thanks for choosing to join The Widget Club. To register, please fill in your details below and click Send Details. Fields marked with an asterisk (*) are required.</p> <?php } ?> <form action="registration.php" method="post"> <div style="width: 30em;"> <label for="firstName"<?php validateField("firstName", $missingFields); ?> >First name *</label> <input type="text" name="firstName" id="firstName" value="<?php setValue("firstName"); ?> " /> <label for="lastName"<?php validateField("lastName", $missingFields); ?> >Last name *</label> <input type="text" name="lastName" id="lastName" value="<?php setValue("lastName"); ?> " /> <label for="password1"<?php if ($missingFields) { echo ' class="error"'; } ?> >Choose a password *</label> <input type="password" name="password1" id="password1" value="" /> <label for="password2"<?php if ($missingFields) { echo ' class="error"'; } ?> >Retype password *</label> <input type="password" name="password2" id="password2" value="" /> <label<?php validateField("gender", $missingFields); ?> >Your gender: *</label> <label for="genderMale">Male</label> <input type="radio" name="gender" id="genderMale" value="M"<?php setChecked("gender", "M"); ?> /> <label for="genderFemale">Female</label> <input type="radio" name="gender" id="genderFemale" value="F"<?php setChecked("gender", "F"); ?> /> <label for="favoriteWidget">What's your favorite widget? *</label> <select name="favoriteWidget" id="favoriteWidget" size="1"> <option value="superWidget"<?php setSelected("favoriteWidget", "superWidget"); ?> >The SuperWidget</option> <option value="megaWidget"<?php setSelected("favoriteWidget", "megaWidget"); ?> >The MegaWidget</option> <option value="wonderWidget"<?php setSelected("favoriteWidget", "wonderWidget"); ?> >The WonderWidget</option> </select> <label for="newsletter">Do you want to receive our newsletter?</label> <input type="checkbox" name="newsletter" id="newsletter" value="yes"<?php setChecked("newsletter", "yes"); ?> /> <label for="comments">Any comments?</label> <textarea name="comments" id="comments" rows="4" cols="50"><?php setValue("comments"); ?> </textarea> <div style="clear: both;"> <input type="submit" name="submitButton" id="submitButton" value="Send Details" /> <input type="reset" name="resetButton" id="resetButton" value="Reset Form" style="margin-right: 20px;" /> </div> </div> </form> <?php }
/** * Sort list of addons for display. * * @since 2.0.0 * @access public * @param array $Array Addon data (e.g. $PluginInfo). * @param bool $Filter Whether to exclude hidden addons (defaults to TRUE). */ public static function sortAddons(&$Array, $Filter = true) { // Make sure every addon has a name. foreach ($Array as $Key => $Value) { if ($Filter && val('Hidden', $Value)) { unset($Array[$Key]); continue; } $Name = val('Name', $Value, $Key); setValue('Name', $Array[$Key], $Name); } uasort($Array, array('SettingsController', 'CompareAddonName')); }
function displayForm($camposPendientes) { cabecera(); if ($camposPendientes) { ?> <p class="error">Hubo algunos problemas con el formulario que usted presentó. Por favor, complete correctamente los campos remarcados de abajo y haga clic en Enviar para volver a enviar el formulario.</p> <?php } else { ?> <p>por favor, rellene sus datos a continuación y haga clic en Enviar. Los campos marcados con un asterisco (*) son obligatorios.</p> <?php } ?> <form action = "" method = "post"> <fieldset> <label for="nombreUsuario" <?php validateField("nombreUsuario", $camposPendientes); ?> >Introduce tu nombre * </label> <input type = "text" name = "nombreUsuario" id="nombreUsuario" value="<?php setValue("nombreUsuario"); ?> "> <label for="apellidos" <?php validateField("apellidos", $camposPendientes); ?> >y tus apellidos *</label> <input type = "text" name = "apellidos" id="apellidos" value="<?php setValue("apellidos"); ?> " ><br><br> <label for="tipoMusica">¿Qué tipo de música te gusta escuchar?</label> <select name="tipoMusica[]" id="tipoMusica" size="4" multiple="multiple"> <option value="Rock"<?php setSelected("tipoMusica", "Rock"); ?> >Rock </option> <option value="Pop"<?php setSelected("tipoMusica", "Pop"); ?> >Pop </option> <option value="Regee"<?php setSelected("tipoMusica", "Regee"); ?> >Regee </option> <option value="Clásica"<?php setSelected("tipoMusica", "Clásica"); ?> >Clásica </option> </select><br><br> ¿Que tipo de libros lees? <br> <label for="novelaNegra">Novela Negra</label> <input type="checkbox" name="tipoLibros[]" id="novelaNegra" value="Novela Negra"<?php setChecked("tipoLibros", "Novela Negra"); ?> ><br> <label for="cienciaFiccion">Ciencia Ficción</label> <input type="checkbox" name="tipoLibros[]" id="cienciaFiccion" value="Ciencia Ficción" <?php setChecked("tipoLibros", "Ciencia Ficción"); ?> ><br> <label for="fantasia">Fantasía</label> <input type="checkbox" name="tipoLibros[]" id="fantasia" value="Fantasía" <?php setChecked("tipoLibros", "Fantasía"); ?> ><br><br> <input type = "submit" name="enviar" value="Enviar"> </fieldset> </form> <?php pie(); }
function displayStep3() { ?> <h1>Member Signup: Step 3</h1> <form action="registration_multistep.php" method="post"> <div style="width: 30em;"> <input type="hidden" name="step" value="3" /> <input type="hidden" name="firstName" value="<?php setValue("firstName"); ?> " /> <input type="hidden" name="lastName" value="<?php setValue("lastName"); ?> " /> <input type="hidden" name="gender" value="<?php setValue("gender"); ?> " /> <input type="hidden" name="favoriteWidget" value="<?php setValue("favoriteWidget"); ?> " /> <label for="newsletter">Do you want to receive our newsletter?</label> <input type="checkbox" name="newsletter" id="newsletter" value="yes"<?php setChecked("newsletter", "yes"); ?> /> <label for="comments">Any comments?</label> <textarea name="comments" id="comments" rows="4" cols="50"><?php setValue("comments"); ?> </textarea> <div style="clear: both;"> <input type="submit" name="submitButton" id="nextButton" value="Next >" /> <input type="submit" name="submitButton" id="backButton" value="< Back" style="margin-right: 20px;" /> </div> </div> </form> <?php }
function displayForm2() { $ciudades = array('Roma', 'Paris', 'Nueva York', 'Londres', 'Berlin', 'Atenas'); $ocultosInformacion = ""; $ocultosCiudades = ""; foreach ($ciudades as $valor) { $valorCampo = setValue2("ciudades", $valor); $ocultosCiudades .= '<input type="hidden" name="ciudades[]" value="' . $valorCampo . '">'; } $informacion = array('Correo Postal', 'Email'); foreach ($informacion as $valor) { $valorCampo = setValue2("informacion", $valor); $ocultosInformacion .= '<input type="hidden" name="informacion[]" value="' . $valorCampo . '">'; } $datos = array("error" => $error, "ocultosCiudades" => $ocultosCiudades, "ocultosInformacion" => $ocultosInformacion, "validacionNombre" => validateField("nombre", $camposPendientes, $camposErroneos), "nombre" => setValue("nombre"), "validacionApellidos" => validateField("apellidos", $camposPendientes, $camposErroneos), "apellidos" => setValue("apellidos"), "validacionDireccion" => validateField("direccion", $camposPendientes, $camposErroneos), "direccion" => setValue("direccion"), "validacionTelefono" => validateField("telefono", $camposPendientes, $camposErroneos), "telefono" => setValue("telefono"), "email" => setValue("email"), "validacionEmail" => validateField("email", $camposPendientes, $camposErroneos), "validacionFoto" => validateField("foto", $camposPendientes, $camposErroneos)); $plantilla = "plantillas/paso1.html"; $formulario = vista($datos, $plantilla); $datos = array("titulo" => TITULO, "formulario" => $formulario); $plantilla = "plantillas/plantilla.html"; $html = vista($datos, $plantilla); print $html; }
/** * Modifies category data before it is returned. * * Adds CountAllDiscussions column to each category representing the sum of * discussions within this category as well as all subcategories. * * @since 2.0.17 * @access public * * @param object $Data SQL result. */ public static function addCategoryColumns($Data) { $Result =& $Data->result(); $Result2 = $Result; foreach ($Result as &$Category) { if (!property_exists($Category, 'CountAllDiscussions')) { $Category->CountAllDiscussions = $Category->CountDiscussions; } if (!property_exists($Category, 'CountAllComments')) { $Category->CountAllComments = $Category->CountComments; } // Calculate the following field. $Following = !((bool) val('Archived', $Category) || (bool) val('Unfollow', $Category)); $Category->Following = $Following; $DateMarkedRead = val('DateMarkedRead', $Category); $UserDateMarkedRead = val('UserDateMarkedRead', $Category); if (!$DateMarkedRead) { $DateMarkedRead = $UserDateMarkedRead; } elseif ($UserDateMarkedRead && Gdn_Format::toTimestamp($UserDateMarkedRead) > Gdn_Format::ToTimeStamp($DateMarkedRead)) { $DateMarkedRead = $UserDateMarkedRead; } // Set appropriate Last* columns. setValue('LastTitle', $Category, val('LastDiscussionTitle', $Category, null)); $LastDateInserted = val('LastDateInserted', $Category, null); if (val('LastCommentUserID', $Category) == null) { setValue('LastCommentUserID', $Category, val('LastDiscussionUserID', $Category, null)); setValue('DateLastComment', $Category, val('DateLastDiscussion', $Category, null)); setValue('LastUserID', $Category, val('LastDiscussionUserID', $Category, null)); $LastDiscussion = arrayTranslate($Category, array('LastDiscussionID' => 'DiscussionID', 'CategoryID' => 'CategoryID', 'LastTitle' => 'Name')); setValue('LastUrl', $Category, DiscussionUrl($LastDiscussion, false, '/') . '#latest'); if (is_null($LastDateInserted)) { setValue('LastDateInserted', $Category, val('DateLastDiscussion', $Category, null)); } } else { $LastDiscussion = arrayTranslate($Category, array('LastDiscussionID' => 'DiscussionID', 'CategoryID' => 'CategoryID', 'LastTitle' => 'Name')); setValue('LastUserID', $Category, val('LastCommentUserID', $Category, null)); setValue('LastUrl', $Category, DiscussionUrl($LastDiscussion, false, '/') . '#latest'); if (is_null($LastDateInserted)) { setValue('LastDateInserted', $Category, val('DateLastComment', $Category, null)); } } $LastDateInserted = val('LastDateInserted', $Category, null); if ($DateMarkedRead) { if ($LastDateInserted) { $Category->Read = Gdn_Format::toTimestamp($DateMarkedRead) >= Gdn_Format::toTimestamp($LastDateInserted); } else { $Category->Read = true; } } else { $Category->Read = false; } foreach ($Result2 as $Category2) { if ($Category2->TreeLeft > $Category->TreeLeft && $Category2->TreeRight < $Category->TreeRight) { $Category->CountAllDiscussions += $Category2->CountDiscussions; $Category->CountAllComments += $Category2->CountComments; } } } }
<title><?php echo setValue($settings, 'site_name', 'T-Shirt eCommerce'); ?> </title> <meta property="og:url" content="<?php echo $url; ?> " /> <meta property="og:type" content="website" /> <meta property="og:title" content="<?php echo setValue($settings, 'site_name', 'T-Shirt eCommerce'); ?> " /> <meta property="og:description" content="<?php echo setValue($settings, 'meta_description', 'T-Shirt eCommerce'); ?> " /> <meta property="og:image" content="<?php echo $image; ?> " /> <script> window.location.href = "<?php echo $base_url; ?> "; </script> </head> <body> </body>
/** * Add/edit a field. */ public function settingsController_profileFieldAddEdit_create($Sender, $Args) { $Sender->permission('Garden.Settings.Manage'); $Sender->setData('Title', t('Add Profile Field')); if ($Sender->Form->authenticatedPostBack()) { // Get whitelisted properties $FormPostValues = $Sender->Form->formValues(); foreach ($FormPostValues as $Key => $Value) { if (!in_array($Key, $this->FieldProperties)) { unset($FormPostValues[$Key]); } } // Make Options an array if ($Options = val('Options', $FormPostValues)) { $Options = explode("\n", preg_replace('/[^\\w\\s()-]/u', '', $Options)); if (count($Options) < 2) { $Sender->Form->addError('Must have at least 2 options.', 'Options'); } setValue('Options', $FormPostValues, $Options); } // Check label if (val('FormType', $FormPostValues) == 'DateOfBirth') { setValue('Label', $FormPostValues, 'DateOfBirth'); } if (!val('Label', $FormPostValues)) { $Sender->Form->addError('Label is required.', 'Label'); } // Check form type if (!array_key_exists(val('FormType', $FormPostValues), $this->FormTypes)) { $Sender->Form->addError('Invalid form type.', 'FormType'); } // Force CheckBox options if (val('FormType', $FormPostValues) == 'CheckBox') { setValue('Required', $FormPostValues, true); setValue('OnRegister', $FormPostValues, true); } // Merge updated data into config $Fields = $this->GetProfileFields(); if (!($Name = val('Name', $FormPostValues))) { // Make unique name from label for new fields $Name = $TestSlug = preg_replace('`[^0-9a-zA-Z]`', '', val('Label', $FormPostValues)); $i = 1; while (array_key_exists($Name, $Fields) || in_array($Name, $this->ReservedNames)) { $Name = $TestSlug . $i++; } } // Save if no errors if (!$Sender->Form->errorCount()) { $Data = c('ProfileExtender.Fields.' . $Name, array()); $Data = array_merge((array) $Data, (array) $FormPostValues); saveToConfig('ProfileExtender.Fields.' . $Name, $Data); $Sender->RedirectUrl = url('/settings/profileextender'); } } elseif (isset($Args[0])) { // Editing $Data = $this->GetProfileField($Args[0]); if (isset($Data['Options']) && is_array($Data['Options'])) { $Data['Options'] = implode("\n", $Data['Options']); } $Sender->Form->setData($Data); $Sender->Form->addHidden('Name', $Args[0]); $Sender->setData('Title', t('Edit Profile Field')); } $CurrentFields = $this->getProfileFields(); $FormTypes = $this->FormTypes; /** * We only allow one DateOfBirth field, since it is a special case. Remove it as an option if we already * have one, unless we're editing the one instance we're allowing. */ if (array_key_exists('DateOfBirth', $CurrentFields) && $Sender->Form->getValue('FormType') != 'DateOfBirth') { unset($FormTypes['DateOfBirth']); } $Sender->setData('FormTypes', $FormTypes); $Sender->setData('CurrentFields', $CurrentFields); $Sender->render('addedit', '', 'plugins/ProfileExtender'); }
function displayGracias() { $datos = array("nombre" => setValue("nombre"), "foto" => $_POST["foto"]); $plantilla = "plantillas/gracias.html"; $formulario = vista($datos, $plantilla); $datos = array("titulo" => TITULO, "formulario" => $formulario); $plantilla = "plantillas/plantilla.html"; $html = vista($datos, $plantilla); print $html; }
} else { if ($theaction == 'setName') { setValue($id, "name"); } else { if ($theaction == 'getEmail') { printValue($id, "email"); } else { if ($theaction == 'setEmail') { setValue($id, "email"); } else { if ($theaction == 'getAddress') { printValue($id, "address"); } else { if ($theaction == 'setAddress') { setValue($id, "address"); } else { if ($theaction == 'getMajor') { printValue($id, "major"); } else { if ($theaction == 'setMajor') { setValue($id, "major"); } else { print "Invalid paramter"; } } } } } } } }
<option value="0"><?php lang('art_category'); ?> </option> <?php echo dispayCateTree($data['categories'], 0, array(setValue($data['art'], 'cate_id', 0))); ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-3"><?php lang('description'); ?> </label> <div class="col-sm-7"> <textarea type="text" class="form-control" name="art[description]" rows="3"><?php echo setValue($data['art'], 'description', ''); ?> </textarea> </div> </div> <input type="hidden" class="form-control" name="id" value="<?php echo $data['id']; ?> "> </form> </div> </div>
/** * Allows user to bookmark or unbookmark a discussion. * * If the discussion isn't bookmarked by the user, this bookmarks it. * If it is already bookmarked, this unbookmarks it. * * @since 2.0.0 * @access public * * @param int $DiscussionID Unique discussion ID. */ public function bookmark($DiscussionID = null) { // Make sure we are posting back. if (!$this->Request->isAuthenticatedPostBack()) { throw permissionException('Javascript'); } $Session = Gdn::session(); if (!$Session->UserID) { throw permissionException('SignedIn'); } // Check the form to see if the data was posted. $Form = new Gdn_Form(); $DiscussionID = $Form->getFormValue('DiscussionID', $DiscussionID); $Bookmark = $Form->getFormValue('Bookmark', null); $UserID = $Form->getFormValue('UserID', $Session->UserID); // Check the permission on the user. if ($UserID != $Session->UserID) { $this->permission('Garden.Moderation.Manage'); } $Discussion = $this->DiscussionModel->getID($DiscussionID); if (!$Discussion) { throw notFoundException('Discussion'); } $Bookmark = $this->DiscussionModel->bookmark($DiscussionID, $UserID, $Bookmark); // Set the new value for api calls and json targets. $this->setData(array('UserID' => $UserID, 'DiscussionID' => $DiscussionID, 'Bookmarked' => (bool) $Bookmark)); setValue('Bookmarked', $Discussion, (int) $Bookmark); // Update the user's bookmark count $CountBookmarks = $this->DiscussionModel->setUserBookmarkCount($UserID); $this->jsonTarget('.User-CountBookmarks', (string) $CountBookmarks); // Short circuit if this is an api call. if ($this->deliveryType() === DELIVERY_TYPE_DATA) { $this->render('Blank', 'Utility', 'Dashboard'); return; } // Return the appropriate bookmark. require_once $this->fetchViewLocation('helper_functions', 'Discussions'); $Html = bookmarkButton($Discussion); // $this->jsonTarget(".Section-DiscussionList #Discussion_$DiscussionID .Bookmark,.Section-Discussion .PageTitle .Bookmark", $Html, 'ReplaceWith'); $this->jsonTarget("!element", $Html, 'ReplaceWith'); // Add the bookmark to the bookmarks module. if ($Bookmark) { // Grab the individual bookmark and send it to the client. $Bookmarks = new BookmarkedModule($this); if ($CountBookmarks == 1) { // When there is only one bookmark we have to get the whole module. $Target = '#Panel'; $Type = 'Append'; $Bookmarks->getData(); $Data = $Bookmarks->toString(); } else { $Target = '#Bookmark_List'; $Type = 'Prepend'; $Loc = $Bookmarks->fetchViewLocation('discussion'); ob_start(); include $Loc; $Data = ob_get_clean(); } $this->jsonTarget($Target, $Data, $Type); } else { // Send command to remove bookmark html. if ($CountBookmarks == 0) { $this->jsonTarget('#Bookmarks', null, 'Remove'); } else { $this->jsonTarget('#Bookmark_' . $DiscussionID, null, 'Remove'); } } $this->render('Blank', 'Utility', 'Dashboard'); }
/** * Modifies comment data before it is returned. * * @since 2.1a32 * @access public * * @param object $Data SQL result. */ public function calculate($Comment) { // Do nothing yet. if ($Attributes = val('Attributes', $Comment)) { setValue('Attributes', $Comment, unserialize($Attributes)); } $this->EventArguments['Comment'] = $Comment; $this->fireEvent('SetCalculatedFields'); }
* PHP Default Argument Value * * If function was used without arguments, but it has default ones, * those will be used as actual arguments * * */ echo "<br>"; function setValue($min_value = 10) { echo "Current value is: {$min_value} <br>"; } setValue(20); setValue(); // will use the default value of 50 setValue(100); setValue(60); /* * PHP Functions - Returning values * * Using return statement * * */ echo "<br>"; function calculation($x, $y, $type) { if ($type == "+") { return $x + $y; } elseif ($type == "-") { return $x - $y; } elseif ($type == "*") { return $x * $y;
function displayForm($missingFields) { $results = array("pageTitle" => "Membership Form", "scriptUrl" => "registration.php", "missingFields" => $missingFields, "firstNameAttrs" => validateField("firstName", $missingFields), "firstNameValue" => setValue("firstName"), "lastNameAttrs" => validateField("lastName", $missingFields), "lastNameValue" => setValue("lastName"), "genderAttrs" => validateField("gender", $missingFields), "genderMChecked" => setChecked("gender", "M"), "genderFChecked" => setChecked("gender", "F"), "favoriteWidgetOptions" => array("superWidget" => setSelected("favoriteWidget", "superWidget"), "megaWidget" => setSelected("favoriteWidget", "megaWidget"), "wonderWidget" => setSelected("favoriteWidget", "wonderWidget")), "newsletterChecked" => setChecked("newsletter", "yes"), "commentsValue" => setValue("comments")); require "templates/registration_form.php"; }
/** * * * @param array $Data * @param array $Columns The columns/table information for the join. Depending on the argument's index it will be interpreted differently. * - <b>numeric</b>: This column will come be added to the resulting join. The value can be either a string or a two element array where the second element specifies an alias. * - <b>alias</b>: The alias of the child table in the query. * - <b>child</b>: The name of the child column. * - <b>column</b>: The name of the column to put the joined data into. Can't be used with <b>prefix</b>. * - <b>parent</b>: The name of the parent column. * - <b>table</b>: The name of the child table in the join. * - <b>prefix</b>: The name of the prefix to give the columns. Can't be used with <b>column</b>. * @param array $Options An array of extra options. * - <b>sql</b>: A Gdn_SQLDriver with the child query. * - <b>type</b>: The join type, either JOIN_INNER, JOIN_LEFT. This defaults to JOIN_LEFT. */ public static function join(&$Data, $Columns, $Options = array()) { $Options = array_change_key_case($Options); $Sql = Gdn::sql(); //GetValue('sql', $Options, Gdn::SQL()); $ResultColumns = array(); // Grab the columns. foreach ($Columns as $Index => $Name) { if (is_numeric($Index)) { // This is a column being selected. if (is_array($Name)) { $Column = $Name[0]; $ColumnAlias = $Name[1]; } else { $Column = $Name; $ColumnAlias = ''; } if (($Pos = strpos($Column, '.')) !== false) { $Sql->select($Column, '', $ColumnAlias); $Column = substr($Column, $Pos + 1); } else { $Sql->select(isset($TableAlias) ? $TableAlias . '.' . $Column : $Column, '', $ColumnAlias); } if ($ColumnAlias) { $ResultColumns[] = $ColumnAlias; } else { $ResultColumns[] = $Column; } } else { switch (strtolower($Index)) { case 'alias': $TableAlias = $Name; break; case 'child': $ChildColumn = $Name; break; case 'column': $JoinColumn = $Name; break; case 'parent': $ParentColumn = $Name; break; case 'prefix': $ColumnPrefix = $Name; break; case 'table': $Table = $Name; break; case 'type': // The type shouldn't be here, but handle it. $Options['Type'] = $Name; break; default: throw new Exception("Gdn_DataSet::Join(): Unknown column option '{$Index}'."); } } } if (!isset($TableAlias)) { if (isset($Table)) { $TableAlias = 'c'; } else { $TableAlias = 'c'; } } if (!isset($ParentColumn)) { if (isset($ChildColumn)) { $ParentColumn = $ChildColumn; } elseif (isset($Table)) { $ParentColumn = $Table . 'ID'; } else { throw Exception("Gdn_DataSet::Join(): Missing 'parent' argument'."); } } // Figure out some options if they weren't specified. if (!isset($ChildColumn)) { if (isset($ParentColumn)) { $ChildColumn = $ParentColumn; } elseif (isset($Table)) { $ChildColumn = $Table . 'ID'; } else { throw Exception("Gdn_DataSet::Join(): Missing 'child' argument'."); } } if (!isset($ColumnPrefix) && !isset($JoinColumn)) { $ColumnPrefix = stringEndsWith($ParentColumn, 'ID', true, true); } $JoinType = strtolower(val('Type', $Options, self::JOIN_LEFT)); // Start augmenting the sql for the join. if (isset($Table)) { $Sql->from("{$Table} {$TableAlias}"); } $Sql->select("{$TableAlias}.{$ChildColumn}"); // Get the IDs to generate an in clause with. $IDs = array(); foreach ($Data as $Row) { $Value = val($ParentColumn, $Row); if ($Value) { $IDs[$Value] = true; } } $IDs = array_keys($IDs); $Sql->whereIn($ChildColumn, $IDs); $ChildData = $Sql->get()->resultArray(); $ChildData = self::index($ChildData, $ChildColumn, array('unique' => GetValue('unique', $Options, isset($ColumnPrefix)))); $NotFound = array(); // Join the data in. foreach ($Data as $Index => &$Row) { $ParentID = val($ParentColumn, $Row); if (isset($ChildData[$ParentID])) { $ChildRow = $ChildData[$ParentID]; if (isset($ColumnPrefix)) { // Add the data to the columns. foreach ($ChildRow as $Name => $Value) { setValue($ColumnPrefix . $Name, $Row, $Value); } } else { // Add the result data. setValue($JoinColumn, $Row, $ChildRow); } } else { if ($JoinType == self::JOIN_LEFT) { if (isset($ColumnPrefix)) { foreach ($ResultColumns as $Name) { setValue($ColumnPrefix . $Name, $Row, null); } } else { setValue($JoinColumn, $Row, array()); } } else { $NotFound[] = $Index; } } } // Remove inner join rows. if ($JoinType == self::JOIN_INNER) { foreach ($NotFound as $Index) { unset($Data[$Index]); } } }
/** * Function to connect to Exact, this creates the client and automatically retrieves oAuth tokens if needed * * @return \Picqer\Financials\Exact\Connection * @throws Exception */ function connect() { $connection = new \Picqer\Financials\Exact\Connection(); $connection->setRedirectUrl('__REDIRECT_URL__'); $connection->setExactClientId('__CLIENT_ID__'); $connection->setExactClientSecret('__CLIENT_SECRET__'); if (getValue('authorizationcode')) { $connection->setAuthorizationCode(getValue('authorizationcode')); } if (getValue('accesstoken')) { $connection->setAccessToken(getValue('accesstoken')); } if (getValue('refreshtoken')) { $connection->setRefreshToken(getValue('refreshtoken')); } if (getValue('expires_in')) { $connection->setTokenExpires(getValue('expires_in')); } // Make the client connect and exchange tokens try { $connection->connect(); } catch (\Exception $e) { throw new Exception('Could not connect to Exact: ' . $e->getMessage()); } // Save the new tokens for next connections setValue('accesstoken', $connection->getAccessToken()); setValue('refreshtoken', $connection->getRefreshToken()); // Save expires time for next connections setValue('expires_in', $connection->getTokenExpires()); return $connection; }