MediaWiki Local Extension Link - hyperlink

I installed MediaWiki locally. Everything worked but I needed a functionality to link files from our file server. I stumbled upon an extension called Extension:NetworkLink which provides this functionality. You just have to add filepath in your wikipage and it should work. My problem is that I the path of my local wiki installation "http://localhost/w/index.php/" is addedd to filepath and then the link does not work. I tried to edit the url manipulation in the PHP file to cut it out but it does not work. Here is the edited code:
<?php
function linkExtension() {
global $wgParser;
$wgParser->setHook( "link", "renderlink" );
}
# The callback function for converting the input text to HTML output
function renderlink( $loc='', $argv=array() ) {
global $wgOut, $wgTitle, $wgParser;
$loc = htmlspecialchars($loc);
$pos = strrpos($loc, "/");
if ($pos != false)
{
$loc = substr($loc, $pos + 1);
}
switch( strtoupper( $argv['TARGET'] ) ) {
case "SELF":
$out = "$loc";
break;
case "TOP":
$out = "$loc";
break;
case "PARENT":
$out = "$loc";
break;
default:
$out = "$loc";
}
return $out;
}

I found another better solution. First install the FF-plugin LocalLink. Then add the MediaWiki Extension:FileProtocolLinks. After this you can add links in your wiki to local files or shares on your network like this:
LAN: <file>\\Fileserver\Directory1\Directory2\MyFile.zip</file>
Local: <file>C:/Directory1/Directory2/MyFile.zip</file>

Related

php scandir produces extra elements (2 dots)

Hi,
I have the following files in a directory called content: index.php, page1.php, page2.php and page3.php ONLY.
Then I have this code:
$column = scandir("content");
foreach ($column as $value) {
$stvalue = str_replace(".php", "", $value);
echo "<div>$stvalue</div>";
}
Nevertheless, this is what I get:
<div>.</div>
<div>..</div>
<div>index</div>
<div>page1</div>
<div>page2</div>
<div>page3</div>
Whats with the first 2 elements? I dont have files named like that so I dont get it.
Thank you.
. - is a special directory referencing the current directory.
.. - is also a special directory and its referencing the parent directory.
To remove the special directories I can think of some options:
1.
foreach(glob("*.php") as $filename) {
echo "<div>$filename</div>";
}
2.
$files = array_diff(scandir("content"), array('..', '.'));
foreach($files as $file) { ... }
3.
foreach ($files as $file) {
if($file != '.' and $file != '..') { ... }
}
All of the above are alternatives. You don't need to use scandir() if you use glob() and vice versa. glob() - expects a pattern. It is possible to also provide it with the path like this:
glob("[path]/*.php") - this will list any php file located in path. glob() documentation can be found here PHP - glob()
$column = scandir("content");
foreach ($column as $value) {
$stvalue = str_replace(".php", "", $value);
if($stvalue != '.' || $stvalue != '..') {
echo "<div>$stvalue</div>";
}
}
. refers to the current directory. .. refers to the parent directory.
This is why typing cd .. on a command prompt will change to the parent directory. It's been this way in DOS, every version of Windows, Mac OS X, it's not just Linux and UNIX variants.
If you don't want to display them on your page, just skip the first two entries using array_slice.

Phalcon PHP post link with JavaScript confirmation dialog

