How do I change PHP Scripts from MediaWiki to Wordpress Plugin? - php

I am working on a project where I have MediaWiki PHP Scripts that import publications information from a DB into a Publications Page.
I need to convert this scripts to Wordpress Plugin but I don't really know the best way to do it. Quite lost right now I try to do the Tutorial: Writing a simple WordPress plugin from scratch but I did not have success on that and I still don't have this working.
Original MediaWiki Code
Here you will see my original MediaWiki Code:
<?php
# the function registered by the extension gets the text between the
# tags as input and can transform it into arbitrary HTML code.
# Note: The output is not interpreted as WikiText but directly
# included in the HTML output. So Wiki markup is not supported.
# To activate the extension, include it from your LocalSettings.php
# with: include("extensions/YourExtensionName.php");
$wgExtensionFunctions[] = "wfExampleExtension";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// Register the extension with the WikiText parser.
// The first parameter is the name of the new tag. In this case it defines
// the tag:
// <server-id> ... </server-id>
// The second parameter is the callback function for processing the text
// between the tags.
//
function wfExampleExtension() {
global $wgParser; // MediaWiki global variable
$wgParser->setHook("server-id", "renderSERVERID");
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// The callback function for converting the input text to HTML output.
// The function registered by the extension gets the text between the
// tags as $input and transforms it into arbitrary HTML code.
// Note: the output is not interpreted as WikiText but directly included in
// the HTML output. So Wiki markup is not supported.
//
// To activate the extension, include it from your LocalSettings.php
// with: include("extensions/YourExtensionName.php");
//
// $argv is an array containing any arguments passed to the extension like:
// <server-id what="foo" bar>..
//
// According to the metawiki, this works in MediaWiki 1.5.5.
// <server-id what="person" id="62">This text is not actually used</server-id>
//
// Personal information:
// <server-id what='person' id='62'></server-id>
//
// Information for a group:
// <server-id what='publications' cc='IP02'></server-id>
//
function renderSERVERID($input, $argv) {
// connect to the database
$idDBLink = odbc_connect('SERVER ID', 'some_db', 'some_db_pw');
if (!$idDBLink) { exit("Connection to database failed! Please contact root#server-id.org."); }
$html = "";
if ($argv['what'] == 'person') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
// information about someone:
// 1. personal contacts and summary
// 2. publications by person
// 3. advisory work by person
//
$html .= personById($idDBLink, $id[0]);
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= pubsById($idDBLink, $internalIds);
$html .= advisingById($idDBLink, $internalIds);
}
}
else if ($argv['what'] == 'advising') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= iconv('latin1', 'UTF-8', advisingById($idDBLink, $internalIds));
}
}
else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$id = trim($argv["id"]);
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', pubsByCC($idDBLink, $cc));
}
else if ($id != '') {
$html .= iconv('latin1', 'UTF-8', pubsById($idDBLink, authorIdByNumber($idDBLink, array($id))));
}
}
/*else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
if ($cc != '') {
$html .= pubsByCC($idDBLink, $cc);
}
}*/
else if ($argv['what'] == 'calls') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$showClosed = isset($argv['showclosed']) ? trim($argv['showclosed']) : "";
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', callsByCC($idDBLink, $cc, $showClosed == "yes"));
}
}
else {
// oops! no text...
}
odbc_close($idDBLink);
return $html;
}
?>
My WordPress Try Version
Here you will see what I try to do with WordPress Code:
<?php
// ==================================================
// WordPress Plugin
// ==================================================
/*
Plugin Name: Publications Importer
Plugin URI: http://someperson.me/downloads/publications-importer
Description: Integrates the Publications Importer plugin into your WordPress install.
Version: 0.0.1
Author: Someone
Author URI: http://someperson.me/
*/
require_once 'server-id-config.php';
require_once 'server-id-util.php';
require_once 'server-id-people.php';
require_once 'server-id-pubs.php';
require_once 'server-id-advising.php';
defined( 'ABSPATH' ) or die( 'Plugin file cannot be accessed directly.' );
if ( ! class_exists( 'Publication' ) ) {
class Publication
{
/**
* Tag identifier used by file includes and selector attributes.
* #var string
*/
protected $tag = 'publications-importer';
/**
* User friendly name used to identify the plugin.
* #var string
*/
protected $name = 'Publications Importer';
/**
* Current version of the plugin.
* #var string
*/
protected $version = '0.0.1';
public function __construct()
{
add_shortcode( $this->tag, array( &$this, 'shortcode' ) );
}
public function shortcode( $atts, $content = null )
{
extract( shortcode_atts( array(
'what' => false,
'cc' => false
), $atts ) );
$styles = array();
if ( is_numeric( $what ) ) {
$styles[] = esc_attr( 'what: ' . $what );
}
$classes = array(
$this->tag
);
if ( !empty( $cc ) ) {
$classes[] = esc_attr( $cc );
}
ob_start();
?><pre cc="<?php esc_attr_e( implode( ' ', $classes ) ); ?>"<?php
echo ( count( $styles ) > 0 ? ' style="' . implode( ' ', $styles ) . '"' : '' );
?>><p><?php echo $content; ?></p></pre><?php
return ob_get_clean();
}
}
new Publication;
}
// ==================================================
// END WordPress Plugin
// ==================================================
# the function registered by the extension gets the text between the
# tags as input and can transform it into arbitrary HTML code.
# Note: The output is not interpreted as WikiText but directly
# included in the HTML output. So Wiki markup is not supported.
# To activate the extension, include it from your LocalSettings.php
# with: include("extensions/YourExtensionName.php");
$wgExtensionFunctions[] = "wfExampleExtension";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// Register the extension with the WikiText parser.
// The first parameter is the name of the new tag. In this case it defines
// the tag:
// <server-id> ... </server-id>
// The second parameter is the callback function for processing the text
// between the tags.
//
function wfExampleExtension() {
global $wgParser; // MediaWiki global variable
$wgParser->setHook("server-id", "renderSERVERID");
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// The callback function for converting the input text to HTML output.
// The function registered by the extension gets the text between the
// tags as $input and transforms it into arbitrary HTML code.
// Note: the output is not interpreted as WikiText but directly included in
// the HTML output. So Wiki markup is not supported.
//
// To activate the extension, include it from your LocalSettings.php
// with: include("extensions/YourExtensionName.php");
//
// $argv is an array containing any arguments passed to the extension like:
// <server-id what="foo" bar>..
//
// According to the metawiki, this works in MediaWiki 1.5.5.
// <server-id what="person" id="62">This text is not actually used</server-id>
//
// Personal information:
// <server-id what='person' id='62'></server-id>
//
// Information for a group:
// <server-id what='publications' cc='IP02'></server-id>
//
function renderSERVERID($input, $argv) {
// connect to the database
$idDBLink = odbc_connect('SERVER ID', 'some_db', 'some_db_pw');
if (!$idDBLink) { exit("Connection to database failed! Please contact root#server-id.org."); }
$html = "";
if ($argv['what'] == 'person') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
// information about someone:
// 1. personal contacts and summary
// 2. publications by person
// 3. advisory work by person
//
$html .= personById($idDBLink, $id[0]);
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= pubsById($idDBLink, $internalIds);
$html .= advisingById($idDBLink, $internalIds);
}
}
else if ($argv['what'] == 'advising') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= iconv('latin1', 'UTF-8', advisingById($idDBLink, $internalIds));
}
}
else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$id = trim($argv["id"]);
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', pubsByCC($idDBLink, $cc));
}
else if ($id != '') {
$html .= iconv('latin1', 'UTF-8', pubsById($idDBLink, authorIdByNumber($idDBLink, array($id))));
}
}
/*else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
if ($cc != '') {
$html .= pubsByCC($idDBLink, $cc);
}
}*/
else if ($argv['what'] == 'calls') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$showClosed = isset($argv['showclosed']) ? trim($argv['showclosed']) : "";
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', callsByCC($idDBLink, $cc, $showClosed == "yes"));
}
}
else {
// oops! no text...
}
odbc_close($idDBLink);
return $html;
}
?>
So what I exactly need to know is:
1) Should not WordPress be able to interpret the MediaWiki tags (for example: <server-id what='publications' cc='IP02'></server-id>) and do this automatically?
2) Where can I find more documentation about this kind of migrations?
3) Am I doing this the wrong way?

