converting a chunk of repeated php into a function? - php

I have little programming experience so the jump from basic php to using classes, functions etc is a little daunting.
I'm building a little php script that works out what "theme" a user has selected via a form and from that selection, it loads some specific files. I've built a working script, but there's so much repetition in it, it's a joke.
// Add our theme names to variables
$theme1 = "theme1";
$theme2 = "theme2";
$theme3 = "theme3";
// Test to see what Theme the user chose.
// Theme 1
if ($themeChoice==$theme1)
{
// Load the theme
$homepage = file_get_contents('../themes/'.$theme1.'/index.html');
$mobile_js_main = file_get_contents('../themes/'.$theme1.'/js/main.js');
$mobile_js_jquery = file_get_contents('../themes/'.$theme1.'/js/jquery.js');
$mobile_css_easy = file_get_contents('../themes/'.$theme1.'/css/easy.css');
$mobile_images_bg = file_get_contents('../themes/'.$theme1.'/images/bg.png');
$mobile_images_footer = file_get_contents('../themes/'.$theme1.'/images/footer.png');
$mobile_images_nav = file_get_contents('../themes/'.$theme1.'/images/nav.png');
if ($AddPortfolioPage != '')
{
$portfolioPage = file_get_contents('../themes/'.$theme1.'/portfolio.html');
}
if ($AddContactPage != '')
{
$ContactPage = file_get_contents('../themes/'.$theme1.'/contact.html');
}
if ($AddBlankPage != '')
{
$blankPage = file_get_contents('../themes/'.$theme1.'/blank.html');
}
}
This is then repeated for each theme...which is obviously not an ideal method of doing this. Any help is much appreciated!

Put all of your themes into an array and loop to find the chosen one.
$themes = array( "theme1", "theme2", "theme3");
foreach( $themes as $theme)
{
if( $themeChoice == $theme)
{
$homepage = file_get_contents('../themes/'.$theme.'/index.html');
$mobile_js_main = file_get_contents('../themes/'.$theme.'/js/main.js');
$mobile_js_jquery = file_get_contents('../themes/'.$theme.'/js/jquery.js');
$mobile_css_easy = file_get_contents('../themes/'.$theme.'/css/easy.css');
$mobile_images_bg = file_get_contents('../themes/'.$theme.'/images/bg.png');
$mobile_images_footer = file_get_contents('../themes/'.$theme.'/images/footer.png');
$mobile_images_nav = file_get_contents('../themes/'.$theme.'/images/nav.png');
if ($AddPortfolioPage != '')
{
$portfolioPage = file_get_contents('../themes/'.$theme.'/portfolio.html');
}
if ($AddContactPage != '')
{
$ContactPage = file_get_contents('../themes/'.$theme.'/contact.html');
}
if ($AddBlankPage != '')
{
$blankPage = file_get_contents('../themes/'.$theme.'/blank.html');
}
break; // Break will exit the loop once the choice is found
}
}

Related

What is a good percent for the similar text function for a mini-search engine?

I am creating a mini search engine for my new poll application. When you go to http://www.pollmc.com/search.php?s=mlg (website not up yet btw) it will search for a similar poll (I have a demo one called "Mlg Right?". It doesn't return it... But If I type in "Right" it does. It returns two polls; one called "Mlg Right?" and the other called "Cool Right?". What percent parameter is recommended for the is_similar text function? Here's my current code:
function search($s, $highPriority = true) {
$link = $this->connect();
$results = array();
$results_highpriority = array();
$results_lowpriority = array();
$query = mysqli_query($link, "SELECT * FROM polls");
while($row = mysqli_fetch_array($query)) {
array_push($results, $row);
}
foreach($results as $r) {
if(strtolower($r['question']) == strtolower($s)) {
array_push($results_highpriority, $r['question']);
continue;
}
/*if(strlen($s) >= 3 && strpos(strtolower($r['question']), strtolower($s)) !== false) {
array_push($results_lowpriority, $r['question']);
continue;
}*/
similar_text(strtolower($r['question']), strtolower($s), $resultPercent);
if($resultPercent >= 50) {
array_push($results_lowpriority, $r['question']);
continue;
}
}
return $highPriority ? $results_highpriority : $results_lowpriority;
}
I did have - commented out - if the question from MYSQL contains the query then add it (that seemed to work) but I'm worried it will return too much when I have like 20+ polls added. Here's my SQL database: http://prntscr.com/alr811

