Example #1
0
 function bindContent($post, $files, $conf, $model, $plugins)
 {
     $app = JFactory::getApplication();
     $this->bind($post);
     if ($this->id == 0) {
         $this->new_ad = true;
     } else {
         $query = "SELECT content FROM #__adsmanager_pending_ads WHERE contentid = {$this->id}";
         $this->_db->setQuery($query);
         $currentpendingchanges = $this->_db->loadResult();
         if ($currentpendingchanges != null) {
             $currentpendingchanges = @json_decode($currentpendingchanges);
             if (isset($currentpendingchanges->published)) {
                 $this->published = $currentpendingchanges->published;
             }
             if (isset($currentpendingchanges->new_ad)) {
                 $this->new_ad = $currentpendingchanges->new_ad;
             }
         }
     }
     $this->data = array();
     $this->errors = array();
     if (function_exists("getMaxCats")) {
         $maxcats = getMaxCats($conf->nbcats);
     } else {
         $maxcats = $conf->nbcats;
     }
     if ($maxcats > 1) {
         $selected_cats = $post["selected_cats"];
         if (!is_array($selected_cats)) {
             $c = array();
             $c[0] = $selected_cats;
             $selected_cats = $c;
         }
         if (count($selected_cats) > $maxcats) {
             $selected_cats = array_slice($selected_cats, 0, $maxcats);
         }
         $this->data['categories'] = $selected_cats;
     } else {
         $category = $post["category"];
         $this->data['categories'] = array();
         $this->data['categories'][0] = intval($category);
     }
     //get fields
     $this->_db->setQuery("SELECT * FROM #__adsmanager_fields WHERE published = 1");
     $fields = $this->_db->loadObjectList();
     foreach ($fields as $key => $field) {
         $fields[$key]->options = json_decode($fields[$key]->options);
     }
     if ($this->_db->getErrorNum()) {
         $this->errors[] = $this->_db->stderr();
         return false;
     }
     $query = "UPDATE #__adsmanager_ads ";
     $bannedwords = str_replace("\r", "", $conf->bannedwords);
     $bannedwords = explode("\n", $bannedwords);
     $replaceword = $conf->replaceword;
     $data['fields'] = array();
     foreach ($fields as $field) {
         //If admin edit only should leave the loop otherwise value is reseted to empty string
         if ($app->isAdmin() == false && @$field->options->edit_admin_only == 1) {
             continue;
         }
         if ($field->type == "multiselect") {
             $value = JRequest::getVar($field->name, array());
             $this->data['fields'][$field->name] = $value;
         } else {
             if ($field->type == "multicheckbox" || $field->type == "multicheckboximage") {
                 $value = $value = JRequest::getVar($field->name, array());
                 $this->data['fields'][$field->name] = $value;
             } else {
                 if ($field->type == "file") {
                     if (isset($files[$field->name]) and !$files[$field->name]['error']) {
                         jimport('joomla.filesystem.file');
                         if (is_file(JPATH_ROOT . "/images/com_adsmanager/files/" . $field->name)) {
                             JFile::delete(JPATH_ROOT . "/images/com_adsmanager/files/" . $field->name);
                         }
                         $filename = $files[$field->name]['name'];
                         $extension = JFile::getExt($filename);
                         $name = md5(rand(1, 100000) . $filename);
                         if (strpos($extension, "php") !== false) {
                             $extension = 'txt';
                         }
                         $filename = $name . "." . $extension;
                         JFile::upload($files[$field->name]['tmp_name'], JPATH_ROOT . "/images/com_adsmanager/files/" . $filename);
                         $this->data['fields'][$field->name] = $filename;
                     } else {
                         if (JRequest::getInt("delete_" . $field->name) == 1) {
                             if (is_file(JPATH_ROOT . "/images/com_adsmanager/files/" . $field->name)) {
                                 JFile::delete(JPATH_ROOT . "/images/com_adsmanager/files/" . $field->name);
                             }
                             $this->data['fields'][$field->name] = "";
                         }
                     }
                 } else {
                     if ($field->type == "editor") {
                         $value = JRequest::getVar($field->name, '', 'post', 'string', JREQUEST_ALLOWHTML);
                         $this->data['fields'][$field->name] = $this->replaceBannedWords($value, $bannedwords, $replaceword);
                     } else {
                         if ($field->type == "price") {
                             $value = JRequest::getVar($field->name, '');
                             $value = str_replace(',', '.', $value);
                             $value = str_replace(' ', '', $value);
                             $this->data['fields'][$field->name] = $value;
                         } else {
                             if (isset($plugins[$field->type])) {
                                 $value = $plugins[$field->type]->onFormSave($this, $field);
                                 if ($value !== null) {
                                     $this->data['fields'][$field->name] = $value;
                                 }
                             } else {
                                 $value = JRequest::getVar($field->name, '');
                                 $this->data['fields'][$field->name] = $this->replaceBannedWords($value, $bannedwords, $replaceword);
                             }
                         }
                     }
                 }
             }
         }
     }
     $this->data['images'] = array();
     $this->data['delimages'] = array();
     $current_images = json_decode($this->images);
     if ($current_images == null) {
         $current_images = array();
     }
     $image_index = 0;
     $pending = JRequest::getInt('pending', 0);
     if ($pending && count($currentpendingchanges->images) > 0) {
         foreach ($currentpendingchanges->images as $img) {
             $this->data['images'][] = $img;
             if ($img->index > $image_index) {
                 $image_index = $img->index;
             }
         }
     }
     $deleted_images = JRequest::getVar("deleted_images", "");
     $deleted_images = explode(',', $deleted_images);
     foreach ($current_images as $i => $img) {
         if (in_array($img->index, $deleted_images)) {
             $this->data['delimages'][] = $img;
         } else {
             if ($img->index > $image_index) {
                 $image_index = $img->index;
             }
         }
     }
     foreach ($this->data['images'] as $i => $img) {
         if (in_array($img->index, $deleted_images)) {
             if (is_file(JPATH_ROOT . "/images/com_adsmanager/ads/waiting/" . $img->image)) {
                 JFile::delete(JPATH_ROOT . "/images/com_adsmanager/ads/waiting/" . $img->image);
             }
             /*  if(is_file(JPATH_ROOT."/images/com_adsmanager/ads/waiting/".$img->thumbnail)) {
                     JFile::delete(JPATH_ROOT."/images/com_adsmanager/ads/waiting/".$img->thumbnail);
                 }
                 if(is_file(JPATH_ROOT."/images/com_adsmanager/ads/waiting/".$img->medium)) {
                     @JFile::delete(JPATH_ROOT."/images/com_adsmanager/ads/waiting/".$img->medium);
                 }*/
             unset($this->data['images'][$i]);
         }
     }
     $nb_images = count($current_images) - count($this->data['delimages']);
     $nbMaxImages = $conf->nb_images;
     if (function_exists("getMaxPaidSystemImages")) {
         $nbMaxImages += getMaxPaidSystemImages();
     }
     $uploader_count = JRequest::getInt('imagesupload_count', 0);
     $targetDir = JPATH_ROOT . '/images/com_adsmanager/ads/uploaded';
     $dir = JPATH_ROOT . "/images/com_adsmanager/ads/waiting/";
     $orderlisttmp = explode(',', JRequest::getString('orderimages', ""));
     $orderlist = array();
     foreach ($orderlisttmp as $value) {
         $orderlist[] = str_replace('li_img_', '', $value);
     }
     for ($i = 0; $i < $uploader_count && $nb_images < $nbMaxImages; $i++) {
         $uploader_tmpname = JRequest::getString('imagesupload_' . $i . '_tmpname', 0);
         $uploader_id = JRequest::getString('imagesupload_' . $i . '_id', 0);
         $uploader_name = JRequest::getString('imagesupload_' . $i . '_name', 0);
         $uploader_status = JRequest::getString('imagesupload_' . $i . '_status', 0);
         $tmpfile = sha1(microtime(true) . mt_rand(10000, 90000)) . ".jpg";
         $thumb_tmpfile = sha1(microtime(true) . mt_rand(10000, 90000)) . ".jpg";
         $medium_tmpfile = sha1(microtime(true) . mt_rand(10000, 90000)) . ".jpg";
         //var_dump($targetDir."/".$uploader_tmpname);
         //var_dump($uploader_status);
         if ($uploader_status == "done" && file_exists($targetDir . "/" . $uploader_tmpname)) {
             try {
                 $error = $model->createImageAndThumb($targetDir . "/" . $uploader_tmpname, $tmpfile, $thumb_tmpfile, $conf->max_width, $conf->max_height, $conf->max_width_t, $conf->max_height_t, $conf->tag, $dir, $uploader_name, $conf->max_width_m, $conf->max_height_m, $medium_tmpfile);
                 if (is_file($targetDir . "/" . $uploader_tmpname)) {
                     JFile::delete($targetDir . "/" . $uploader_tmpname);
                 }
                 if ($error != null) {
                     $this->errors[] = $error;
                 } else {
                     $image_index++;
                     $nb_images++;
                     $newimg = new stdClass();
                     $newimg->index = $image_index;
                     $newimg->image = $tmpfile;
                     $newimg->thumbnail = $thumb_tmpfile;
                     $newimg->medium = $medium_tmpfile;
                     $this->data['images'][] = $newimg;
                     //echo $uploader_id."<br/>";
                     foreach ($orderlist as $key => $val) {
                         if ($val == $uploader_id) {
                             $orderlist[$key] = $image_index;
                         }
                     }
                 }
             } catch (Exception $e) {
                 if (is_file($targetDir . "/" . $uploader_tmpname)) {
                     JFile::delete($targetDir . "/" . $uploader_tmpname);
                 }
                 $this->errors[] = $e->getMessage();
             }
         }
     }
     $this->data['orderimages'] = $orderlist;
     $this->update_validation = @$conf->update_validation;
     $app = JFactory::getApplication();
     if ($app->isAdmin() == false && $this->id == 0) {
         $this->date_created = date("Y-m-d H:i:s");
         $delta = $conf->ad_duration;
         if ($delta == 0) {
             $this->expiration_date = null;
         } else {
             $this->expiration_date = date("Y-m-d H:i:s", time() + $delta * 24 * 3600);
         }
         if ($conf->auto_publish == 1) {
             $this->published = 1;
         } else {
             $this->published = 0;
         }
     } else {
         if ($this->id != 0) {
             if ($this->update_validation) {
                 $this->published = 0;
             }
         }
     }
     if ($this->id == 0) {
         if (!isset($conf->publication_date) || $conf->publication_date == 0) {
             $this->publication_date = date("Y-m-d H:i:s");
         } else {
             $this->publication_date = $this->publication_date . ' 00:00:00';
         }
         if ($app->isAdmin() == false) {
             $this->expiration_date = date("Y-m-d H:i:s", strtotime($this->publication_date) + $delta * 24 * 3600);
         }
     } else {
         if ($app->isAdmin() == true) {
             $this->publication_date = $this->publication_date . ' 00:00:00';
         }
     }
     if (count($this->errors) > 0) {
         return false;
     } else {
         return true;
     }
 }
