MediaWiki - Hook to edit/alter page title on creation - mediawiki

I'm looking to (programmatically) edit/alter the title of a page when its created and before its saved. I've tried a couple hooks to no avail. I can access the title being saved along with other info which ill be used to alter the title, but can not find the right call to save the altered title.
It is for a private/local lan wiki (currently MediaWiki version 1.38.1 ).
When a new article is created with in a certon category I want to number it with a prefix of #### - based on the number of articles already in the category. At the top of the category page itself I have a <inputbox> which pulls a template that has the wiki syntax for the category in it [[Category:BlaBla]]. When the article is saved I'm doing a check to make sure its a new article and some ofther checks for the info I need, which is working fine, but I can not save the new altered page name.
I've tried the following hooks to no avail.
onMultiContentSave
onArticlePrepareTextForEdit
https://www.mediawiki.org/wiki/Manual:Hooks/MultiContentSave
https://www.mediawiki.org/wiki/Manual:Hooks/ArticlePrepareTextForEdit
Heres acouple snippets ive been testing with, both do as i want, aside from saving the altered page name.
public static function onArticlePrepareTextForEdit( WikiPage $wikiPage, ParserOptions $parserOptions ) {
return;
$exists = $wikiPage->exists();
if ($exists == 1) {
#return true;
}
$getTitle = $wikiPage->getTitle();
# check if title starts with 0000, exit if so, no work needs to be done
if (self::titleCheck($getTitle)) {
#return true;
}
$checkCategories = $wikiPage->getCategories();
$inMalak = false;
foreach ($checkCategories as $value) {
if ($value == "Category:Malak") {
$inMalak = true;
}
}
if ($inMalak == 1) {
$newTitle = self::newTitlePre() . $getTitle;
#$wikiPage->setTitle($newTitle);
print(">" . $newTitle . "<br>");
}
self::pr($newTitle);
}
public static function onMultiContentSave(RenderedRevision $renderedRevision, UserIdentity $user, CommentStoreComment $summary, $flags, Status $hookStatus){
#return;
$revision = $renderedRevision->getRevision();
$getTitle = $revision->getPageAsLinkTarget();
if (self::titleCheck($getTitle)) {
return true;
}
#$titleOBJ = $revision->Title();
$title = $revision->getId();
$parent_id = $revision->getId();
$content = $revision->getContent( SlotRecord::MAIN );
$new_content = $content->getText();
#$test = $revision->ParserOutput();
$parent_id = "";
if ($parent_id == "") {
$pos = strpos($new_content, "[[Category:Malak]]");
if ($pos) {
$newTitle = self::newTitlePre() . $getTitle;
#$wikiPage->setTitle($newTitle);
}
}
self::pr($newTitle);
}
EDIT........
Still have not found the proper way to do this, but came up with a work around (hackery) which works for my needs.
Using the onEditFormPreloadText hook, change the url and added a new parameter ('MalakHere'), edited the 'title' parameter to the altered title, then do a redirect with the new page name. In the hook function there is a check for the 'MalakHere' parameter, if found (only cause of redirect) then it will exit the function so not to create a loop.
public static function onEditFormPreloadText(string &$text, Title &$title ) {
global $wgOut;
if ( isset( $_GET["MalakHere"] ) ) {
return true;
}
$pos = strpos($text, "[[Category:Malak]]");
if ($pos) {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlTitle = urlencode($_GET["title"]);
$newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
$newTitle = self::newTitlePre() . $title->prefixedText;
$url = $newURL . "&title=" . $newTitle;
return $wgOut->redirect($url);
}
return true;
}

Still have not found the proper way to do this, but came up with a work around (hackery) which works for my needs.
Using the onEditFormPreloadText hook, change the url and added a new parameter ('MalakHere'), edited the 'title' parameter to the altered title, then do a redirect with the new page name. In the hook function there is a check for the 'MalakHere' parameter, if found (only cause of redirect) then it will exit the function so not to create a loop.
public static function onEditFormPreloadText(string &$text, Title &$title ) {
global $wgOut;
if ( isset( $_GET["MalakHere"] ) ) {
return true;
}
$pos = strpos($text, "[[Category:Malak]]");
if ($pos) {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlTitle = urlencode($_GET["title"]);
$newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
$newTitle = self::newTitlePre() . $title->prefixedText;
$url = $newURL . "&title=" . $newTitle;
return $wgOut->redirect($url);
}
return true;
}

Related

how to use searchmailbox() to search emails by passing date in the criteria of this method?