WordPress and MediaWiki are independent applications and one can not expect a plugin written for one to be directly portable to the other. If you are lucky some of the code may be reusable but it will not be as simple as a cut and paste. The two application has different ways of doing things.
1) No, WordPress will not be able to understand such tags. WordPress can be made to understand MediaWiki style markdown tags with additional plugins but I do not recognise the tag example you highlight.
2) I think your current approach is sound, you will need to understand what the MediaWiki code is doing and re-create this within a WordPress plugin. I doubt there is a short cut to this other than taking some time to get to grips with WP plugins. If you enjoy coding and writing plugins thin this is time well spent. Being able to customise WordPress is very useful.
3) Other than re-coding it yourself the other option would be to see if there is a WordPress plugin that does what you are looking for. Your question does not detail what exactly the functionality is that you are trying to add.
Having written plugins for both MediaWiki and WordPress I have found the easier more enjoyable to work with.

Related

PHP widget use class selector instead of <tag> to build menu

I hope on of you clever chaps might be able to answer this riddle.
I have an excellent widget I am trying to integrate into my site. It creates menus from <H1>, <H2> etc, tags in the document. This is very useful as I can create sub menu navigation for each of my pages by styling the titles.
I am however using a wordpress theme that has extensions added to the editor that style various parts of the pages, including for example titles.
So the output from how it styles the title in HTML output is as follows for example:
<h1 class="grve-element grve-align-left grve-title-striped" style="">Visit</h1>
The PHP script I will load in below, the relevant section it appears to grab tags is:
$tags_to_parse = "<h1>";
Is there a way I can tell this PHP script to grab this particular H1 class?
Cheers,
Tomek
<?php
/*
Plugin Name: Anchors Menu
Description: Check Wordpress static pages content and create a widget menu with links that point to words between the HTML tags you chose.
Author: Gonçalo Rodrigues
Version: 1.2
Author URI: http://www.goncalorodrigues.com
*/
/* Copyright 2010 Gonçalo Rodrigues (email : gonafr [AT] gmail [DOT] com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
//ERROR_REPORTING(E_ALL);
$count = -1;
add_action("init", "anc_insert_init");
add_filter("the_content", "anc_add_link_text");
// renders the list in your theme;
function anc_insert()
{
$tags_to_parse = "<h1>";
$current_page_id = get_the_ID();
$page_data = get_page($current_page_id);
$current_page_name = $page_data->post_name;
$current_page_cat_id = get_cat_ID($current_page_name);
$page_id = get_the_ID();
// if it's blog style page
if (is_home()){
$count = 0;
$content = "";
if ( have_posts() ) : while ( have_posts() ) : the_post();
$id_post = get_the_ID();
$post = get_post($id_post);
$content .= "<a name=\"$count\"></a>";
$content .= $post->post_content;
$count++;
endwhile; else:
//_e("Sorry, no posts matched your criteria.");
endif;
anc_list_menu($content);
//echo "Sorry but this plugin only work on Wordpress pages.";
}
//if it's page style page
else if(is_page()){
$page_id = get_the_ID();
$page_data = get_page( $page_id );
//$title = $page_data->post_title; // Get title
$content = $page_data->post_content;
//if content is empty i will fetch all pages that are child of the current page and get their titles
$fetch_children_pages = true;
if (fetch_children_pages == true && $content==""){
$content = "";
$pages = get_pages('child_of='.$page_id.'&sort_column=post_date&sort_order=desc');
foreach($pages as $page)
{
$content .= "<".$tags_to_parse.">".$page->post_title."</".$tags_to_parse.">";
if(!$content)
continue;
$count++;
}
}
anc_list_menu($content);
}
// if it's single post
else if (is_single()){
$content = "";
$content .= get_the_content();
anc_list_menu($content);
//echo "Sorry but this plugin only work on Wordpress pages.";
}
//if it's a category page
else if(is_category){
//echo $current_page_cat_id;
//echo $current_page_name;
//echo $current_page_id;
$current_cat = get_the_category();
//echo 'teste'.$current_cat[0]->cat_name;
$current_cat_id = get_cat_ID($current_cat[0]->cat_name);
$posts = get_posts('$category_name='.$current_cat[0]->cat_name);
$content = "";
if ( have_posts() ) : while ( have_posts() ) : the_post();
$id_post = get_the_ID();
$post = get_post($id_post);
$content .= "<".$tags_to_parse.">".$post->post_title."</".$tags_to_parse.">";
endwhile; else:
//_e("Sorry, no posts matched your criteria.");
endif;
anc_list_menu($content);
//echo "Sorry but this plugin only work on Wordpress pages.";
}
else {
//_e("Error: This page is not a tradicional Wordpress Page or a Wordpress Blog!");
}
}
// prints the menu with the links to the titles
function anc_list_menu($content){
// list all tags
$foo_tags = anc_get_tags($content);
if($foo_tags[1] != 0){
$foo = -1;
echo "<ul>";
foreach($foo_tags[0] as $key => $val){
$foo++;
echo "<li>".$val."</li>";
}
echo "</ul>";
}else{
//no tags found
//_e("Not found any tag of the type that was selected to be parsed.");
}
}
// retrieve all words between tags
function anc_get_tags($content){
global $tags_to_parse;
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
$pattern_search = "/(<".$tags_to_parse.".*>)(.*)(<\/".$tags_to_parse.">)/isxmU";
preg_match_all($pattern_search, $content, $patterns);
$res = array();
array_push($res, $patterns[2]);
array_push($res, count($patterns[2]));
return $res;
}
// insert widget
function anc_insert_init()
{
//register the widget
register_sidebar_widget("Anchors Menu", "anc_widget_insert");
//register the widget control
register_widget_control("Anchors Menu", "anc_widget_insert_control");
}
function anc_widget_insert($args) {
global $title, $tags_to_parse;
extract($args);
//get our options
$options = get_option("anc_title");
$title = $options["anc_title"];
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
echo $before_widget;
/*Insert any headers you want in the next line, between "?>" and "<?". Leave blank for no header. */
echo $before_title . $title . $after_title;
anc_insert();
echo $after_widget;
}
// responsable for options in backoffice
function anc_widget_insert_control() {
global $title, $tags_to_parse;
//get saved options if user change things
//handle user input
if (isset($_POST["anc_insert_submit"])){
$foo_title = strip_tags(stripslashes($_POST["anc_title"]));
$foo_tags = strtolower(stripslashes($_POST["anc_tags"]));
$options["anc_title"] = $foo_title;
$options["anc_tags"] = $foo_tags;
update_option("anc_title", $options);
update_option("anc_tags", $options);
}
else {
//default options
$options["anc_title"] = "Menu";
$options["anc_tags"] = "h2";
update_option("anc_title", $options);
update_option("anc_tags", $options);
}
//get our options
$options = get_option("anc_title");
$title = $options["anc_title"];
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
//print the widget control
include("anc-insert-widget-control.php");
}
// adds anchors to content tags
function anc_add_link_text($content){
global $tags_to_parse, $count;
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
$pattern_search = array();
$pattern_search = "/(<".$tags_to_parse.".*>)(.*)(<\/".$tags_to_parse.">)/isxmU";
return preg_replace_callback($pattern_search, "anc_replacement", $content, -1);
}
// aux funtion to add_link_text
function anc_replacement($matches){
global $tags_to_parse, $count;
$count++;
return "<a name=\"".$count."\"></a>"."<".$tags_to_parse.">".$matches[2]."</".$tags_to_parse.">";
}
?>
Replace your $pattern_search variable with this:
$pattern_search = "/(<h1 .*(".$tags_to_parse.")+ .*>)+(.*)+(<\/h1>)/isxmU";
Now you can pass class to your function:
$tags_to_parse = "grve-element";
Update
$tags_to_parse = "grve-element";
$content = '<h1 class="grve-element grve-align-left grve-title-striped" style="">Visit</h1>sf efew <h1 grve-element>rffef</h1>';
$pattern_search = "/\<h1 .(".$tags_to_parse.")?[^\>]*\>(.*?)\<\/h1\>/";
preg_match_all($pattern_search, $content, $patterns);
print_r($patterns[2]);
Output
Array ( [0] => Visit [1] => rffef )