Example #2
0
 function _editcontent()
 {
     $this->setEditToolbar(JText::_("COM_ADSMANAGER") . " - " . JText::_("ADSMANAGER_EDIT_CONTENT"));
     $app = JFactory::getApplication();
     $document = JFactory::getDocument();
     $user = JFactory::getUser();
     $confmodel = $this->getModel("Configuration");
     $usermodel = $this->getModel("User");
     $contentmodel = $this->getModel("Content");
     $catmodel = $this->getModel("Category");
     $fieldmodel = $this->getModel("Field");
     $conf = $confmodel->getConfiguration();
     if (!isset($conf->single_category_selection_type)) {
         $conf->single_category_selection_type = 'normal';
     }
     $baseurl = JURI::root();
     $document->addStyleSheet($baseurl . 'components/com_adsmanager/js/plupload/jquery.plupload.queue/css/jquery.plupload.queue.css');
     $document->addStyleSheet($baseurl . 'components/com_adsmanager/css/adsmanager.css');
     $document->addScript($baseurl . 'components/com_adsmanager/js/plupload/plupload.full.js');
     $document->addScript($baseurl . 'components/com_adsmanager/js/plupload/jquery.plupload.queue/jquery.plupload.queue.js');
     $lang = JFactory::getLanguage();
     $tag = $lang->getTag();
     $tag = substr($tag, 0, strpos($tag, '-'));
     if (file_exists(JPATH_ROOT . "/components/com_adsmanager/js/plupload/i18n/{$tag}.js")) {
         $document->addScript($baseurl . "components/com_adsmanager/js/plupload/i18n/{$tag}.js");
     }
     $this->assignRef('conf', $conf);
     $catid = JRequest::getInt('catid', 0);
     if ($catid != 0) {
         $category = $catmodel->getCategory($catid);
         $category->img = TTools::getCatImageUrl($catid, true);
     } else {
         $category = new stdClass();
         $category->name = JText::_("");
         $category->description = "";
         $category->img = "";
     }
     $this->assignRef('category', $category);
     $this->assignRef('catid', $catid);
     $fields = $fieldmodel->getFields();
     $this->assignRef('fields', $fields);
     $field_values = $fieldmodel->getFieldValues();
     foreach ($fields as $field) {
         if ($field->cbfieldvalues != "-1") {
             /*get CB value fields */
             $cbfieldvalues = $fieldmodel->getCBFieldValues($field->cbfieldvalues);
             $field_values[$field->fieldid] = $cbfieldvalues;
         }
     }
     $this->assignRef('field_values', $field_values);
     $plugins = $fieldmodel->getPlugins();
     $field = new JHTMLAdsmanagerField($conf, $field_values, "1", $plugins, "", $this->get('baseurl'));
     $this->assignRef('field', $field);
     $errorMsg = JRequest::getString('errorMsg', "");
     $this->assignRef('errorMsg', $errorMsg);
     $users = $usermodel->getUsers();
     $this->assignRef('users', $users);
     /* No need to user query, if errorMsg */
     if ($errorMsg == "") {
         if (COMMUNITY_BUILDER == 0) {
             $profile = $usermodel->getProfile($user->id);
         } else {
             $profile = $usermodel->getCBProfile($user->id);
         }
     }
     $contentid = JRequest::getVar('cid', array(0), '', 'array');
     JArrayHelper::toInteger($contentid, array(0));
     $contentid = JRequest::getVar('id', $contentid[0], '', 'int');
     // Update Ad ?
     if ($contentid > 0) {
         // edit ad
         $content = $contentmodel->getContent($contentid, false, 1);
         if ($content == null) {
             echo "Error Ad not found";
             exit;
         }
         $content->ad_text = str_replace('<br/>', "\r\n", $content->ad_text);
         $isUpdateMode = 1;
     } else {
         // insert
         $content = new stdClass();
         $content->published = 1;
         $isUpdateMode = 0;
     }
     $this->assignRef('content', $content);
     $this->assignRef('isUpdateMode', $isUpdateMode);
     $nbcats = $conf->nbcats;
     if (function_exists("getMaxCats")) {
         $nbcats = getMaxCats($conf->nbcats);
     }
     $this->assignRef('nbcats', $nbcats);
     if ($nbcats > 1) {
         $cats = $catmodel->getFlatTree();
     } else {
         switch ($conf->single_category_selection_type) {
             default:
             case 'normal':
             case 'color':
             case 'combobox':
                 $cats = $catmodel->getFlatTree();
                 break;
             case 'cascade':
                 $cats = $catmodel->getCategoriesPerLevel();
                 break;
         }
     }
     $this->assignRef('cats', $cats);
     $nullobj = null;
     if ($errorMsg != "") {
         $this->assignRef('default', (object) JRequest::get('post'));
     } else {
         $this->assignRef('default', $nullobj);
     }
     if ($conf->submission_type == 2 && $user->id == "0") {
         $this->assignRef('warning_text', ADSMANAGER_WARNING_NEW_AD_NO_ACCOUNT . "<br/>");
     }
     switch ($errorMsg) {
         case "bad_password":
             $this->assignRef('error_text', JText::_('ADSMANAGER_BAD_PASSWORD') . "<br />");
             break;
         case "email_already_used":
             $this->assignRef('error_text', JText::_('ADSMANAGER_EMAIL_ALREADY_USED') . "<br />");
             break;
         case "file_too_big":
             $this->assignRef('error_text', JText::_('ADSMANAGER_FILE_TOO_BIG') . "<br />");
     }
     if ($conf->submission_type == 0 && $user->id == 0) {
         $this->assignRef('account_creation', 1);
     }
 }
