/**
 * Loeschen eines Bildes
 */
 function Joom_User_DeletePic()
 {
     $config = Joom_getConfig();
     $mainframe =& JFactory::getApplication('site');
     $database =& JFactory::getDBO();
     $user =& JFactory::getUser();
     jimport('joomla.filesystem.file');
     if ($this->userid != $user->get('id') && !$this->adminlogged) {
         $mainframe->redirect(JRoute::_($this->userpanel_url . _JOOM_ITEMID, false), JText::_('JGS_ALERT_NOT_ALLOWED_DELETE_PICTURE'));
     }
     if ($this->picid) {
         $row = new mosjoomgallery($database);
         $row->load($this->picid);
         $catpath = Joom_GetCatPath($row->catid);
         //Detailbild loeschen
         if (JFile::delete(JPATH_ROOT . DS . $config->jg_pathimages . DS . $catpath . $row->imgfilename)) {
             //Thumb loeschen
             if (JFile::delete(JPATH_ROOT . DS . $config->jg_paththumbs . DS . $catpath . $row->imgthumbname)) {
                 // ggf. Originalbild loeschen
                 if (file_exists(JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $row->imgfilename)) {
                     JFile::delete(JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $row->imgfilename);
                 }
                 //Kommentare loeschen
                 $database->setQuery(" DELETE \n                                FROM \n                                  #__joomgallery_comments\n                                WHERE \n                                  cmtpic={$this->picid}\n                              ");
                 if (!$database->query()) {
                     echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
                 }
                 //Namensschilder loeschen
                 $database->setQuery(" DELETE \n                                FROM \n                                  #__joomgallery_nameshields\n                                WHERE \n                                  nid = {$this->picid}\n                              ");
                 if (!$database->query()) {
                     echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
                 }
                 //Bild loeschen
                 $database->setQuery(" DELETE \n                                FROM \n                                  #__joomgallery\n                                WHERE \n                                  id = {$this->picid}\n                              ");
                 if (!$database->query()) {
                     echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
                 }
             } else {
                 die(JText::_('JGS_COULD_NOT_DELETE_THUMBNAIL_FILE'));
             }
         } else {
             die(JText::_('JGS_COULD_NOT_DELETE_PICTURE_FILE'));
         }
         $mainframe->redirect(JRoute::_($this->userpanel_url . _JOOM_ITEMID, false), JText::_('JGS_ALERT_PICTURE_AND_COMMENTS_DELETED'));
     }
 }
    /**
    * Single upload
    * The user choose single picture files and upload them
    * concurrent uploads can be modified in backend
    * @param Category ID
    */
    function Upload_Singles($catid)
    {
        $config = Joom_getConfig();
        $mainframe =& JFactory::getApplication('site');
        $database =& JFactory::getDBO();
        $user =& JFactory::getUser();
        jimport('joomla.filesystem.file');
        $debugoutput = '';
        //no user logged in
        if (!$user->get('id')) {
            $mainframe->redirect(JRoute::_('index.php?option=com_joomgallery' . _JOOM_ITEMID, false), JText::_('JGS_YOU_ARE_NOT_LOGGED'));
        }
        $catpath = Joom_GetCatPath($catid);
        $debugoutput .= '<p />';
        for ($i = 0; $i < $config->jg_maxuploadfields; $i++) {
            $screenshot = $this->arrscreenshot["tmp_name"][$i];
            $screenshot_name = $this->arrscreenshot["name"][$i];
            $screenshot_filesize = $this->arrscreenshot["size"][$i];
            $ii = $i + 1;
            //Any picture entry at position?
            //(4=UPLOAD_ERR_NO_FILE constant since PHP 4.3.0)
            //if not continue with next entry
            if ($this->arrscreenshot['error'][$i] == 4) {
                continue;
            }
            //Check for path exploits, and replace spaces
            $screenshot_name = Joom_FixFilename($screenshot_name);
            // Get extension
            $tag = strtolower(JFile::getExt($screenshot_name));
            if ($config->jg_useruploadnumber == 1) {
                $filecounter = $i + 1;
                $praefix = substr($screenshot_name, 0, strpos(strtolower($screenshot_name), $tag) - 1);
                $newfilename = $this->Upload_GenFilename($praefix, $tag, $filecounter);
            } else {
                $newfilename = $this->Upload_GenFilename($screenshot_name, $tag);
            }
            //Picture size must not exceed the setting in backend
            //except for Admin/SuperAdmin
            if ($screenshot_filesize > $config->jg_maxfilesize && !$this->adminlogged) {
                $debugoutput .= JText::_('JGS_ALERT_MAX_ALLOWED_FILESIZE') . " " . $config->jg_maxfilesize . " " . JText::_('JGS_ALERT_BYTES');
                continue;
            }
            //Check for right format
            if ($tag == 'jpeg' || $tag == 'jpg' || $tag == 'jpe' || $tag == 'gif' || $tag == 'png') {
                $debugoutput .= '<hr />Position: ' . $ii . '<br />';
                $debugoutput .= $ii . ". " . $screenshot_name . "<br />";
                //if picture already exists
                if (file_exists(JPath::clean(JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $newfilename))) {
                    $debugoutput .= JText::_('JGS_ALERT_SAME_PICTURE_ALREADY_EXIST');
                    continue;
                }
                // We'll assume that this file is ok because with open_basedir,
                // we can move the file, but may not be able to access it until it's moved
                $returnval = JFile::upload($screenshot, JPATH_ROOT . DS . $config->jg_pathoriginalimages . DS . $catpath . $newfilename);
                if (!$returnval) {
                    $debugoutput .= JText::_('JGS_WRONG_FILENAME') . ': ' . JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename . '<br />';
                    continue;
                }
                $debugoutput .= JText::_('JGS_UPLOAD_COMPLETE') . '...<br />';
                if (!($img_info = getimagesize(JPath::clean(JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename)))) {
                    // getimagesize didn't find a valid image or this is
                    // some sort of hacking attempt
                    JFile::delete(JPATH_ROOT . DS . $config->jg_pathoriginalimages . DS . $catpath . $newfilename);
                    jexit();
                }
                //check the possible available memory for picture resizing
                //if not available echo error message and continue with next picture
                if ($this->Upload_CheckMemory($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . DS . $catpath . $newfilename, $tag) == false) {
                    $this->Upload_Rollback($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, null, null);
                    continue;
                }
                // create thumb
                $returnval = Joom_ResizeImage($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $newfilename, $config->jg_useforresizedirection, $config->jg_thumbwidth, $config->jg_thumbheight, $config->jg_thumbcreation, $config->jg_thumbquality);
                if (!$returnval) {
                    $debugoutput .= JText::_('JGS_WRONG_FILENAME') . ': ' . JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $newfilename;
                    $this->Upload_Rollback($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, null, null);
                    continue;
                }
                $debugoutput .= JText::_('JGS_THUMBNAIL_CREATED') . '...<br />';
                //create detail picture
                if ($config->jg_resizetomaxwidth && ($config->jg_special_gif_upload == 0 || $this->create_special_gif != 1 || $tag != 'gif' && $tag != 'png')) {
                    $returnval = Joom_ResizeImage($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $newfilename, false, $config->jg_maxwidth, false, $config->jg_thumbcreation, $config->jg_picturequality, true);
                    if (!$returnval) {
                        $debugoutput .= JText::_('JGS_WRONG_FILENAME') . ': ' . JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $newfilename;
                        $this->Upload_Rollback($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, null, JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $newfilename);
                        continue;
                    }
                    $debugoutput .= JText::_('JGS_RESIZED_TO_MAXWIDTH') . '<br />';
                } else {
                    $returnval = JFile::copy($config->jg_pathoriginalimages . $catpath . $newfilename, $config->jg_pathimages . $catpath . $newfilename, JPATH_ROOT);
                    if (!$returnval) {
                        $debugoutput .= JText::_('JGS_PROBLEM_COPYING ') . $config->jg_pathimages . $catpath . $newfilename;
                        $this->Upload_Rollback($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, null, JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $newfilename);
                        continue;
                    }
                }
                if ($config->jg_delete_original_user == 1 || $config->jg_delete_original_user == 2 && $this->original_delete == 1) {
                    if (JFile::delete(JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename)) {
                        $debugoutput .= JText::_('JGS_ORIGINAL_DELETED') . '<br />';
                    } else {
                        $debugoutput .= JText::_('JGS_PROBLEM_DELETING_ORIGINAL') . ' - ' . JText::_('JGS_CHECK_PERMISSIONS');
                        $this->Upload_Rollback($debugoutput, null, JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $newfilename, JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $newfilename);
                        continue;
                    }
                }
                $ordering = $this->Upload_GetOrdering($config->jg_uploadorder, $catid);
                $row = new mosjoomgallery($database);
                if (!$row->bind($_POST, JText::_('JGS_APPROVED_OWNER_PUBLISHED'))) {
                    $this->Upload_Rollback($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $newfilename, JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $newfilename);
                    echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
                    jexit();
                }
                $row->imgdate = mktime();
                $row->owner = $user->get('id');
                $row->published = 1;
                //Upload from admin/superadmin are approved
                if ($config->jg_approve == 1 && !$this->adminlogged) {
                    $row->approved = 0;
                } else {
                    $row->approved = 1;
                }
                $row->imgfilename = $newfilename;
                $row->imgthumbname = $newfilename;
                $row->useruploaded = 1;
                $row->ordering = $ordering;
                //Wenn im Backend die Vergabe von lfd. Nummern eingestellt wurde
                //wird dem Bildtitel die lfd. Nummer (+1) hinzugefügt
                if ($config->jg_useruploadnumber) {
                    $row->imgtitle = $row->imgtitle . '_' . $filecounter;
                }
                if (!$row->store()) {
                    $this->Upload_Rollback($debugoutput, JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $newfilename, JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $newfilename, JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $newfilename);
                    $debugoutput .= $row->getError();
                    continue;
                } else {
                    // E-Mail ueber ein neues Bild an die User, die global als User Email-Empfang
                    // erlaubt haben TODO -> In Backend-Konfig einstellen bzw. deaktivieren
                    /* TODO
                       // portierung: /administrator/components/com_messages/tables/message.php anstatt administrator/components/com_messages/messages.class.php
                       require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_messages'.DS.'tables'.DS.'message.php' );
                       $database->setQuery("SELECT id
                           FROM #__users
                           WHERE sendEmail='1'");
                       $users = $database->loadResultArray();
                       foreach ($users as $user_id) {
                         $msg = new TableMessage($database); // portierung: TableMessage anstatt mosMessage
                         $msg->send($user->get('id'),
                         $user_id,
                         JText::_('JGS_NEW_PICTURE_UPLOADED'),
                         sprintf( JText::_('JGS_NEW_CONTENT_SUBMITTED') . " %s " . JText::_('JGS_TITLED') ." %s.",
                         $user->get('username'),
                         $row->imgtitle));
                       }
                       */
                    $debugoutput .= JText::_('JGS_ALERT_PICTURE_SUCCESSFULLY_ADDED') . '<br />';
                    $debugoutput .= JText::_('JGS_NEW_FILENAME') . ': ' . $newfilename . '<br /><br />';
                }
            } else {
                $debugoutput .= JText::_('JGS_ALERT_INVALID_IMAGE_TYPE');
                continue;
            }
        }
        echo $debugoutput;
        ?>
    <p>
      <img src="<?php 
        echo _JOOM_LIVE_SITE . 'components/com_joomgallery/assets/images/arrow.png';
        ?>
" class="pngfile jg_icon" alt="arrow" />
      <a href="<?php 
        echo JRoute::_('index.php?option=com_joomgallery&func=showupload' . _JOOM_ITEMID);
        ?>
">
        <?php 
        echo JText::_('JGS_MORE_UPLOADS');
        ?>
      </a>
    </p>
    <p>
      <img src="<?php 
        echo _JOOM_LIVE_SITE . 'components/com_joomgallery/assets/images/arrow.png';
        ?>
" class="pngfile jg_icon" alt="arrow" />
      <a href="<?php 
        echo JRoute::_('index.php?option=com_joomgallery&func=userpanel' . _JOOM_ITEMID);
        ?>
">
        <?php 
        echo JText::_('JGS_BACK_TO_USER_PANEL');
        ?>
      </a>
    </p>
    <p>
      <img src="<?php 
        echo _JOOM_LIVE_SITE . 'components/com_joomgallery/assets/images/arrow.png';
        ?>
" class="pngfile jg_icon" alt="arrow" />
      <a href="<?php 
        echo JRoute::_('index.php?option=com_joomgallery&startpage=1' . _JOOM_ITEMID);
        ?>
">
        <?php 
        echo JText::_('JGS_BACK_TO_GALLERY');
        ?>
      </a>
    </p>
<?php 
    }
 /**
  * Move pictures
  * @param array $id: id's of pictures to be moved
  */
 function Joom_SaveMovePicture($id)
 {
     $config = Joom_getConfig();
     $mainframe =& JFactory::getApplication('administrator');
     $database =& JFactory::getDBO();
     $user =& JFactory::getUser();
     jimport('joomla.filesystem.file');
     //TODO: error messages
     //id of destination category
     $pictureMove = JRequest::getInt('catid', '', 'post');
     //when no category chosen before
     if (!$pictureMove || $pictureMove == 0) {
         //error message and abort
         echo "<script> alert('" . JText::_('JGA_ALERT_PLEASE_SELECT_CATEGORY', true) . "');\n              window.history.go(-1);</script>\n";
         exit;
         //category chosen
     } else {
         //and the array contains picture
         if (count($id)) {
             //create a new array which contains the succesful moved pictures
             $successids = array();
             //loop through array
             for ($i = 0; $i < count($id); $i++) {
                 //database query for picture title and the catid from source category
                 $database->setQuery("SELECT id, catid, imgfilename, imgthumbname\n              FROM #__joomgallery\n              WHERE id = {$id[$i]}");
                 //if succesful
                 if ($database->query()) {
                     //write in array
                     $rows = $database->loadObjectList();
                     $row = $rows[0];
                     //write to class members
                     $this->imgfilename = $row->imgfilename;
                     $this->imgthumbname = $row->imgthumbname;
                     $old_catid = $row->catid;
                     //catpath for new category
                     $catpath = Joom_GetCatPath($pictureMove);
                     //catpath for old category
                     $catpath_ori = Joom_GetCatPath($row->catid);
                     //query if there are entries in which the picture file to move
                     //is assigned and count them
                     $database->setQuery("SELECT COUNT(id)\n                FROM #__joomgallery\n                WHERE imgthumbname = '" . $this->imgthumbname . "'\n                AND id != '" . $id[$i] . "'\n                AND catid = '" . $old_catid . "'");
                     $count2 = $database->loadResult();
                     //check if thumbnail already exists in source directory and not
                     //exists already in destination
                     //otherwise the file will not be copied
                     if (JFile::exists(JPATH_ROOT . DS . $config->jg_paththumbs . $catpath_ori . $this->imgthumbname) && !JFile::exists(JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $this->imgthumbname)) {
                         //if there is no picture remaining in source directory
                         //which uses the picture
                         if ($count2 < 1) {
                             //move the thumbnail
                             $result = JFile::move($config->jg_paththumbs . $catpath_ori . $this->imgthumbname, $config->jg_paththumbs . $catpath . $this->imgthumbname, JPATH_ROOT);
                             //otherwise...
                         } else {
                             //copy the thumbnail and let it remain in source
                             $result = JFile::copy($config->jg_paththumbs . $catpath_ori . $this->imgthumbname, $config->jg_paththumbs . $catpath . $this->imgthumbname, JPATH_ROOT);
                         }
                         //if not succesful error message and abort
                         if (!$result) {
                             Joom_AlertErrorMessages(0, 0, 0, $successids);
                         }
                         //set control variable according to succesful move/copy
                         $thumb = 1;
                         //not succesful
                     } else {
                         $thumb = 0;
                     }
                     //same procedure with detail
                     //in case of error call previous copy/move of
                     $database->setQuery("SELECT COUNT(id)\n                FROM #__joomgallery\n                WHERE imgfilename = '" . $this->imgfilename . "'\n                AND id != '" . $id[$i] . "'\n                AND catid = '" . $old_catid . "'");
                     $count = $database->loadResult();
                     $imgsource = JPATH_ROOT . DS . $config->jg_pathimages . $catpath_ori . $this->imgfilename;
                     $imgdest = JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $this->imgfilename;
                     if (JFile::exists($imgsource) && !JFile::exists($imgdest)) {
                         if ($count < 1) {
                             $result2 = JFile::move($catpath_ori . $this->imgfilename, $catpath . $this->imgfilename, JPATH_ROOT . DS . $config->jg_pathimages);
                         } else {
                             $result2 = JFile::copy($catpath_ori . $this->imgfilename, $catpath . $this->imgfilename, JPATH_ROOT . DS . $config->jg_pathimages);
                         }
                         if (!$result2) {
                             if ($thumb == 1) {
                                 if ($count2 < 1) {
                                     JFile::move($config->jg_paththumbs . $catpath . $this->imgthumbname, $config->jg_paththumbs . $catpath_ori . $this->imgthumbname, JPATH_ROOT);
                                 } else {
                                     JFile::delete(JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $this->imgthumbname);
                                 }
                             }
                             Joom_AlertErrorMessages(0, 0, 0, $successids);
                         }
                         $picture = 1;
                     } else {
                         $picture = 0;
                     }
                     if (JFile::exists(JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath_ori . $this->imgfilename) && !JFile::exists(JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $this->imgfilename)) {
                         if ($count < 1) {
                             $result3 = JFile::move($catpath_ori . $this->imgfilename, $catpath . $this->imgfilename, JPATH_ROOT . DS . $config->jg_pathoriginalimages);
                         } else {
                             $result3 = JFile::copy($catpath_ori . $this->imgfilename, $catpath . $this->imgfilename, JPATH_ROOT . DS . $config->jg_pathoriginalimages);
                         }
                         if (!$result3) {
                             if ($thumb == 1) {
                                 if ($count2 < 1) {
                                     JFile::move($config->jg_paththumbs . $catpath . $this->imgthumbname, $config->jg_paththumbs . $catpath_ori . $this->imgthumbname, JPATH_ROOT);
                                 } else {
                                     JFile::delete(JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $this->imgthumbname);
                                 }
                             }
                             if ($picture == 1) {
                                 if ($count < 1) {
                                     JFile::move($config->jg_pathimages . $catpath . $this->imgfilename, $config->jg_pathimages . $catpath_ori . $this->imgfilename, JPATH_ROOT);
                                 } else {
                                     JFile::delete(JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $this->imgfilename);
                                 }
                             }
                             Joom_AlertErrorMessages(0, 0, 0, $successids);
                         }
                     }
                     //if database query not succesful error message and abort
                 } else {
                     echo "<script> alert('" . $database->getErrorMsg() . "');\n                  window.history.go(-1); </script>\n";
                 }
                 //add the succesful processed picture (id) to array
                 array_push($successids, $id[$i]);
                 //if all folder operations for the picture succesful
                 //modify the database entry
                 $pic = new mosjoomgallery($database);
                 //call Joom_MovePictures
                 $pic->Joom_MovePictures($id[$i], $pictureMove);
                 //new object from mosCatgs
                 $cat = new mosCatgs($database);
                 $cat->load($pictureMove);
             }
         }
         //construct the success message
         //count of moved pictures
         $total = count($successids);
         //TODO: MSG 'x Bilder verschoben zu y' anpassen
         $msg = $total . " Pictures moved to " . $cat->name;
         //redirect to picture manager with success message
         $mainframe->redirect('index.php?option=' . _JOOM_OPTION . '&act=pictures', $msg);
     }
 }