This is my function and in this line of code * $mailIds = $mailbox->searchMailBox(); * i'm facing problem .. i want to search latest email but if i write anything in this method i'm facing the syntax problem or the blank page. please anyone can help me in solving this problem?
public function actionCreate1()
{
$imapConnection = new ImapConnection();
$imapConnection->imapPath = '{imap.gmail.com:993/imap/ssl}INBOX';
$imapConnection->imapLogin = 'example#gmail.com';
$imapConnection->imapPassword = 'password';
$imapConnection->serverEncoding = 'encoding'; // utf-8 default.
$imapConnection->attachmentsDir = '/';
$imapConnection->decodeMimeStr = true;
$mailbox = new Mailbox($imapConnection);
$mailbox->readMailParts = false;
$mailIds = $mailbox->searchMailBox();
foreach($mailIds as $mailId)
{
// Returns Mail contents
$mail = $mailbox->getMail($mailId);
// Read mail parts (plain body, html body and attachments
$mailObject = $mailbox->getMailParts($mail);
// Array with IncomingMail objects
echo '<pre>';
print_r($mailObject);
// Returns mail attachements if any or else empty array
$attachments = $mailObject->getAttachments();
foreach($attachments as $attachment){
echo ' Attachment:' . $attachment->name . PHP_EOL;
// Delete attachment file
unlink($attachment->filePath);
}
}}

mkdir(): File existed (Yii2)

I am getting this error when trying to create new directory. What I don't understand is that when I use $folderGallery = mkdir($dir.$modelGallery->gallery_id, 0777, true);, it does not work, but when I change to $modelGallery->gallery_name, it is successfully created.
$session = Yii::$app->session;
$modelGallery= new Gallery();
//die(count($modelEulogy));
if ($modelGallery->load(Yii::$app->request->post()))
{
if($modelGallery->validate())
{
$dir = 'img/'.$session['UserID'].'/album/';
//die($modelGallery->gallery_id);
if(!file_exists($dir))
$folderGallery = mkdir($dir.$modelGallery->gallery_id, 0777, true);
else
$folderGallery = mkdir($dir.$modelGallery->gallery_id, 0777, true);
//$model->gallery_id = $id;
$modelGallery->user_id = $session['UserID'];
$modelGallery->date = date("Y-m-d H:i:s");
$modelGallery->save();
}
return $this->redirect(['index', 'gallery_id'=>$id]);
}
You must check the existing directory
$path = $dir.$modelGallery->gallery_id;
if (!is_dir($path)) {
mkdir($dir.$modelGallery->gallery_id, 0777, true);
}
You may use FileHelper::createDirectory() - it will do any necessary checks for you. You should also use absolute paths to avoid ambiguous path resolution:
$dir = '#webroot/img/'.$session['UserID'].'/album/';
FileHelper::createDirectory(Yii::getAlias($dir . $modelGallery->gallery_id, 0777, true));

List of files from my google drive