I am developing a CRUD system in Phalcon PHP (version 1.3.4).
My goal is to create a link (delete row), that asks for confirmation on click (JavaScript confirmation box) and then goes (request type POST) to the link.
So lets say a user clicks on the "delete row" button.
JavaScript confirmation "Are you sure you want to delete this row?"
User clicks "yes"
Webpage does a POST to "/users/delete/1"
I know CakePHP has a function (FormHelper::postLink()) that does exactly that.
I was wondering if Phalcon PHP also had a function like this.
I see three possibilities to achieve what you want. One is to create a macro in Volt template, second is to add a function to your View. Third and closest to - what I understand is your wish - is to extend Phalcons tag helper and this is part I will describe here.
Phalcon has its own Tag helper to allow you to easily create some elements. postLink is not a part that is implemented there, but you can easily achieve it. In my example I have namespace of Application with class of Tag that extends from \Phalcon\Tag. This is my base for this tutorial.
// Tag.php
namespace Application;
class Tag extends \Phalcon\Tag
{
static public function postLink() {
return '<strong>TEST TAG</strong>';
}
}
To force Phalcon DI to use this class, it is necessary to override it's standard declaration from engine by declaring it by hand as a new DI service:
// services.php
$di['tag'] = function() {
return new \Application\Tag();
};
You can test if it is working properly by typing {{ tag.postLink() }} in Volt template or with $this->tag->postLink() if using phtml template.
Now you can fill your Tag::postLink() method with HTML and parameters you wish it will produce:
namespace Application;
class Tag extends \Phalcon\Tag
{
static $forms = [];
static public function postLink($title, $url, $options = array()) {
// random & unique form ID
while ($randId = 'f_' . mt_rand(9000, 999999)) {
if (!isset(self::$forms[$randId])) {
self::$forms[$randId] = true;
break;
}
}
// dialog message
$dialogMessage = isset($options['message']) && $options['message'] ? $options['message'] : 'Are you sure you want to go on?';
$html = <<<HTML
<form action="{$url}" method="post" id="{$randId}">
<!-- maybe not necessary part -->
<input type="hidden" name="confirmed" value="1" />
</form>
{$title}
HTML;
return $html;
}
}
Now you can run it like this:
{{ tag.postLink('delete', '/users/delete/1') }}
{% set formOptions = ['message' : 'Are you sure you want to delete user Kialia Kuliambro?'] %}
{{ tag.postLink('delete', '/users/delete/1', formOptions) }}
{{ tag.postLink('delete', '/users/delete/1', ['message' : 'Are you sure you want to delete user Kialia Kuliambro?']) }}
Have fun extending :)
There's a few ways to implement such behavior in phalcon. Before anything, we need to understand how views and view helpers work in phalcon. And if you pay close attention, you'll notice, both .volt and .phtml have direct access to the DI.
In volt, for example, you can access the flash service, and output its messages by calling:
{{ flash.output() }}
which gets converted to the phtml: <?php echo $this->flash->output(); ?>
Thus my solution focuses on defining a new service in the DI which volt can access. In CakePHP, the syntax for postLink(), looks something like: echo $this->Form->postLink() while the function is actually defined in a class named FormHelper. So my solution will do the same thing, define a class FormHelper, then inject it into the view under the name Form.
Create an app/helpers/ directory.
Update your app/config/config.php file adding a reference to our new directory: 'helpersDir'=> APP_PATH . '/app/helpers/'
Update your app/config/loader.php file adding $config->application->helpersDir to the registered directories.
Create a new file app/helpers/FormHelper.php
Copy-paste the following code into the file:
<?php
use Phalcon\Tag;
class FormHelper extends Tag
{
protected $_lastAction = '';
public function dottedNameToBracketNotation($name)
{
$parts=explode('.',$name);
$first = array_shift($parts);
$name=$first . ($parts ? '[' . implode('][', $parts) . ']' : '');
return $name;
}
protected function flatten(array $data, $separator = '.')
{
$result = [];
$stack = [];
$path = null;
reset($data);
while (!empty($data)) {
$key = key($data);
$element = $data[$key];
unset($data[$key]);
if (is_array($element) && !empty($element)) {
if (!empty($data)) {
$stack[] = [$data, $path];
}
$data = $element;
reset($data);
$path .= $key . $separator;
} else {
$result[$path . $key] = $element;
}
if (empty($data) && !empty($stack)) {
list($data, $path) = array_pop($stack);
reset($data);
}
}
return $result;
}
protected function _confirm($message, $okCode, $cancelCode = '', $options = [])
{
$message = json_encode($message);
$confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
if (isset($options['escape']) && $options['escape'] === false) {
$confirm = $this->h($confirm);
}
return $confirm;
}
public function h($text, $double = true, $charset = 'UTF-8')
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, $charset, $double);
}
protected function _lastAction($url)
{
$action = $url;//Router::url($url, true);
$query = parse_url($action, PHP_URL_QUERY);
$query = $query ? '?' . $query : '';
$this->_lastAction = parse_url($action, PHP_URL_PATH) . $query;
}
public function postLink($title, $url = null, array $options = [])
{
$out='';
$options += ['block' => null, 'confirm' => null];
$requestMethod = 'POST';
if (!empty($options['method'])) {
$requestMethod = strtoupper($options['method']);
unset($options['method']);
}
$confirmMessage = $options['confirm'];
unset($options['confirm']);
$formName = str_replace('.', '', uniqid('post_', true));
$formOptions = [
'name' => $formName,
'style' => 'display:none;',
'method' => 'post',
];
if (isset($options['target'])) {
$formOptions['target'] = $options['target'];
unset($options['target']);
}
$formOptions[0]=$url;
$out.=$this->form($formOptions);
$out .= $this->hiddenField(['_method','value' => $requestMethod]);
$fields = [];
if (isset($options['data']) && is_array($options['data'])) {
foreach ($this->flatten($options['data']) as $key => $value) {
$out .= $this->hiddenField([$this->dottedNameToBracketNotation($key),'value' => $value]);
}
unset($options['data']);
}
$out .= $this->endForm();
//This is currently unsupported
if ($options['block']) {
if ($options['block'] === true) {
$options['block'] = __FUNCTION__;
}
//$this->_View->append($options['block'], $out);
$out = '';
}
unset($options['block']);
$url = '#';
$onClick = 'document.' . $formName . '.submit();';
if ($confirmMessage) {
$options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
} else {
$options['onclick'] = $onClick . ' ';
}
$options['onclick'] .= 'event.returnValue = false; return false;';
$options[0]=$url;
$options[1]=$title;
$options[2]=false;
$out .= $this->linkTo($options);
return $out;
}
}
Edit your app/config/services.php file and add in:
$di->set('Form',function () {
return new FormHelper();
});
(you could make "Form" lowercase if you want, both work. I made it capital to closer resemble CakePHP's syntax. Do note that Volt is case sensitive when trying to access services but phtml will lowercase it.)
Edit the template you want to test the code on, such as app/views/index/test.volt
Copy-paste the following code into there:
{{ Form.postLink(' Delete','',['confirm':'Are you sure you want to delete #4?','data':['a':['b','c']]]) }}
Alternatively for phtml, use: <?php echo $this->form->postLink(' Delete', '', array('confirm' => 'Are you sure you want to delete #4?', 'data' => array('a' => array('b', 'c')))); ?>
Run it, and watch it work its magic, just render your index/test.volt template by visiting /index/test in your address bar. (Make sure you defined such an action in your index controller)
In terms, of other solutions, you could also use $compiler->addFunction() to make functions available to volt, one at time. The page in the manual gives the example of $compiler->addFunction('shuffle', 'str_shuffle');. You can attempt to override the factoryDefault for "tag" in the DI, and use the helper we already defined which extends tag. So you'd just change it from "form" to "tag" like so: $di->set('tag',function () {return new FormHelper();}); but, as you can see, it won't make the function postLink() available to volt as a function, you'll notice you still need to access it as tag.postLink(). Rather, all the \Phalcon\Tag functions are actually hard-coded into the volt engine. You can see this clearly by viewing the zephir source code of the \Phalcon\Mvc\View\Engine\Volt\Compiler class available over here. For your convenience, and in case the link ever gets broken, I have posted a snippet here which shows the "tag" functions in volt are actually hard-coded into it:
if method_exists(className, method) {
let arrayHelpers = this->_arrayHelpers;
if typeof arrayHelpers != "array" {
let arrayHelpers = [
"link_to": true,
"image": true,
"form": true,
"select": true,
"select_static": true,
"submit_button": true,
"radio_field": true,
"check_field": true,
"file_field": true,
"hidden_field": true,
"password_field": true,
"text_area": true,
"text_field": true,
"email_field": true,
"date_field": true,
"tel_field": true,
"numeric_field": true,
"image_input": true
];
let this->_arrayHelpers = arrayHelpers;
}
if isset arrayHelpers[name] {
return "$this->tag->" . method . "(array(" . arguments . "))";
}
return "$this->tag->" . method . "(" . arguments . ")";
}
So, if you'd like to "hack" in a few more methods by extending the \Phalcon\Tags class, you're out of luck. However, as demonstrated on the volt documentation page, there exists the concept of registering custom extensions to work with volt. The documentation gives the example of: $compiler->addExtension(new PhpFunctionExtension());
Where the source of the class is:
<?php
class PhpFunctionExtension
{
/**
* This method is called on any attempt to compile a function call
*/
public function compileFunction($name, $arguments)
{
if (function_exists($name)) {
return $name . '('. $arguments . ')';
}
}
}
This would allow volt access to any function you'd like, without having to manually register every possible function you could possibly ever need. You can test this by trying to access str_shuffle in volt, like we did before with $compiler->addFunction('shuffle', 'str_shuffle'); but this time without having to register it.
In terms of other solutions, you could also try to integrate CakePHP and PhalconPHP together, and attempt to call CakePHP's view helpers from PhalconPHP, but then you'd run into a problem of CakePHP not understanding your router setup you have configured in Phalcon. But, if you're determined, you could code all the routes and config for CakePHP and run it alongside PhalconPHP, but I'd highly discourage such a desperate workaround. And, finally, if you understand how the function works, and you barely use it, you could get away with just hard-coding the HTML in the first place. Honestly, CakePHP's logic doesn't look so sound to me in the first place because it has to corrupt your HTML document with a form inserted which can bother your layout. I think it would make more sense to generate a form dynamically with JavaScript, if we're using JavaScript already, and append it to the <body> when the button is clicked, then submit the form we just created dynamically. But, you wanted a CakePHP implementation, so I coded it as close to the logic they used as possible. It's not perfect, in terms of supporting all their features, such as block, but it should suit most of your needs.
I can always revise my implementation, but I think it demonstrates how to work with Phalcon pretty well for those migrating from CakePHP.

How do I tell where the user's home directory is, in Dart?

I want to store a small bit of information in a file, persisted between runs of a command-line app. Probably the best location is a small file in the user's home directory.
I'd like to write a property/config file into a user's home directory. How can I tell, for Windows, Mac, and Linux, what the user's home directory is? I am using Dart.
Identify the OS then use the designated environment variable for that particular OS. You can read the OS/environment variables from platform. For e.g. :
OS : String os = Platform.operatingSystem; Various checks like isLinux, isAndroid are given
Map<String, String> envVars = Platform.environment;
An example:
import 'dart:io' show Platform, stdout;
void main() {
String os = Platform.operatingSystem;
String home = "";
Map<String, String> envVars = Platform.environment;
if (Platform.isMacOS) {
home = envVars['HOME'];
} else if (Platform.isLinux) {
home = envVars['HOME'];
} else if (Platform.isWindows) {
home = envVars['UserProfile'];
}
stdout.writeln(home);
}
Home dirs taken from here : http://en.wikipedia.org/wiki/Home_directory
This will do:
String get userHome =>
Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
I don't have access to a windows machine, but I found this logic in pub:
if (Platform.environment.containsKey('PUB_CACHE')) {
cacheDir = Platform.environment['PUB_CACHE'];
} else if (Platform.operatingSystem == 'windows') {
var appData = Platform.environment['APPDATA'];
cacheDir = path.join(appData, 'Pub', 'Cache');
} else {
cacheDir = '${Platform.environment['HOME']}/.pub-cache';
}
Looks like for Linux and Mac, we can do:
Platform.environment['HOME']
For Windows, it's better to find a location inside of Platform.environment['APPDATA']
Similar to other answers:
// Get the home directory or null if unknown.
String homeDirectory() {
switch (Platform.operatingSystem) {
case 'linux':
case 'macos':
return Platform.environment['HOME'];
case 'windows':
return Platform.environment['USERPROFILE'];
case 'android':
// Probably want internal storage.
return '/storage/sdcard0';
case 'ios':
// iOS doesn't really have a home directory.
return null;
case 'fuchsia':
// I have no idea.
return null;
default:
return null;
}
}
You can tweak how it behaves according to your needs. I did try and figure out the answer for Fuchsia but I can't work out if it even has home directories to be honest!

TCPDF and database: conflicts in PHP

Hi this my php code :
<?php require_once('tcpdf/config/lang/eng.php'); ?>
<?php require_once('tcpdf/tcpdf.php'); ?>
<?php include_once("class/class_productos.php"); ?>
<?php include_once("class/class_clientes.php"); ?>
<?php include_once("class/class_img_gen.php"); ?>
<?php include_once("class/class_acros.php"); ?> // here is MY DB CONNECTION
<?php
class MYPDF extends TCPDF {
//Page header
public function Header() {
$auto_page_break = $this->AutoPageBreak;
$this->SetAutoPageBreak(false, 0);
$img_file = 'img/pdf_fondo.jpg';
$this->Image($img_file, $x=0, $y=0, $w=210, $h=297, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0);
$this->SetAutoPageBreak($auto_page_break);
}
}
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator('ACROS');
$pdf->SetAuthor('ACROS');
$pdf->SetTitle('Lista de producto');
$pdf->SetSubject('Lista de producto');
$pdf->SetKeywords('ACROS, acros, mayorista, informática');
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(false);
$pdf->SetMargins(0, 0, 0);
$pdf->SetAutoPageBreak(FALSE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->setLanguageArray($l);
$pdf->AddPage();
$category = $_GET['c'];
$getCategory = "SELECT * FROM prod_detalle WHERE fk_marca = '$category'";
$getCategory = mysql_query($getCategory);
$count = mysql_num_rows($getCategory);
$txt = "result ".$count;
// output the HTML content
$pdf->writeHTML($txt, true, 0, true, 0);
$pdf->SetY(-30);
$pdf->SetX(0.65);
$pdf->MultiCell(20, 0, $txtB, $border = 0,$align = 'L',$fill = 0,$ln = 1,$x = '',$y = '',$reseth = false, $stretch = 0, $ishtml = true, $autopadding = false, $maxh = 0);
$pdf->Output('lista.pdf', 'I');
?>
and i'm getting this two warnings :
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean
given in /mnt/futurehome/netlogiq/public_html/acros/lista_pdf.php on
line 64
Warning: Cannot modify header information - headers already sent by
(output started at
/mnt/futurehome/netlogiq/public_html/acros/lista_pdf.php:64) in
/mnt/futurehome/netlogiq/public_html/acros/tcpdf/tcpdf.php on line
5405 TCPDF ERROR: Some data has already been output to browser, can't
send PDF file
Can anyone help me with this ?? If run the query in phpmyadmin, it returns the wanted data. So the query works fine !
The reason you are getting the error from mysql_num_rows() is because you haven't initialized the connection to the database. You are also using the old (and deprecated as og PHP 5.5) MySQL interface - you should look into using mysqli or PDO instead.
A full explanation of how to initialize the connection to the database and communicate with it using the correct resource handle is, IMO, beyond the scope of an SO answer. Maybe start here instead:
http://www.php.net/manual/en/mysqli.quickstart.connections.php
The reason you're getting the second error is simply because the first error message is being sent to the browser before your call to $pdf->Output(). Once you get your database connection working and remove the error messages that problem will go away.
Just remove the line
require_once('tcpdf/config/lang/eng.php');
and
edit the tcpdf.php file from the tcpdf folder:
add the line ob_end_clean(); as below (3rd last line):
public function Output($name='doc.pdf', $dest='I') {
//LOTS OF CODE HERE....}
switch($dest) {
case 'I': {
// Send PDF to the standard output
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
//some code here....}
case 'D': { // download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
break;}
case 'F':
case 'FI':
case 'FD': {
// save PDF to a local file
//LOTS OF CODE HERE..... break;}
case 'E': {
// return PDF as base64 mime email attachment)
case 'S': {
// returns PDF as a string
return $this->getBuffer();
}
default: {
$this->Error('Incorrect output destination: '.$dest);
}
}
ob_end_clean(); //add this line here
return '';
}

action script getUrl issue

am facing an problem using getUrl in as2 , when i run the swf using test movie the link work probably , but if i run the published file am getting a wrong url , example
-run via test movie : getting -> www.google.com
-run the published swf file : getting ->file:///C:/Users/moata/Desktop/actionScript/www.google.com
dots.ignoreWhite = true;
dots.load('links.xml');
dots.onLoad = function(success:Boolean){
if(success){
xmlNode = this.firstChild;
var all:MovieClip = attachMovie("test","all",depth);
setTimeout(startMe,6000);
}else{
trace("Could not load XML");
}
function startMe (){
for(i=1;i<=6;i++){
all['btn'+i].onRelease = function() {
for(i=0;i<6;i++){
var name = this;
if(String(xmlNode.childNodes[i].attributes.TITLE) == String(name)){
getURL(xmlNode.childNodes[i].childNodes[0].nodeValue, "_blank");
}
}
}
}
}
};
i just need add http:// in getRUL as follow
getURL("http://www.google.com"); , instead of getURL("www.google.com");

Resources