Wordpress do_shortcode strange behavior

I am developing a WP plugin which processes shortcodes and displays amazon item data in place of them. The plugin is working as desired, except for a little strange behavior. You can see my test run at http://passivetest.themebandit.com/test-post-for-zon-plugin/ .
If you scroll down on that page, you can see that 4 "1" s are appended to the content. The shortcode is processed 4 times in this page, and each time WP is adding an undesired 1 to the output. I don't understand why this is happening. There is no "1" anywhere in my html files, and its nowhere in the post content. All my functions just return the content that is to be replaced in place of the shortcode. Can someone please give an explanation for it and let me know how to remove these? Thanks in advance..
My code is as follows:
add_shortcode('zon_product', 'zon_process_shortcode');
// Zon Shortcode processor
function zon_process_shortcode($attributes, $content = null) {
global $zon_html_path;
// default options for shortcode
$options = array('asin' => '', 'style' => 'compact', 'loc' => 'com');
extract(shortcode_atts($options, $attributes));
$asin = $attributes['asin'];
// first find asin in local zon_data table
$zdb = ZonDbHandler::instance();
$product = $zdb->findASIN($asin);
if ($product) {
// if product exists in db, render template
return zon_display_product($product, $attributes);
} else {
// product does not exist in database, get data through amazon api worflow
$product = ZonLibrary::getAmazonProduct($asin, $attributes['loc']);
if ($product) {
// product data has been successfully retrieved and saved, render template
return zon_display_product($product, $attributes);
} else {
// error in fetching product data, check amazon access key id and api secret
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'api_error.php');
return $content;
}
}
}
// Renders selected template with product data
function zon_display_product(ZonProduct $product, $attributes) {
global $zon_html_path;
global $zon_path;
// process other shortcode options
$view_vars = array();
$view_vars['style'] = (isset($attributes['style'])) ? $attributes['style'] : "default";
$view_vars['show_price'] = (isset($attributes['show_price']) && $attributes['show_price'] == 0) ? false : true;
$view_vars['price_updates'] = (isset($attributes['price_updates']) && $attributes['price_updates'] == 0) ? false : true;
$view_vars['hide_unavailable'] = (isset($attributes['hide_unavailable']) && $attributes['hide_unavailable'] == 1) ? true : false;
$view_vars['show_desc'] = (isset($attributes['show_desc']) && $attributes['show_desc'] == 0) ? false : true;
// check if template file exists
if (!is_file($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php')) {
$content = 'ERROR! Zon Template not found. Please check you are using a correct value for the "style" parameter.';
return $content;
} else {
// get product array
$product = $product->getArray();
// if product is unavailable and hide_unavailable is true, return unavailable template
if ($view_vars['hide_unavailable']) {
if ((strpos($product['availability'], "Usually") === false) && strpos($product['availability'], "ships") === false) {
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'unavailable.php');
return $content;
}
}
// render chosen template file
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php');
return $content;
}
}