How To Get Twig Template Engine Header Tags in PHP Function

I am trying to extend a Pico navigation plugin to exclude items from the navigation tree where the page's utilizes Twig template engine header tags.
My question is how do I get specific header tags from the .md files in the below PHP function and filter them to be excluded in the navigation tree?
The plugin currently implements the ability to omit items (pages and folders) from the tree with the following settings in a config.php file:
// Exclude pages and/or folders from navigation header
$config['navigation']['hide_page'] = array('a Title', 'another Title');
$config['navigation']['hide_folder'] = array('a folder', 'another folder');
The current function in the plugs' file uses the above config.php as follows:
private function at_exclude($page) {
$exclude = $this->settings['navigation'];
$url = substr($page['url'], strlen($this->settings['base_url'])+1);
$url = (substr($url, -1) == '/') ? $url : $url.'/';
foreach ($exclude['hide_page'] as $p) {
$p = (substr($p, -1*strlen('index')) == 'index') ? substr($p, 0, -1*strlen('index')) : $p;
$p = (substr($p, -1) == '/') ? $p : $p.'/';
if ($url == $p) {
return true;
}
}
foreach ($exclude['hide_folder'] as $f) {
$f = (substr($f, -1) == '/') ? $f : $f.'/';
$is_index = ($f == '' || $f == '/') ? true : false;
if (substr($url, 0, strlen($f)) == $f || $is_index) {
return true;
}
}
return false;
}
I need to add the ability of omitting items (or pages) from the tree using the Twig header tags 'Type' and 'Status' like so in the .md files:
/*
Title: Post01 In Cat01
Description: This post01 in cat01
Date: 2013-10-28
Category:
Type: post // Options: page, post, event, hidden
Status: draft // Options: published, draft, review
Author: Me
Template:
*/
...
The MarkDown content . . .
So if a user wants to remove items tagged with "post" in the 'type' tag and/or "draft" from the 'draft' tag (see header above), they would then add the linked tags in the array below that I added into the config.php:
// Exclude taged items:
$config['navigation']['hide_status'] = array('draft', 'maybe some other status tag');
$config['navigation']['hide_type'] = array('post', 'etc');
I also added the following to the bottom of the at_exclude() function:
private function at_exclude($page) {
. . .
foreach ($exclude['hide_staus'] as $s) {
$s = $headers['status'];
if ($s == 'draft' || 'review') {
return true;
}
}
foreach ($exclude['hide_type'] as $t) {
$t = $headers['type'];
if ($t == 'post' || 'hidden') {
return true;
}
return true;
}
. . .
This is obviously not working for me (because my PHP knowledge is limited). Any help with what I am missing, doing wrong or how I can add this functionality will be greatly appreciated.
I dived into the (not so beautiful) Pico code and those are my findings.
First of all, Pico doesn't read every custom field you add to the content header.
Instead, it has an internal array of fields to parse. Luckily, an hook called before_read_file_meta is provided to modify the array.
In at_navigation.php we'll add:
/**
* Hook to add custom file meta to the array of fields that Pico will read
*/
public function before_read_file_meta(&$headers)
{
$headers['status'] = 'Status';
$headers['type'] = 'Type';
}
This will result in Pico reading the headers, but it won't add the fields to the page data yet. We need another hook, get_page_data. In the same file:
/**
* Hook to add the custom fields to the page data
*/
public function get_page_data(&$data, $page_meta)
{
$data['status'] = isset($page_meta['status']) ? $page_meta['status'] : '';
$data['type'] = isset($page_meta['type']) ? $page_meta['type'] : '';
}
Now, in the at_exclude function, we can add the new logic.
(Instead of cycling, We configure an array of status and types we want to exclude, and we'll check if there is a match with the current page status/type)
private function at_exclude($page)
{
[...]
if(in_array($page['status'], $exclude['status']))
{
return true;
}
if(in_array($page['type'], $exclude['type']))
{
return true;
};
return false;
}
Now let's customize our config.php (I standardized the configuration with the plugin standards):
$config['at_navigation']['exclude']['status'] = array('draft', 'review');
$config['at_navigation']['exclude']['type'] = array('post');
All done!
But if you are just starting out, I'd advise you to use a more mature and recent flat file cms. Unless you are stuck with PHP5.3
I decided to simplify the function to omit it from the config.php since it really isn't needed to be set by the end-user. By doing so, the at_exclude() function is much simpler and quicker on the back-end by omitting all the checks via other files:
at_exclude {
. . .
$pt = $page['type'];
$ps = $page['status'];
$home = ($pt == "home");
$post = ($pt == "post");
$event = ($pt == "event");
$hide = ($pt == "hide");
$draft = ($ps == "draft");
$review = ($ps == "review");
$type = $home || $post || $event || $hide;
$status = $draft || $review;
if ( $type || $status ) {
return true;
};
return false;
}
Obviously it needs some tidying up but you get the picture. Thnx

Update PHP for AiContactSafe to add multiple redirects dependent on Combobox Value

This may help a few people using Aicontactsafe with joomla as the core component does not have it currently as an option. Essentially i need to change the module php file to allow different redirect urls depending on what dropdown option is selected in the "Studio" Combobox field.
Perfectly honest with you i do not know if i am typing in the correct fields or code values:
The test site you can see here - http://www.datumcreative.com/wellness/ and the form is 'book my taster class' on the right.
Below is where i believe code needs adding in the original file:
if (!array_key_exists('return_to', $parameters)) {
// initialize the database
$db = &JFactory::getDBO();
$query = 'SELECT redirect_on_success FROM #__aicontactsafe_profiles WHERE id = ' . $pf;
$db->setQuery( $query );
$redirect_on_success = $db->loadResult();
// set the return link to the current url or the one setup into the profile
if (strlen(trim($redirect_on_success)) == 0) {
$postData['return_to'] = $currentUrl;
} else {
$postData['return_to'] = $redirect_on_success;
}
}
To create the other redirects i added the following custom lines, below the line "$redirect_on_success = $db->loadResult();":
$redirect_to_wgc = "http://www.google.com";
$redirect_to_harp = "http://www.yahoo.co.uk";
I then needed to add the "if" statements **.
**if ($field_values['aics_studio'] == "Welwyn Garden City") {
$postData['return_to'] = $redirect_to_wgc;
}
elseif ($field_values['$aics_studio'] == "Harpenden") {
$postData['return_to'] = $redirect_to_harp;
}**
elseif (strlen(trim($redirect_on_success)) == 0) {
$postData['return_to'] = $currentUrl;
} else {
$postData['return_to'] = $redirect_on_success;
}
No luck so far, any suggestions?

PHP recently viewed script to session array

I've been given this bit of code:
if(isset($_GET['viewevent'])) {
if(count($_SESSION['e_lastviewed']) == 0) {
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
} else if(!in_array($_GET['viewevent'], $_SESSION['e_lastviewed'])) {
$_SESSION['e_lastviewed'][2] = $_SESSION['e_lastviewed'][1];
$_SESSION['e_lastviewed'][1] = $_SESSION['e_lastviewed'][0];
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
}
}
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}
It apparently saves ID's of recently viewed items, so i need to put these id's into an array.
Would this work?
$my_array = array($_SESSION['e_lastviewed'][2],$_SESSION['e_lastviewed'][1],$_SESSION['e_lastviewed'][0]);
I've ran it but it displays blank results (not sure if thats due to me not doing it right or incomplete code...Have i missed something? I'm not sure if i completley understand the script i was given...
try this:
if ( !isset($_SESSION['e_lastviewed']) )
$_SESSION['e_lastviewed'] = array();
// alt: while(count($_SESSION['e_lastviewed']) > 2 ) {
if(count($_SESSION['e_lastviewed']) > 2 ) {
array_shift($_SESSION['e_lastviewed']); // drop off from 3
array_unshift($_SESSION['e_lastviewed'],$_GET['viewevent']); // insert in the beginning
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}

silverstripe, how to use the doPublish()

I am working with SilverStripe, and I am working on making a newspage.
I use the DataObjectAsPage Module( http://www.ssbits.com/tutorials/2012/dataobject-as-pages-the-module/ ), I got it working when I use the admin to publish newsitems.
Now I want to use the DataObjectManager Module instead of the admin module to manage my news items. But this is where the problem exists. Everything works fine in draft mode, I can make a new newsitem and it shows up in draft. But when I want to publish a newsitem, it won't show up in the live or published mode.
I'm using the following tables:
-Dataobjectaspage table,
-Dataobjectaspage_live table,
-NewsArticle table,
-NewsArticle_Live table
The Articles have been inserted while publishing in the Dataobjectaspage table and in the NewsArticle table... But not in the _Live tables...
Seems the doPublish() function hasn't been used while 'Publishing'.
So I'm trying the use the following:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
But when I use this, it gets an error:
here is this picture
It seems to be in a loop....
I've got the NewsArticle.php file where I use this function:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
This function calls the DataObjectAsPage.php file and uses this code:
function doPublish() {
if (!$this->canPublish()) return false;
$original = Versioned::get_one_by_stage("DataObjectAsPage", "Live", "\"DataObjectAsPage\".\"ID\" = $this->ID");
if(!$original) $original = new DataObjectAsPage();
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onBeforePublish', $original);
$this->Status = "Published";
//$this->PublishedByID = Member::currentUser()->ID;
$this->write();
$this->publish("Stage", "Live");
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onAfterPublish', $original);
return true;
}
And then it goes to DataObject.php file and uses the write function ():
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$isNewRecord = false;
if(self::get_validation_enabled()) {
$valid = $this->validate();
if(!$valid->valid()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
throw new ValidationException($valid, "Validation error writing a $this->class object: " . $valid->message() . ". Object not written.", E_USER_WARNING);
return false;
}
}
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = true;
}
}
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if($this->changed) {
foreach($this->getClassAncestry() as $ancestor) {
if(self::has_own_table($ancestor))
$ancestry[] = $ancestor;
}
// Look for some changes to make
if(!$forceInsert) unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $ancestry[0];
if((!isset($this->record['ID']) || !$this->record['ID']) && isset($ancestry[0])) {
DB::query("INSERT INTO \"{$baseTable}\" (\"Created\") VALUES (" . DB::getConn()->now() . ")");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
$manipulation = array();
if(isset($ancestry) && is_array($ancestry)) {
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $fieldValue) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->hasOwnTableDatabaseField($fieldName)) {
$fieldObj = $this->dbObject($fieldName);
if(!isset($manipulation[$class])) $manipulation[$class] = array();
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
$fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
$fieldObj->setValue($this->record[$fieldName], $this->record);
if($class != $baseTable || $fieldName!='ID')
$fieldObj->writeToManipulation($manipulation[$class]);
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "'".SS_Datetime::now()->Rfc2822()."'";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "'".SS_Datetime::now()->Rfc2822()."'";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(self::has_own_table($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->onAfterWrite();
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
if(!isset($this->record['Created'])) {
$this->record['Created'] = SS_Datetime::now()->Rfc2822();
}
$this->record['LastEdited'] = SS_Datetime::now()->Rfc2822();
} else {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Write ComponentSets as necessary
if($writeComponents) {
$this->writeComponents(true);
}
return $this->record['ID'];
}
Look at the $this->onAfterWrite();
It probably goes to my own function on NewsArticle.php and there starts the loop! I'm not sure though, so i could need some help!!
Does anyone knows how to use the doPublish() function?
The reason that is happening is that in the DataObjectAsPage::publish() method, it is calling ->write() - line 11 of your 3rd code sample.
So what happens is it calls ->write(), at the end of ->write() your onAfterWrite() method is called, which calls publish(), which calls write() again.
If you remove the onAfterWrite() function that you've added, it should work as expected.
The doPublish() method on DataObjectAsPage will take care of publishing from Stage to Live for you.

Categories