/**
 * The following function was taken from admin.frontpage.php Joomla 1.0
 * @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
 * modification aHa - additional saveorder for categories
 * @see admin.joomgallery.php // only backend
 * @param int $cid
 * @param unknown_type $catg
 */
function Joom_SaveOrder(&$cid, &$catg)
{
    $mainframe =& JFactory::getApplication('administrator');
    $database =& JFactory::getDBO();
    $returntask = Joom_mosGetParam('returntask', null);
    if ($returntask == 'pictures') {
        $total = count($cid);
        $order = Joom_mosGetParam('order', array(0), 'post');
        for ($i = 0; $i < $total; $i++) {
            //get catid
            $database->setQuery("SELECT catid\n          FROM #__joomgallery\n          WHERE id={$cid[$i]}");
            $piccatid = $database->loadResult();
            $query = "UPDATE #__joomgallery\n          SET ordering = {$order[$i]}\n          WHERE id = {$cid[$i]}";
            $database->setQuery($query);
            if (!$database->query()) {
                echo "<script> alert('" . $database->getErrorMsg() . "');\n              window.history.go(-1); </script>\n";
                exit;
            }
            // update ordering
            $row = new mosjoomgallery($database);
            $row->load($cid[$i]);
            $row->reorder('catid=' . $piccatid);
        }
        $mainframe->redirect('index.php?option=' . _JOOM_OPTION . '&act=pictures', JText::_('JG_NEW_ORDERING_SAVED'));
    } else {
        $total = count($catg);
        $order = Joom_mosGetParam('order', array(0), 'post');
        for ($i = 0; $i < $total; $i++) {
            $query = "UPDATE #__joomgallery_catg\n          SET ordering = {$order[$i]}\n          WHERE cid = {$catg[$i]}";
            $database->setQuery($query);
            if (!$database->query()) {
                echo "<script> alert('" . $database->getErrorMsg() . "');\n              window.history.go(-1); </script>\n";
                exit;
            }
            // update ordering
            $row = new mosjoomgallery($database);
            $row->load($catg[$i]);
            $row->reorder('');
        }
        $mainframe->redirect('index.php?option=' . _JOOM_OPTION . '&act=categories', JText::_('JG_NEW_ORDERING_SAVED'));
    }
}
/**
 * recreates thumbnails of the selected images
 * if original image is existent, detail image will be recreated, too.
 */