Example #3
0
        </div>
		<?php
	  }
	  else
	  {
		?>
   		<div class="control-group">
            <?php
                if (isset($this->content->catsid)) {
                    $catids = $this->content->catsid;
                } else {
                    $catids = array();
                }
                $nbcats = $this->conf->nbcats;
                if (PAIDSYSTEM) {
                    $nbcats = getMaxCats($nbcats);
                }
                JHTMLAdsmanagerCategory::displayMultipleCategories("cats",$this->cats,$catids,array("root_allowed"=>$this->conf->root_allowed,"display_price"=>true),$nbcats);
                ?>
                <?php 
                if (PAIDSYSTEM)
                {
                    displayPaidCat($this->conf->nbcats);
                }
                else
                {
                    echo sprintf(JText::_('ADSMANAGER_NBCATS_LEGEND'),$this->conf->nbcats);
                }
            ?>
        </div>
        <?php 
Example #4
0
 /**
  * Saves the content item an edit form submit
  *
  * @todo
  */
 function save()
 {
     $app = JFactory::getApplication();
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     $user = JFactory::getUser();
     $content = JTable::getInstance('contents', 'AdsmanagerTable');
     $this->addModelPath(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_adsmanager' . DS . 'models');
     $configurationmodel = $this->getModel("configuration");
     $contentmodel = $this->getModel("content");
     $usermodel = $this->getModel("user");
     $fieldmodel = $this->getModel("field");
     $conf = $configurationmodel->getConfiguration();
     $plugins = $fieldmodel->getPlugins();
     $id = JRequest::getInt('id', 0);
     // New or Update
     if ($id != 0) {
         $content->load($id);
         if ($content == null || $content->userid != $user->id) {
             $app->redirect(TRoute::_('index.php?option=com_adsmanager&view=list'));
         }
         $isUpdateMode = 1;
         if ($conf->update_validation == 1) {
             $redirect_text = JText::_('ADSMANAGER_INSERT_SUCCESSFULL_CONFIRM');
         } else {
             $redirect_text = JText::_('ADSMANAGER_AD_UPDATED');
         }
     } else {
         $isUpdateMode = 0;
         if ($conf->auto_publish == 0) {
             $redirect_text = JText::_('ADSMANAGER_INSERT_SUCCESSFULL_CONFIRM');
         } else {
             $redirect_text = JText::_('ADSMANAGER_INSERT_SUCCESSFULL_PUBLISH');
         }
     }
     //Check Max Ads by User
     $nbcats = $conf->nbcats;
     if (function_exists("getMaxCats")) {
         $nbcats = getMaxCats($conf->nbcats);
     }
     if ($nbcats <= 1) {
         if (function_exists("checkAuthorisedNumberAds")) {
             $limitAds = checkAuthorisedNumberAds($contentmodel, JRequest::getInt('category', 0));
             if ($limitAds !== true) {
                 $redirect_text = sprintf(JText::_('ADSMANAGER_MAX_NUM_ADS_PER_CATEGORY_REACHED'), $limitAds);
                 $app->redirect(TRoute::_('index.php?option=com_adsmanager&view=list'), $redirect_text, 'message');
             }
         } else {
             if (JRequest::getInt('category', 0) != 0) {
                 $category = JRequest::getInt('category', 0);
                 // Need to check limit only for new ad and if category of ad is changed
                 if ($isUpdateMode == 0 || !in_array($category, $contentmodel->getContentCategories($id))) {
                     $nb = $contentmodel->getNbContentsOfUser($user->id, $category);
                     //TODO : check authorised number for multi-categories
                     $categoriesModel = $this->getModel("category");
                     $category = $categoriesModel->getCategory($category);
                     if ($category->limitads !== "" && $category->limitads !== null) {
                         if ($nb >= $category->limitads && $category->limitads != -1) {
                             $redirect_text = sprintf(JText::_('ADSMANAGER_MAX_NUM_ADS_PER_CATEGORY_REACHED'), $category->limitads);
                             $app->redirect(TRoute::_('index.php?option=com_adsmanager&view=list'), $redirect_text, 'message');
                         }
                     }
                 }
             }
         }
     }
     if ($id == 0 && $user->id != "0" && $conf->nb_ads_by_user != -1) {
         $nb = $contentmodel->getNbContentsOfUser($user->id);
         if ($nb >= $conf->nb_ads_by_user) {
             $redirect_text = sprintf(JText::_('ADSMANAGER_MAX_NUM_ADS_REACHED'), $conf->nb_ads_by_user);
             $app->redirect(TRoute::_('index.php?option=com_adsmanager&view=list'), $redirect_text, 'message');
         }
     }
     //check if user can post an ad in the category selected
     //TODO : If multiple category
     if (version_compare(JVERSION, '1.6', 'ge')) {
         if ($nbcats <= 1) {
             $authorisedCategory = TPermissions::getAuthorisedCategories('write');
             if (array_search(JRequest::getInt('category', 0), $authorisedCategory) === false) {
                 $redirect_text = sprintf(JText::_('ADSMANAGER_FORBIDDEN_CATEGORY'), $conf->nb_ads_by_user);
                 $app->redirect(TRoute::_('index.php?option=com_adsmanager&view=list'), $redirect_text, 'message');
             }
         }
     }
     $current = clone $content;
     $content->bindContent(JRequest::get('post'), JRequest::get('files'), $conf, $this->getModel("adsmanager"), $plugins);
     if (function_exists('bindPaidSystemContent')) {
         bindPaidSystemContent($content, JRequest::get('post'), JRequest::get('files'), $conf, $this->getModel("adsmanager"));
     }
     $content->current = $current;
     $errors = $content->getErrors();
     if (count($errors) > 0) {
         $this->reloadForm($content);
     }
     if ($conf->metadata_mode == 'backendonly') {
         $content->metadata_description = JRequest::getVar('ad_text', '');
         $content->metadata_keywords = str_replace(" ", ",", JRequest::getVar('ad_headline', ''));
     }
     $errorMsg = null;
     $dispatcher = JDispatcher::getInstance();
     JPluginHelper::importPlugin('adsmanagercontent');
     try {
         $results = $dispatcher->trigger('ADSonContentBeforeSave', array());
     } catch (Exception $e) {
         $errorMsg = $e->getMessage();
         $this->reloadForm($content, $errorMsg);
     }
     //Creation of account if needed
     if ($conf->submission_type == 0 && $user->id == 0) {
         $username = JRequest::getVar('username', "");
         $password = JRequest::getVar('password', "");
         $email = JRequest::getVar('email', "");
         $errorMsg = $usermodel->checkAccount($username, $password, $email, $userid, $conf);
         if (isset($errorMsg)) {
             $this->reloadForm($content, $errorMsg);
         }
         $user->id = $userid;
     }
     //Valid account or visitor are allowed to post
     if ($user->id != 0 || $conf->submission_type == 2) {
         $content->userid = $user->id;
     } else {
         //trying to save ad, without being registered
         return;
     }
     if (function_exists("getPaidSystemMode")) {
         $mode = getPaidSystemMode();
     } else {
         $mode = "nopaidsystem";
     }
     $total = 0;
     switch ($mode) {
         case "credits":
             computeCost($total, $items, $content, $conf, $isUpdateMode);
             if ($total == 0) {
                 $content->save();
             } else {
                 if (checkCredits($total, $user->id) == true) {
                     //TODO ?
                     //generateBill($content,$total,$items,$mode,"ok");
                     removeCredits($user->id, $total, $items, 'Adsmanager');
                     $content->save();
                 } else {
                     $errorMsg = sprintf(JText::_('PAIDSYSTEM_NOT_ENOUGH_CREDITS'), strtolower(getCurrencySymbol()));
                     $this->reloadForm($content, $errorMsg);
                 }
             }
             break;
         case "payperad":
             $adid = $content->savePending();
             $content->isPending = true;
             computeCost($total, $items, $content, $conf, $isUpdateMode);
             if ($total == 0) {
                 $content->save();
             } else {
                 $invoice_id = generateBill($content, $items, $adid);
             }
             break;
         case "nopaidsystem":
             $content->save();
             break;
     }
     // We need to put "pending or new values" in the $content obj instead of $content->data
     $content->map();
     if ($mode == "payperad" && $total > 0 && $isUpdateMode == 0) {
         if (@$conf->preview == 1) {
             $app->redirect('index.php?option=com_adsmanager&view=preview&id=' . $adid);
         } else {
             Invoicing::redirectToPayment($invoice_id);
             //$app->redirect( 'index.php?option=com_paidsystem&view=payment');
         }
     } else {
         if (@$conf->preview == 1 && JRequest::getInt('pending', 0) == 1) {
             $app->redirect('index.php?option=com_adsmanager&view=preview&id=' . $adid);
         } else {
             if ($mode == "payperad" && $total > 0 && $isUpdateMode == 1) {
                 Invoicing::redirectToPayment($invoice_id);
             } else {
                 $cache =& JFactory::getCache('com_adsmanager');
                 $cache->clean();
                 if ($isUpdateMode == 0) {
                     if ($conf->send_email_on_new_to_user == 1 && $conf->auto_publish == 1) {
                         $contentmodel->sendMailToUser($conf->new_subject, $conf->new_text, $user, $content, $conf, "new");
                     } else {
                         if ($conf->send_email_waiting_validation_to_user == 1 && $conf->auto_publish == 0) {
                             $contentmodel->sendMailToUser($conf->waiting_validation_subject, $conf->waiting_validation_text, $user, $content, $conf, "waiting_validation");
                         }
                     }
                     if ($conf->email_on_waiting_validation == 1 && $conf->auto_publish == 0) {
                         if (isset($conf->admin_waiting_validation_subject) && $conf->admin_waiting_validation_text) {
                             $contentmodel->sendMailToAdmin($conf->admin_waiting_validation_subject, $conf->admin_waiting_validation_text, $user, $content, $conf, "admin_waiting_validation");
                         }
                     }
                     if ($conf->send_email_on_new == 1) {
                         $contentmodel->sendMailToAdmin($conf->admin_new_subject, $conf->admin_new_text, $user, $content, $conf, "new");
                     }
                 } else {
                     if ($conf->update_validation == 1) {
                         $contentmodel->sendMailToUser($conf->waiting_validation_subject, $conf->waiting_validation_text, $user, $content, $conf, "waiting_validation");
                     } else {
                         if ($conf->send_email_on_update_to_user == 1) {
                             $contentmodel->sendMailToUser($conf->update_subject, $conf->update_text, $user, $content, $conf, "update");
                         }
                     }
                     if ($conf->email_on_waiting_validation == 1 && $conf->update_validation == 1) {
                         if (isset($conf->admin_waiting_validation_subject) && $conf->admin_waiting_validation_text) {
                             $contentmodel->sendMailToAdmin($conf->admin_waiting_validation_subject, $conf->admin_waiting_validation_text, $user, $content, $conf, "admin_waiting_validation");
                         }
                     }
                     if ($conf->send_email_on_update == 1) {
                         $contentmodel->sendMailToAdmin($conf->admin_update_subject, $conf->admin_update_text, $user, $content, $conf, "update");
                     }
                 }
                 JPluginHelper::importPlugin('adsmanagercontent');
                 try {
                     $results = $dispatcher->trigger('ADSonContentAfterSave', array($content, $isUpdateMode, $conf));
                 } catch (Exception $e) {
                     $errorMsg = $e->getMessage();
                 }
                 //Redirect
                 if ($conf->submission_type == 2) {
                     $app->redirect(TRoute::_('index.php?option=com_adsmanager&view=list'), $redirect_text, 'message');
                 } else {
                     $app->redirect(TLink::getMyAdsLink(), $redirect_text, 'message');
                 }
             }
         }
     }
 }
	function display($tpl = null)
	{
		$app = JFactory::getApplication();

		$user		= JFactory::getUser();
		$app	= JFactory::getApplication();
		$pathway = $app->getPathway();
		$document	= JFactory::getDocument();
		
		$configurationmodel	= $this->getModel("configuration");
		$fieldmodel		= $this->getModel("field");
		$contentmodel	= $this->getModel("content");
		$catmodel		= $this->getModel("category");
		$usermodel		= $this->getModel("user");
		
		// Get the parameters of the active menu item
		$menus	= $app->getMenu();
		$menu    = $menus->getActive();
		
		$conf = $configurationmodel->getConfiguration();
        
        if(!isset($conf->single_category_selection_type))
            $conf->single_category_selection_type = 'normal';
		
        $this->assignRef('conf',$conf);	
		
		$fields = $fieldmodel->getFields(true,null,null,"fieldid","ASC",true,'write');	
		$this->assignRef('fields',$fields);
		
		
		$field_values = $fieldmodel->getFieldValues();
		foreach($fields as $field)
		{
			if ($field->cbfieldvalues != "-1")
			{
				/*get CB value fields */
				$cbfieldvalues = $fieldmodel->getCBFieldValues($field->cbfieldvalues);
				$field_values[$field->fieldid] = $cbfieldvalues;
			}
		}
		$this->assignRef('field_values',$field_values);
		
		$plugins = $fieldmodel->getPlugins();
		$field = new JHTMLAdsmanagerField($conf,$field_values,"1",$plugins);
		
		$this->assignRef('field',$field);
		
		$errorMsg = JRequest::getString( 'errorMsg',	"" );
		$this->assignRef('errorMsg',$errorMsg);	
		
		/* No need to user query, if errorMsg */
		if ($errorMsg == "")
		{
			if ($conf->comprofiler == 0)
			{	
				$profile = $usermodel->getProfile($user->id);
			}
			else if (COMMUNITY_BUILDER == 1)
			{
				$profile = $usermodel->getCBProfile($user->id);
			} else {
				$profile = new stdClass();
			}
			$this->assignRef('default',$profile);
		}
		
		$contentid = JRequest::getInt( 'id', 0 );
		
		// Update Ad ?
		if ($contentid > 0)
		{ // edit ad	
			$content = $contentmodel->getContent($contentid,false,1);
			//$content->ad_text = str_replace ('<br/>',"\r\n",$content->ad_text);
            
            if(!isset($this->isDuplicated))
                $this->isDuplicated = 0;
            
            if ($user->id == 0) {
                $app->redirect( TRoute::_('index.php?option=com_adsmanager') );
            }
            else if ($content->userid == $user->id)
            {
                if($this->isDuplicated == 1){
                    foreach($content->images as $image){
                        $src = 'images/com_adsmanager/ads/'.$image->image;
                        $dest = 'images/com_adsmanager/ads/uploaded/'.$image->image;
                        
                        copy($src, $dest);
                    }
                    
                    $content->id = 0;
                    $isUpdateMode = 0;
                } else {
                    $isUpdateMode = 1;
                }
            }
            else
            {
                $app->redirect(TLink::getMyAdsLink());
            }
			
		}
		else { // insert
			$isUpdateMode = 0;	
		}
		
		$this->assignRef('content',$content);
        
        if(isset($content->pendingdata->new_ad) && $content->pendingdata->new_ad == true) {
            $isUpdateMode = 0;
        }
        
		$this->assignRef('isUpdateMode',$isUpdateMode);
		
		$catid = JRequest::getInt('catid',0);
		
		// If Root cat is not allowed we must check that catid is correct
		$submit_allow = 1;
		if (($catid != 0)&&($conf->root_allowed == 0)) {
			$submit_allow = !$catmodel->isRootCategory($catid);
		}
		$this->assignRef('submit_allow',$submit_allow);
		
		if ($catid != 0) {
			if ($catmodel->isPublishedCategory($catid) == false) {
				$app->redirect( JRoute::_('index.php?option=com_adsmanager'),"Invalid Category selection","message");
				return;
			}
		}
        
		if (($catid == 0)&&($isUpdateMode == 1))
		{
			$catid = $content->cats[0]->catid;
		}
		
		$rootid = JRequest::getInt('rootid',0);
		$this->assignRef('rootid',$rootid);
		
		if ($catid != "0") {
			$category = $catmodel->getCategory($catid);
			$category->img = TTools::getCatImageUrl($catid,true);
		}
		else
		{
			$category = new stdClass();
			$category->name = JText::_("");
			$category->description = "";
			$category->img = "";
		}
		$this->assignRef('category',$category);
		$this->assignRef('catid',$catid);
		
		if (isset($content))
			$extra = " - ".$content->ad_headline;
		else
			$extra = "";
		$document->setTitle( JText::_('ADSMANAGER_PAGE_TITLE')." ".JText::_($category->name).$extra);
		
		$nbcats = $conf->nbcats;
		if (function_exists("getMaxCats"))
		{
			$nbcats = getMaxCats($conf->nbcats);
		}
		$this->assignRef('nbcats',$nbcats);
		
		if ($nbcats > 1) {
			$cats = $catmodel->getFlatTree(true, false, $nbContents, 'write',$rootid);
		} else {
			$rootid = JRequest::getInt('rootid',0);
			switch(@$conf->single_category_selection_type) {
				default:
				case 'normal':
				case 'color':
				case 'combobox':
					$cats = $catmodel->getFlatTree(true, false, $nbContents, 'write',$rootid);
					break;
				case 'cascade':
					$cats = $catmodel->getCategoriesPerLevel(true, false, $nbContents, 'write',$rootid);
					break;
			}
		}
        
        if(empty($cats)){
			$app->redirect( JRoute::_('index.php?option=com_adsmanager&view=front&status=error'), JText::_('ADSMANAGER_NO_WRITE_RIGHT'),'message' );
		}
        
        $this->assignRef('cats',$cats);
		
		if ($errorMsg != "") {
			//$post = (object) $_POST;
			$post = JRequest::get( 'post' ); 
			$this->assignRef('default',$post);
		}
			
		if (($conf->submission_type == 2)&&($user->id == "0"))
		{
			$txt = JText::_('ADSMANAGER_WARNING_NEW_AD_NO_ACCOUNT');
			$this->assignRef('warning_text',$txt);
		}
		
		switch($errorMsg)
		{
			case "bad_password":
				$txt = JText::_('ADSMANAGER_BAD_PASSWORD');
				$this->assignRef('error_text',$txt);
				break;
			case "email_already_used":
				$txt = JText::_('ADSMANAGER_EMAIL_ALREADY_USED');
				$this->assignRef('error_text',$txt);
				break;
			case "file_too_big":
				$txt = JText::_('ADSMANAGER_FILE_TOO_BIG');
				$this->assignRef('error_text',$txt);
				break;
			default:
				if ($errorMsg != "") {
					$txt = $errorMsg;
					$this->assignRef('error_text',$txt);
				}
		}
		
		if (($conf->submission_type == 0)&&($user->id == 0))
		{
			$account_creation = 1;
		}
		else
			$account_creation = 0;
		
		$this->assignRef('account_creation',$account_creation);
		
		$dispatcher = JDispatcher::getInstance();
		JPluginHelper::importPlugin('adsmanagercontent');
		
		$event = new stdClass();
		$results = $dispatcher->trigger('ADSonContentAfterForm', array ($content));
		$event->onContentAfterForm = trim(implode("\n", $results));
		$this->assignRef('event',$event);
		
		if (PAIDSYSTEM) {
			if(isset($content->id)) {
				$db = JFactory::getDbo();
				$db->setQuery( "SELECT * FROM #__paidsystem_ads WHERE id=".(int)$content->id );
				$adext = $db->loadObject();
			} else {
				$adext = new stdClass();
				$adext->images = 0;
			}
		} else {
			$adext = new stdClass();
			$adext->images = 0;
		}
		$this->assignRef('adext',$adext);
        
		parent::display($tpl);
	}