First Drupal Module - converting PHP script to Drupal 7 Module

I am trying to convert a much used PHP script that has served me well as a block for a while but now I am trying to convert it into a module for ease of use, and for the challenge. It puts a block into the list but not any content into the block. As I am more of a HTML5 / CSS3 geek this PHP is a little new to me. Could anyone help mentor me here? Many thanks
<code>
<?php
/**
* #file
* A block module that displays a local weather forcast for Reading Berks UK.
*/
function moduleone_help($path, $arg) {
switch ($path) {
case "admin/help#moduleone":
return '<p>' . t("Displays the weather for a user defined region defined by <a href='#'>LINK</a>") . '</p>';
break;
}
}
/**
* Implement hook_block_info().
*/
function moduleone_block_info() {
$blocks['moduleone'] = array(
// The name that will appear in the block list.
'info' => t('Module One Weather'),
// Default setting.
'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
/**
* Custom content function.
*
* Get weather report from Yahoo
* Output var is $output.
*
* #return
* A result set of the targeted posts.
*/
function moduleone_weather(){
$zipcode = 'UKXX0117';
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=f');
$xml = simplexml_load_string($result);
//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');
if(!empty($location)){
foreach($xml->channel->item as $item){
$current = $item->xpath('yweather:condition');
$forecast = $item->xpath('yweather:forecast');
$current = $current[0];
$output = <<<END
<h1 style="margin-bottom: 0">Weather for {$location[0]['city']}, {$location[0]['region']}</h1>
<small>{$current['date']}</small>
<h2>Current Conditions</h2>
<p>
<span style="font-size:72px; font-weight:bold;">{$current['temp']}°F</span>
<br/>
<img src="http://l.yimg.com/a/i/us/we/52/{$current['code']}.gif" style="vertical-align: middle;"/>
{$current['text']}
</p>
<h2>Forecast</h2>
{$forecast[0]['day']} - {$forecast[0]['text']}. High: {$forecast[0]['high']} Low: {$forecast[0]['low']}
<br/>
{$forecast[1]['day']} - {$forecast[1]['text']}. High: {$forecast[1]['high']} Low: {$forecast[1]['low']}
<br/>
{$forecast[2]['day']} - {$forecast[2]['text']}. High: {$forecast[2]['high']} Low: {$forecast[2]['low']}
</p>
END;
}
}else{
$output = 'No results found, please try a different zip code.';
}
function moduleone_block_view($delta = '') {
switch ($delta) {
case 'moduleone':
$block['subject'] = t('Weather Conditions');
if (user_access('access content')) {
}
if (empty($output)) {
$block['content'] = t('No forcast available.');
}
else {
$block['content'] = theme('item_list', array(
'items' => $output));
}
}
return $block;
}
}</code>
Drupal works via a system of hooks which you override, so rightly you've overridden hook_help, hook_block_info and hook_block_view but there is no hook_weather (well, at least not in core Drupal although a contributed module may provide one) so at the moment moduleone_weather() is never called.
You could fix this by placing $output = moduleone_weather(); before you check whether $output is empty or not in your hook_block_view function.

Drupal SEO page titles

I am trying to list a few games, each, on individual pages. While a game page is opened into a new window the head title of page (< title>) is set to games page header (< h1> My Game). Also to list all game types I am using quick tabs.
From 12 types of games only at 2 of them the title is settled correctly and my problem is that I don't know from where it comes. I have tried to var_dump() all the headers and all of them are returning the same thing "Game" not the title/heading from db.
Where should I look or what would be the next step ?
$metaTitle = $page['content']['metatags']['global']['title']['#attached']['metatag_set_preprocess_variable'][0][2];
$metaTitle = str_replace(' | SuperCasino.com', '', $metaTitle);
Where should I look or what would be the next step ?
Here is my preprocess page code
function desktop_preprocess_page(&$vars, $hook) {
if (isset($vars['node_title'])) {
$vars['title'] = $vars['node_title'];
}
// Adding a class to #page in wireframe mode
if (theme_get_setting('wireframe_mode')) {
$vars['classes_array'][] = 'wireframe-mode';
}
// Adding classes wether #navigation is here or not
if (!empty($vars['main_menu']) or !empty($vars['sub_menu'])) {
$vars['classes_array'][] = 'with-navigation';
}
if (!empty($vars['secondary_menu'])) {
$vars['classes_array'][] = 'with-subnav';
}
// Page template suggestions based off of content types
if (isset($vars['theme_hook_suggestions']['node'])) {
$vars['theme_hook_suggestions'][] = 'page__type__'. $vars['node']->type;
$vars['theme_hook_suggestions'][] = "page__node__" . $vars['node']->nid;
}
// Add first/last classes to node listings about to be rendered.
if (isset($vars['page']['content']['system_main']['nodes'])) {
// All nids about to be loaded (without the #sorted attribute).
$nids = element_children($vars['page']['content']['system_main']['nodes']);
// Only add first/last classes if there is more than 1 node being rendered.
if (count($nids) > 1) {
$first_nid = reset($nids);
$last_nid = end($nids);
$first_node = $vars['page']['content']['system_main']['nodes'][$first_nid]['#node'];
$first_node->classes_array = array('first');
$last_node = $vars['page']['content']['system_main']['nodes'][$last_nid]['#node'];
$last_node->classes_array = array('last');
}
}
//var_dump($vars['theme_hook_suggestions']);die();
// Page template suggestions based off URL alias
if (module_exists('path')) {
//$alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
$alias = request_path();
if ($alias != $_GET['q']) {
//echo'here';die;
$template_filename = 'page';
foreach (explode('/', $alias) as $path_part) {
$template_filename = $template_filename . '__' . str_replace('-','_',$path_part);
$vars['theme_hook_suggestions'][] = $template_filename;
//var_dump($template_filename);
}
}
}
You can use drupal_set_title(YOUR_TITLE) for the different pages.
drupal_set_title($title = NULL, $output = CHECK_PLAIN)
https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_set_title/7
From the theme level, you can use this code in your template.php:
function MYTHEMENAME_preprocess_page(&$vars, $hook) {
$vars['title'] = $custom_title';
$vars['head_title'] = $custom_title;
}
For Drupal 7 its is :
$vars['site_name']

php script is parsing content from RTE (tt_news) but internal links are not appearing as speaking url

I have a news article with internal links. In the RTE I see links like
http://www.yourdomain.com/?id=3
in the html text mode. The problem is that this link also appears on the frontend. RealURL should convert this link to something like
http://www.yourdomain.com/products/
The content of RTE is currently parsed like this
$parseObj = t3lib_div::makeInstance('t3lib_parsehtml_proc');
$txt = $parseObj->TS_links_rte($result['bodytext']);
$txt = $parseObj->TS_transform_rte($txt);
I read that I should use something like this
$pObj = t3lib_div::makeInstance('tslib_pibase');
$txt = $pObj->pi_RTEcssText($result['bodytext']);
but I don't know how can I access this function. I get
Fatal error: Call to a member function parseFunc() on a non-object in /home/myuser/www/home/typo3/sysext/cms/tslib/class.tslib_pibase.php on line 1384
What is the right way doing this? How can I access the function pi_RTEcssText? Do I have to use a class? Are there other ways doing it without a class?
EDIT:
I created a new template with TemplaVoila and defined lib.newscontent as TS object path.
TS Main Template
includeLibs.user_news = fileadmin/templates/php_scripts/news/class.news.php
lib.newscontent = USER_INT
lib.newscontent {
userFunc = user_news->main
userFunc.bodytext.parseFunc < lib.parseFunc_RTE
}
class.news.php
<?
class user_news {
var $cObj;
private $conf;
function main($content,$conf) {
$this->conf = $conf;
$this->setPreferences();
$content .= $this->aktuelleNews();
return $content;
}
private function aktuelleNews() {
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*', // SELECT ...
'tt_news', // FROM ...
'pid=22 AND deleted=0 AND hidden=0', // WHERE...
'', // GROUP BY...
'datetime DESC' // ORDER BY...
);
$i = 1;
$out_list = '<ul id="news">';
while ($data = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
$date = date("d.m.Y",$data['datetime']);
$out_list .= '<li>'.$date.': '.$data['title'].'</li>';
$out_detail.= $this->outputnewsdetail($data,$i);
$i++;
}
$out_list .= '</ul>';
return $out_list . $out_detail;
}
private function outputnewsdetail($result,$count){
$this->cObj->start($result, 'tt_news');
$bodytext = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext']);
$bodytext = $this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);
return $bodytext;
}
private function setPreferences() {
}
}
?>
localconf.php
include(PATH_site.'fileadmin/templates/php_scripts/news/class.news.php');
Remaining question
Why does the rendering part in the TS Main Template doesn't work? I used
$this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);
to get my result.
I would prefer:
$txt = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext.']);
You need in your main method: $this->conf = $conf;
In your TypoScript add the parseFunc to bodytext:
plugin.tx_yourplugin_pi1 {
bodytext.parseFunc < lib.parseFunc_RTE
}
The main idea is to use the usual parseFunc which is used by content elements. So you have the same rendering. Another benefit is, that your application is more flexible.
Just as a side note. It is worth to make a lokal cObj for that and hand over the complete data. So you are able to use alle fields in TypoScript. F.e. field = bodytext in your case.
# create lokal cObj - do not override the original data!
$cObj = t3lib_div::makeInstance('tslib_cObj');
foreach ($row = ...) {
# override data array with row. Every field in $row is now accesible via
# TypoScript field = fieldname
$cObj->start($row, $tableName);
$content .= $cObj->stdWrap($row['bodytext'], $this->conf['bodytext.']);
}
# TS Setup:
# in your case you could do somesthing like:
plugin.tx_yourplugin_pi1 {
bodytext.parseFunc < lib.parseFunc_RTE
bodytext.wrap = <div class="hide">|</div>
bodytext.prepend = TEXT
bodytext.prepend.field = bodytext
bodytext.prepend.stripHtml = 1
bodytext.prepend.crop = 30 | ... | 1
bodytext.prepend.wrap = <span title="|" onclick="showBodytext()">info</span>
}
If you need it in an user function try it like this:
function user_yourfunction($content,$conf) {
$result = *magic*
$cObj = t3lib_div::makeInstance('tslib_cObj');
$cObj->start($result, 'your table name');
return $cObj->stdWrap($result['bodytext'], $conf['bodytext.']);
}
In TypoScript:
includeLibs.something = media/scripts/example_callfunction.php
page.10 = TEXT
page.10 {
value = Hello World
postUserFunc = user_yourfunction
postUserFunc.bodytext.parseFunc < lib.parseFunc_RTE
}

Categories