function Joom_Recreate()
{
    jimport('joomla.filesystem.file');
    $mainframe =& JFactory::getApplication('administrator');
    $database =& JFactory::getDBO();
    $config = Joom_GetConfig();
    $cids = $mainframe->getUserStateFromRequest('joom.recreate.ids', 'id', array(), 'array');
    $thumb_count = $mainframe->getUserState('joom.recreate.thumbcount');
    $img_count = $mainframe->getUserState('joom.recreate.imgcount');
    $row = new mosjoomgallery($database);
    // before first loop check for selected images
    if (is_null($thumb_count) and !count($cids)) {
        return array(false, JText::_('JGA_NO_IMAGES_SELECTED'));
    }
    //Check the maximum execution time of the script
    //set secure setting of the real execution time
    $max_execution_time = @ini_get('max_execution_time');
    //try to set the max execution time to 60s if lower than
    //if not succesful the return value will be the old time, so use this
    if ($max_execution_time < 60) {
        #@ini_set('max_execution_time','60');
        $max_execution_time = @ini_get('max_execution_time');
    }
    $maxtime = (int) $max_execution_time * 0.8;
    $starttime = time();
    $debugoutput = '';
    //loop through selected images
    foreach ($cids as $key => $cid) {
        $row->load($cid);
        //catpath for category
        $catpath = Joom_GetCatPath($row->catid);
        $orig = JPATH_ROOT . DS . $config->jg_pathoriginalimages . $catpath . $row->imgfilename;
        $img = JPATH_ROOT . DS . $config->jg_pathimages . $catpath . $row->imgfilename;
        $thumb = JPATH_ROOT . DS . $config->jg_paththumbs . $catpath . $row->imgthumbname;
        //check if there is an original image
        if (JFile::exists($orig)) {
            $orig_existent = true;
        } else {
            //if not, use detail image to create thumbnail
            $orig_existent = false;
            if (JFile::exists($img)) {
                $orig = $img;
            } else {
                JError::raiseWarning(100, JText::sprintf('JGA_IMG_NOT_EXISTENT', $img));
                $mainframe->setUserState('joom.recreate.cids', array());
                $mainframe->setUserState('joom.recreate.count', null);
                return false;
            }
        }
        //TODO: move image into a trash instead of deleting immediately for possible rollback
        JFile::delete($thumb);
        $return = Joom_ResizeImage($debugoutput, $orig, $thumb, $config->jg_useforresizedirection, $config->jg_thumbwidth, $config->jg_thumbheight, $config->jg_thumbcreation, $config->jg_thumbquality);
        if (!$return) {
            JError::raiseWarning(100, JText::sprintf('JGA_COULD_NOT_CREATE_THUMB', $thumb));
            $mainframe->setUserState('joom.recreate.cids', array());
            $mainframe->setUserState('joom.recreate.thumbcount', null);
            $mainframe->setUserState('joom.recreate.imgcount', null);
            return false;
        }
        $mainframe->enqueueMessage(JText::sprintf('JGA_SUCCESSFULLY_CREATED_THUMB', $row->id, $row->imgtitle));
        $thumb_count++;
        if ($orig_existent) {
            //TODO: move image into a trash instead of deleting immediately for possible rollback
            JFile::delete($img);
            $return = Joom_ResizeImage($debugoutput, $orig, $img, false, $config->jg_maxwidth, false, $config->jg_thumbcreation, $config->jg_picturequality, true);
            if (!$return) {
                JError::raiseWarning(100, JText::sprintf('JGA_COULD_NOT_CREATE_IMG', $img));
                $this->_mainframe->setUserState('joom.recreate.cids', array());
                $this->_mainframe->setUserState('joom.recreate.thumbcount', null);
                $this->_mainframe->setUserState('joom.recreate.imgcount', null);
                return false;
            }
        }
        $mainframe->enqueueMessage(JText::sprintf('JGA_SUCCESSFULLY_CREATED_IMG', $row->id, $row->imgtitle));
        $img_count++;
        unset($cids[$key]);
        //check remaining time
        $timeleft = -(time() - $starttime - $maxtime);
        if ($timeleft <= 0 and count($cids)) {
            $mainframe->setUserState('joom.recreate.cids', $cids);
            $mainframe->setUserState('joom.recreate.thumbcount', $thumb_count);
            $mainframe->setUserState('joom.recreate.imgcount', $img_count);
            $mainframe->redirect('index.php?option=' . _JOOM_OPTION . '&task=recreate', JText::_('JGA_REDIRECT'));
        }
    }
    $mainframe->setUserState('joom.recreate.cids', array());
    $mainframe->setUserState('joom.recreate.thumbcount', null);
    $mainframe->setUserState('joom.recreate.imgcount', null);
    return array($thumb_count, $img_count);
}