mkdir(): File existed (Yii2) - 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));

Related

MediaWiki - Hook to edit/alter page title on creation

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;
}

Google Drive API: Get titles of the parent folders

I have this code from google:
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
I know i can do this:
$files = retrieveAllFiles($service);
foreach($files as $file){
$id = $file->getId();
$title = $file->getTitle()
}
We can also fetch the parents of the file by:
foreach($files as $file){
$parents = $file->getParents();
}
Is it possible to get the titles of the parent folders without calling another request? like:
foreach($files as $file){
$parents = $file->getParents();
foreach($parents as $parent){
$parent_title = $parent->getTitle(); //NOT EXISTING
}
}
I know that it throws an error but is there other alternative to achieve this requirement?
No it's not possible. Embedding the meta data of one file within another would make for an ugly API. The Drive API is a very clean REST API, which means that you'll need to make multiple requests.
I've edited your question slightly to clarify that a file can have more than one parent.

Memory Efficient reading + writing of .csv and .xlsx data

I am looking to implement memory efficient reading and writing of .xlsx/.csv files.
I am currently using phpExcel and am having trouble with large files. (Known issue)
I found the following library for reading: https://github.com/nuovo/spreadsheet-reader
This seems that it will work.
For writing files currently I create an array and then loop the array to output the file. Is this why it uses a lot of memory? What is the best way to not use a lot of memory when writing csv/xlsx when getting data from mysql database using code igniter?
This is what I do now:
/* added for excel expert */
function excel_export() {
$data = $this->Customer->get_all($this->Customer->count_all())->result_object();
$this->load->helper('report');
$rows = array();
$header_row = $this->_excel_get_header_row();
$header_row[] = lang('customers_customer_id');
$rows[] = $header_row;
foreach ($data as $r) {
$row = array(
$r->first_name,
$r->last_name,
$r->email,
$r->phone_number,
$r->address_1,
$r->address_2,
$r->city,
$r->state,
$r->zip,
$r->country,
$r->comments,
$r->account_number,
$r->taxable ? 'y' : '',
$r->company_name,
$r->person_id
);
$rows[] = $row;
}
$content = array_to_spreadsheet($rows);
force_download('customers_export.'.($this->config->item('spreadsheet_format') == 'XLSX' ? 'xlsx' : 'csv'), $content);
exit;
}
function array_to_spreadsheet($arr)
{
$CI =& get_instance();
$objPHPExcel = new PHPExcel();
//Default all cells to text
$objPHPExcel->getDefaultStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
for($k = 0;$k < count($arr);$k++)
{
for($j = 0;$j < count($arr[$k]); $j++)
{
$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($j, $k+1, $arr[$k][$j]);
}
}
if ($CI->config->item('spreadsheet_format') == 'XLSX')
{
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
}
else
{
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
}
ob_start();
$objWriter->save('php://output');
$excelOutput = ob_get_clean();
return $excelOutput;
}

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...

Show Chrome extension version on options page?

I've got my manifest file with my version number and an options page. Is there a way to display the installed version and latest available version on the options page without needing to do it manually?
You can get the current version of your extension using chrome.runtime.getManifest().version.
In order to get the "latest version" of your extension, you need to download updates.xml, and extract the version number:
var extensionID = chrome.i18n.getMessage('##extension_id');
var currentVersion = chrome.runtime.getManifest().version;
var url = 'https://clients2.google.com/service/update2/crx?x=id%3D' + extensionID + '%26v%3D' + currentVersion;
var x = new XMLHttpRequest();
x.open('GET', url);
x.onload = function() {
var doc = new DOMParser().parseFromString(x.responseText, 'text/xml');
// Get and show version info. Exercise for the reader.
};
x.send();
If you want to customize your request with PHP, avoiding to update the extension every time Google changes the API, I suggest the following
update_info.php (from your site):
<?php
$last_ver;
$googleupdate = 'http://clients2.google.com/service/update2/crx?response=updatecheck&x=id%3D__id__%26uc';
$ver = $_POST['ver'];
$id = $_POST['id'];
//filter/control for post request very fast for this example
if(isset($id) && isset($ver)){
if(strlen($id)>0){
$urlupdate = str_replace('__id__', $id, $googleupdate);
$last_ver = _GetLastVersion($urlupdate);
if($last_ver>0 && $last_ver>$ver){
echo 'New version available, v'.$last_ver;
}else{
echo 'Your version is update';
}
}else{
echo 'Insert id for response';
}
}else{
echo 'Insert data for response';
}
//if your server do not connect with file_get_contents() use this function
function getContent ($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
$info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($output === false || $info != 200) {
$output = null;
}
return $output;
}
//this function return 0 if error or not content load
function _GetLastVersion($url){
try {
$last=0;
//if you have proble you can use getContent($url)
$xmlcontent = file_get_contents($url);
if($xmlcontent){
$doc = new DOMDocument();
$doc->loadXML($xmlcontent);
$items = $doc->getElementsByTagName('updatecheck');
foreach ($items as $item) {
if($item->getAttribute('version')>0){
return $item->getAttribute('version');
}
}
return $last;
}else{
return 0;
}
} catch (Exception $e) {
return 0;
}
}
?>
in your extension send request to your webpage, now you are in control of your script, you can decide which answer back every time