I am writing PHP script which get files from my Google Drive folder and write list of them with download links on my website, but can not find solution which take files from my folder. Every solution I found need sign up from user, that is viewing page and get list of files from his google drive. Can anyone help me with solution?
Here is my code.
function printFilesInFolder($service, $folderId) {
$pageToken = NULL;
do {
try {
$parameters = array();
$parameters = array(
'q' => "'0B5NCdsbrL1VfQ00xY3pFS3BtOE0' in parents"
);
$children = $service->files->listFiles($parameters);
var_dump($children);
foreach ($children->getFiles() as $child) {
print 'File Id: ' . $child->getId();
}
$pageToken = $children->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
}
$client = new Google_Client();
$client->setApplicationName("Web client 1");
$client->setClientId('CLIENTID');
$client->setClientSecret('SECRET');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setRedirectUri('http://localhost/googledrive/drive/drive.php');
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
$ret = printFilesInFolder($service,"FOLDERID");
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
But i still dont getting right data.
Second think is, that i want to remove need of authentication on every refresh of page, but i dont know how to do that.

Geolocation Redirect to certain webpage

I'm at a loss here. I've found all the HTML5 geolocation items to detect user location. But what I need to do is redirect them to the nearest location webpage. So if they are in/near San Antonio, maybe within a certain range (50 miles), they will be sent to the /san-antonio/ page on the site. Same would go for other locations around the USA. And if they do no have geolocation permissions turned on, they get directed to the generic /locations/ page.
I've found this basic code for getting the position:
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Where to go from here is a gray area. I thought this would be easy and easy google search, but i've come up with nothing.
Any help would be awesome since I just spent 5 hours trying to figure it out and have come up with nothing.
EDIT:* After searching our entire server for the word geolocation, I just found this in an old client theme, but i tested it and it doesn't give me the correct location. I don't know if it has something to do w/the where.yahoo api which isn't functional anymore. In the header.php file there is:
if (geo_position_js.init()) {
geo_position_js.getCurrentPosition(success, null);
}
function lookup_location() {
geo_position_js.getCurrentPosition(success, show_map_error);
}
function success(loc) {
url='http://www.websiteexample.com/location/?long='+loc.coords.longitude+'&lat='+loc.coords.latitude;
location.href=url;
}
function show_map_error() {
}
Then in the functions.php there is this:
function calc_distance($point1, $point2) {
$radius = 3958; // Earth's radius (miles)
$deg_per_rad = 57.29578; // Number of degrees/radian (for conversion)
$distance = ($radius * pi() * sqrt(
($point1['lat'] - $point2['lat'])
* ($point1['lat'] - $point2['lat'])
+ cos($point1['lat'] / $deg_per_rad) // Convert these to
* cos($point2['lat'] / $deg_per_rad) // radians for cos()
* ($point1['long'] - $point2['long'])
* ($point1['long'] - $point2['long'])
) / 180);
return $distance; // Returned using the units used for $radius.
}
function get_longlat($address) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://where.yahooapis.com/geocode?appid=8gkElW6o&q='.urlencode($address));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$content = curl_exec($ch);
curl_close($ch);
$loc = simplexml_load_string($content)->Result;
$geo['lat'] = (string)$loc->latitude;
$geo['long'] = (string)$loc->longitude;
return $geo;
}
function redirect_to_nearest($clientlong, $clientlat) {
$clientgeo['long'] = $clientlong;
$clientgeo['lat'] = $clientlat;
$query = new WP_Query( array( 'post_type' => 'location' ) );
while ( $query->have_posts() ) : $query->the_post();
$custom = get_post_custom();
$slug = basename(get_permalink());
$location[$slug]['permalink'] = get_permalink();
$location[$slug]['address'] = $custom[google_maps_address][0];
$location[$slug]['geo'] = get_longlat($location[$slug][address]);
$location[$slug]['distance'] = calc_distance($clientgeo, $location[$slug]['geo']);
endwhile;
wp_reset_postdata();
usort($location,"cmp");
return $location[0]['permalink'];
}
function cmp($a, $b) {
if ($a['distance'] == $b['distance']) { return 0; }
return ($a['distance'] < $b['distance']) ? -1 : 1;
}
Then in the actual custom post type archive page there is this:
if(isset($_GET[long]) && isset($_GET[lat])) {
$redirectto = redirect_to_nearest($_GET[long], $_GET[lat]);}
if(isset($redirectto) && preg_match("/http:\/\/www.websiteexample.com\/location\/.*/i", $redirectto)) {
header( "HTTP/1.1 303 See Other" );
header( "Location: $redirectto" );
}
I thought I'd had struck gold. But I was wrong :-/

codeigniter - convert html to pdf

I have a little problem. I have html page and I want to convert to pdf. My index page has a list that will get to the database and click on "Download PDF", I put this list in a PDF file.
My controller:
<?php
class pdf_c extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper(array('url', 'mediatutorialpdf'));
}
function index($download_pdf = ''){
$ret = '';
$ID = 1;
$pdf_filename = 'user_info_'.$ID.'.pdf';
$link_download = ($download_pdf == TRUE)?'':anchor(base_url().'index.php/true', 'Download PDF');
$query = $this->db->query("SELECT * FROM `ci_pdf_user` WHERE `id` = '{$ID}' LIMIT 1");
if($query->num_rows() > 0)
{
$user_info = $query->row_array();
}
$data_header = array(
'title' => 'Convert codeigniter to pdf'
);
$data_userinfo = array(
'user_info' => $user_info,
'link_download' => $link_download
);
$header = $this->load->view('header',$data_header, true);
$user_info = $this->load->view('user_table', $data_userinfo, true);
$footer = $this->load->view('footer','', true);
$output = $header.$user_info.$footer;
if($download_pdf == TRUE)
{
generate_pdf($output, $pdf_filename);
}
else
{
echo $output;
}
}
}
?>
The problem is when I click the button "Download PDF" should redirect me to the function index () and get the $ download_pdf = true. And so called generate_pdf function () that will generate the PDF.
I think the problem is in the variable $ link_download, but can not solve the problem.
Thanks
I think that you could try with:
function index(pdf = 0)...
Then check that optional parameter with:
$pdf = $this->uri->segment(2, 0); //not sure, should be 2? try it...`
And then, if $pdf=='1' (send nummber rather than string 'true') ...etc,etc...