_binary From 1a309c4b589d7a2a1c509124660c10e17c51735f Mon Sep 17 00:00:00 2001
From: Pushkar Umaranikar <pushkar.umaranikar@sjsu.edu>
Date: Sun, 31 May 2015 15:39:03 -0700
Subject: [PATCH] 0000169: Advertisement server integration with yioop

---
 controllers/components/accountaccess_component.php |   9 ++
 controllers/components/advertisement_component.php | 152 ++++++++++--------
 controllers/components/system_component.php        |  38 +++++
 controllers/search_controller.php                  |  28 ++--
 css/search.css                                     |   2 +-
 data/default.db                                    | Bin 224256 -> 294912 bytes
 lib/upgrade_functions.php                          |  16 +-
 models/adkeyword_model.php                         | 173 +++++++++++++++++++++
 models/admetadata_model.php                        | 145 +++++++++++++++++
 models/advertisement_model.php                     | 150 +++++++++---------
 models/advkeyword_model.php                        | 173 ---------------------
 models/advmetadata_model.php                       | 145 -----------------
 models/profile_model.php                           |  26 ++--
 views/elements/displayadvertisement_element.php    |  12 +-
 views/elements/manageaccount_element.php           |   3 +-
 views/elements/manageadvertisements_element.php    | 107 +++++++------
 views/elements/serversettings_element.php          |  27 +++-
 17 files changed, 653 insertions(+), 553 deletions(-)
 create mode 100644 models/adkeyword_model.php
 create mode 100644 models/admetadata_model.php
 delete mode 100644 models/advkeyword_model.php
 delete mode 100644 models/advmetadata_model.php

diff --git a/controllers/components/accountaccess_component.php b/controllers/components/accountaccess_component.php
index 6c4873c..4b52bd4 100644
--- a/controllers/components/accountaccess_component.php
+++ b/controllers/components/accountaccess_component.php
@@ -70,10 +70,19 @@ class AccountaccessComponent extends Component
         $user_model = $parent->model("user");
         $crawl_model = $parent->model("crawl");
         $role_model = $parent->model("role");
+        $profile_model = $parent->model("profile");
         $possible_arguments = array("updateuser");
+        $profile = $profile_model->getProfile(WORK_DIRECTORY);
         $data["ELEMENT"] = "manageaccount";
         $data['SCRIPT'] = "";
         $data['MESSAGE'] = "";
+        $data['yioop_advertisement'] = $profile['ADVERTISEMENT_TYPE'];
+        if (!in_array($profile['ADVERTISEMENT_TYPE'],
+            array('no_advertisements','external_advertisements'))) {
+            $data['yioop_advertisement'] = true;
+        } else {
+            $data['yioop_advertisement'] = false;
+        }
         $user_id = $_SESSION['USER_ID'];
         $username = $signin_model->getUserName($user_id);
         $data["USER"] = $user_model->getUser($username);
diff --git a/controllers/components/advertisement_component.php b/controllers/components/advertisement_component.php
index ff567e8..4592545 100644
--- a/controllers/components/advertisement_component.php
+++ b/controllers/components/advertisement_component.php
@@ -49,9 +49,9 @@ class AdvertisementComponent extends Component
         $parent = $this->parent;
         $signin_model = $parent->model("signin");
         $user_model = $parent->model("user");
-        $advkeyword_model = $parent->model("advkeyword");
-        $request_fields = array("start_row", "num_show", "end_row", "ADV_NAME",
-            "ADV_DESTINATION", "ADV_DESCRIPTION", "ADV_KEYWORDS", "ADV_BUDGET");
+        $adkeyword_model = $parent->model("adkeyword");
+        $request_fields = array("start_row", "num_show", "end_row", "AD_NAME",
+            "AD_DESTINATION", "AD_DESCRIPTION", "AD_KEYWORDS", "AD_BUDGET");
         $advertisement_model = $parent->model("advertisement");
         $data['SCRIPT'] = "";
         $data['MESSAGE'] = "";
@@ -60,39 +60,44 @@ class AdvertisementComponent extends Component
         $data['NEW_KEYWORDS'] = "";
         $today = strtotime(date('Y-m-d'));
         $data['TODAY'] = $today;
+        foreach ($request_fields as $field) {
+            if (isset($_REQUEST[$field])) {
+                $data[$field] = $_REQUEST[$field];
+            }
+        }
         if (isset($_REQUEST['keywords'])) {
-            if (empty($_REQUEST['ADV_NAME']) ||
-                empty($_REQUEST['ADV_DESCRIPTION']) ||
-                empty($_REQUEST['ADV_DESTINATION'])) {
+            if (empty($_REQUEST['AD_NAME']) ||
+                empty($_REQUEST['AD_DESCRIPTION']) ||
+                empty($_REQUEST['AD_DESTINATION'])) {
                 $parent->redirectWithMessage(
                     tl('advertisement_component_fields_cannot_be_empty'),
                     array_merge((array)$_REQUEST['arg'],
                     $request_fields));
             }
-            if (empty($_REQUEST['ADV_START_DATE']) ||
-               empty($_REQUEST['ADV_END_DATE'])) {
+            if (empty($_REQUEST['AD_START_DATE']) ||
+               empty($_REQUEST['AD_END_DATE'])) {
                 $parent->redirectWithMessage(
                     tl('advertisement_component_date_cannot_be_empty'),
                     array_merge((array)$_REQUEST['arg'],
                     $request_fields));
             }
-            if (empty($_REQUEST['ADV_KEYWORDS'])) {
+            if (empty($_REQUEST['AD_KEYWORDS'])) {
                 $parent->redirectWithMessage(
                     tl('advertisement_component_enter_keywords'),
                     array_merge((array)$_REQUEST['arg'],
                     $request_fields));
             }
             $temp_keywords= explode(",",strtolower($parent->
-                clean($_REQUEST['ADV_KEYWORDS'], "string")));
+                clean($_REQUEST['AD_KEYWORDS'], "string")));
             array_walk($temp_keywords, array("AdvertisementComponent",
                 "trim_value"));
             $new_keywords = array();
-            $adv_fields =  array("ADV_NAME", "ADV_DESTINATION",
-                "ADV_DESCRIPTION", "ADV_KEYWORDS", "ADV_BUDGET",
-                "ADV_START_DATE","ADV_END_DATE");
-            $start_date = strtotime($parent->clean($_REQUEST['ADV_START_DATE'],
+            $adv_fields =  array("AD_NAME", "AD_DESTINATION",
+                "AD_DESCRIPTION", "AD_KEYWORDS", "AD_BUDGET",
+                "AD_START_DATE","AD_END_DATE");
+            $start_date = strtotime($parent->clean($_REQUEST['AD_START_DATE'],
                 "string"));
-            $end_date = strtotime($parent->clean($_REQUEST['ADV_END_DATE'],
+            $end_date = strtotime($parent->clean($_REQUEST['AD_END_DATE'],
                 "string"));
             $date_diff = $end_date - $start_date;
             if ($date_diff < 0 ) {
@@ -116,7 +121,7 @@ class AdvertisementComponent extends Component
                 $temp_date = $start_date;
                 for ( $k = 0; $k < $day_count; $k++ ) {
                     $keyword_bid_amount = 0;
-                    if(!$advkeyword_model->
+                    if(!$adkeyword_model->
                         isKeywordPresent($temp_keywords[$i], $temp_date)){
                         $new_keywords[$j]['KEYWORD'] = $temp_keywords[$i];
                         $new_keywords[$j]['BID_AMOUNT'] = ADV_KEYWORD_INIT_BID;
@@ -127,7 +132,7 @@ class AdvertisementComponent extends Component
                         $j++;
                         $min_bid_reqd++;
                     } else {
-                        $bid_amount =$advkeyword_model->
+                        $bid_amount =$adkeyword_model->
                             getBidAmount($temp_keywords[$i], $temp_date);
                         if ($bid_amount > 1 ) {
                             $data['ADVERTISEMENT_KEYWORD'][$temp_keywords[$i]] =
@@ -146,11 +151,11 @@ class AdvertisementComponent extends Component
                         $expensive_bid = $keyword_bid_amount;
                         $data['EXPENSIVE_KEYWORD'] = $temp_keywords[$i];
                     }
-                    $temp_date = date(ADV_DATE_FORMAT,
+                    $temp_date = date(AD_DATE_FORMAT,
                         strtotime($temp_date .' +1 day'));
                 }
             }
-            $data['ADV_MIN_BID'] = $min_bid_reqd;
+            $data['AD_MIN_BID'] = $min_bid_reqd;
             foreach ($adv_fields as $field) {
                 if(isset($_REQUEST[$field])) {
                     $data[$field] = $parent->
@@ -161,7 +166,17 @@ class AdvertisementComponent extends Component
                 $data['NEW_KEYWORDS']= implode(",", $temp_keywords);
             }
             if (!empty($new_keywords)) {
-                $advkeyword_model->addKeywords($new_keywords);
+                $adkeyword_model->addKeywords($new_keywords);
+            }
+        }
+        if (isset($_REQUEST['edit-keywords'])) {
+            $advertisement_fields = array("start_row", "num_show", "end_row",
+                "AD_NAME", "AD_DESTINATION", "AD_DESCRIPTION",
+                "AD_KEYWORDS", "AD_BUDGET", "AD_START_DATE", "AD_END_DATE");
+            foreach ($advertisement_fields as $field) {
+                if (isset($_REQUEST[$field])) {
+                    $data[$field] = $_REQUEST[$field];
+                }
             }
         }
         $possible_arguments = array("addadvertisement", 'editadvertisement',
@@ -173,10 +188,10 @@ class AdvertisementComponent extends Component
         $data['PAGING'] = "";
         $search_array = array();
         if (isset($_REQUEST['adv'])) {
-            $adv_id = substr($parent->clean($_REQUEST['adv'], "string"),
+            $ad_id = substr($parent->clean($_REQUEST['adv'], "string"),
                 0, strlen($_REQUEST['adv']));
         } else {
-            $adv_id = "";
+            $ad_id = "";
         }
         if (isset($_REQUEST['arg']) &&
             in_array($_REQUEST['arg'], $possible_arguments)) {
@@ -186,9 +201,9 @@ class AdvertisementComponent extends Component
                         $advertisement = array();
                         $associated_keywords = array();
                         $advertisement['USER_ID'] = $user_id;
-                        $fields = array("ADV_NAME", "ADV_DESCRIPTION",
-                            "ADV_DESTINATION", "ADV_BUDGET", "ADV_KEYWORDS",
-                            "ADV_START_DATE", "ADV_END_DATE");
+                        $fields = array("AD_NAME", "AD_DESCRIPTION",
+                            "AD_DESTINATION", "AD_BUDGET", "AD_KEYWORDS",
+                            "AD_START_DATE", "AD_END_DATE");
                         foreach ($fields as $field) {
                             if (isset($_REQUEST[$field])) {
                                 $advertisement[$field] = $parent->
@@ -196,7 +211,7 @@ class AdvertisementComponent extends Component
                                 $data['ADV'][$field] = $advertisement[$field];
                             }
                         }
-                        if (empty($_REQUEST['ADV_KEYWORDS'])) {
+                        if (empty($_REQUEST['AD_KEYWORDS'])) {
                             $parent->redirectWithMessage(
                                 tl('advertisement_component_enter_keywords'),
                                 array_merge((array)$_REQUEST['arg'],
@@ -209,44 +224,44 @@ class AdvertisementComponent extends Component
                                 $parent->clean($_REQUEST['NEW_KEYWORDS'],
                                 "string")));
                         }
-                        if (isset($_REQUEST['ADV_KEYWORDS'])) {
+                        if (isset($_REQUEST['AD_KEYWORDS'])) {
                             $keywords = explode(",", strtolower($parent->
-                                clean($_REQUEST['ADV_KEYWORDS'], "string")));
+                                clean($_REQUEST['AD_KEYWORDS'], "string")));
                         }
-                        $budget = $parent->clean($_REQUEST['ADV_BUDGET'],
+                        $budget = $parent->clean($_REQUEST['AD_BUDGET'],
                             "string");
-                        $min_bid = $parent->clean($_REQUEST['ADV_MIN_BID'],
+                        $min_bid = $parent->clean($_REQUEST['AD_MIN_BID'],
                             "string");
-                        $adv_start_date = $parent->
-                            clean($_REQUEST['ADV_START_DATE'], "string");
-                        $adv_end_date = $parent->
-                            clean($_REQUEST['ADV_END_DATE'], "string");
+                        $ad_start_date = $parent->
+                            clean($_REQUEST['AD_START_DATE'], "string");
+                        $ad_end_date = $parent->
+                            clean($_REQUEST['AD_END_DATE'], "string");
                         if ($budget < $min_bid) {
                             $parent->redirectWithMessage(
                                 tl('advertisement_component_budget_less'),
                                 array_merge((array)$_REQUEST['arg'],
                                 $request_fields));
                         }
-                        $adv_date_diff = strtotime($adv_end_date) -
-                            strtotime($adv_start_date);
-                        $adv_day_count = $adv_date_diff/ONE_DAY + 1;
+                        $ad_date_diff = strtotime($ad_end_date) -
+                            strtotime($ad_start_date);
+                        $adv_day_count = $ad_date_diff/ONE_DAY + 1;
                         foreach ($keywords as $keyword) {
-                            $temp_date = $adv_start_date;
+                            $temp_date = $ad_start_date;
                             for ( $j = 0 ; $j < $adv_day_count ; $j++ ) {
-                                $day_bid_amt = $advkeyword_model ->
+                                $day_bid_amt = $adkeyword_model ->
                                     getBidAmount($keyword,$temp_date);
                                 if (in_array(strtolower($keyword),
                                     $new_keywords)) {
                                     if ($day_bid_amt > 1) {
                                        $updated_budget =
                                        (($day_bid_amt/2)/$min_bid) * $budget;
-                                        $advkeyword_model->
+                                        $adkeyword_model->
                                         updateBidAmount($keyword,
                                             $updated_budget, $temp_date, false);
                                     } else {
                                         $updated_budget =
                                             ($day_bid_amt / $min_bid) * $budget;
-                                        $advkeyword_model->updateBidAmount(
+                                        $adkeyword_model->updateBidAmount(
                                             $keyword, $updated_budget,
                                             $temp_date, true);
                                     }
@@ -254,32 +269,34 @@ class AdvertisementComponent extends Component
                                     $updated_budget = ($day_bid_amt > 1) ?
                                         (($day_bid_amt/2)/$min_bid) * $budget :
                                         (($day_bid_amt)/$min_bid) * $budget;
-                                    $advkeyword_model->
+                                    $adkeyword_model->
                                         updateBidAmount($keyword, 
                                         $updated_budget, $temp_date, false);
                                 }
-                                $temp_date = date(ADV_DATE_FORMAT,
+                                $temp_date = date(AD_DATE_FORMAT,
                                     strtotime($temp_date .' +1 day'));
                             }
                         }
-                        $temp_date = $adv_start_date;
+                        $temp_date = $ad_start_date;
                         for ( $k = 0; $k < $adv_day_count; $k++ ) {
                             $advertisement_model ->
                             addAdvertisement($advertisement, $temp_date,
                                 $user_id);
-                            $temp_date = date(ADV_DATE_FORMAT,
+                            $temp_date = date(AD_DATE_FORMAT,
                                 strtotime($temp_date .' +1 day'));
                         }
-                        $advertisement['ADV_KEYWORDS'] =
+                        $advertisement['AD_KEYWORDS'] =
                             strtolower(implode(",", $associated_keywords));
                         unset($data['ADVERTISEMENT_KEYWORD']);
+                        unset($data['AD_MIN_BID']);
                         $parent->redirectWithMessage(
                             tl('advertisement_component_ad_created'),
-                        array_merge((array)$_REQUEST['arg'], $request_fields));
+                        array_merge((array)$_REQUEST['arg']),array
+                        ("start_row", "num_show", "end_row"));
                     }
                     break;
                 case "deleteadvertisement":
-                    if ($adv_id <= 0) {
+                    if ($ad_id <= 0) {
                         $parent->redirectWithMessage(
                         tl('advertisement_component_advertisement_doesnt_exists'
                             ),
@@ -287,7 +304,7 @@ class AdvertisementComponent extends Component
                     } else {
                         $status = $_REQUEST['status'];
                         $result = $advertisement_model->
-                            deactivateAdvertisement($adv_id, $status);
+                            deactivateAdvertisement($ad_id, $status);
                         if ($result) {
                          $parent->redirectWithMessage(tl(
                             'advertisement_component_status_changed'),
@@ -297,35 +314,36 @@ class AdvertisementComponent extends Component
                     }
                     break;
                 case "editadvertisement":
+                    var_dump($_REQUEST);
                     $data["FORM_TYPE"] = "editadvertisement";
                     $update = false;
                     if (isset($_REQUEST['save'])) {
                         $update = true;
                     }
-                    if (isset($_REQUEST['adv_ids'])) {
-                        $adv_ids = substr($parent->clean
-                        ($_REQUEST['adv_ids'],
-                            "string"), 0, strlen($_REQUEST['adv_ids']));
+                    if (isset($_REQUEST['ad_ids'])) {
+                        $ad_ids = substr($parent->clean
+                        ($_REQUEST['ad_ids'],
+                            "string"), 0, strlen($_REQUEST['ad_ids']));
                         $advertisement = $advertisement_model->
-                            getAdvertisementByIds($adv_ids);
+                            getAdvertisementByIds($ad_ids);
                         usort($advertisement, array("AdvertisementComponent",
                             "dateSortFunc"));
-                        $adv_fields = array("ADV_NAME", "ADV_DESTINATION",
-                            "ADV_DESCRIPTION","ADV_BUDGET","ADV_KEYWORDS",
-                            "ADV_DATE");
+                        $adv_fields = array("AD_NAME", "AD_DESTINATION",
+                            "AD_DESCRIPTION","AD_BUDGET","AD_KEYWORDS",
+                            "AD_DATE");
                         $i = 0;
                         if (!empty($advertisement)) {
                             foreach ($adv_fields as $field) {
                                 $data[$field] = $advertisement[$i][$field];
                             }
-                            $data['ADV_START_DATE'] =
-                                $advertisement[$i]['ADV_DATE'];
-                            $data['ADV_END_DATE'] =
-                            $advertisement[count($advertisement)-1]['ADV_DATE'];
+                            $data['AD_START_DATE'] =
+                                $advertisement[$i]['AD_DATE'];
+                            $data['AD_END_DATE'] =
+                            $advertisement[count($advertisement)-1]['AD_DATE'];
                             if ($update) {
                                 $updated_advertisement = array();
-                                $adv_update_fields = array("ADV_NAME",
-                                "ADV_DESCRIPTION","ADV_DESTINATION");
+                                $adv_update_fields = array("AD_NAME",
+                                "AD_DESCRIPTION","AD_DESTINATION");
                                 foreach ($adv_update_fields as $field) {
                                     if (isset($_REQUEST[$field])) {
                                         $updated_advertisement[$field] =
@@ -335,12 +353,12 @@ class AdvertisementComponent extends Component
                                 }
                                 $advertisement_model ->
                                    updateAdvertisement($updated_advertisement,
-                                       $adv_ids);
+                                       $ad_ids);
                                 foreach ($request_fields as $field) {
                                     unset($data[$field]);
                                 }
-                                unset($data['ADV_START_DATE']);
-                                unset($data['ADV_END_DATE']);
+                                unset($data['AD_START_DATE']);
+                                unset($data['AD_END_DATE']);
                                 $parent->redirectWithMessage(
                                     tl('advertisement_component_ad_updated'),
                                     array_merge((array)$_REQUEST['arg'],
@@ -370,7 +388,7 @@ class AdvertisementComponent extends Component
      */
     function dateSortFunc($date1, $date2)
     {
-        return strtotime($date1["ADV_DATE"]) - strtotime($date2["ADV_DATE"]);
+        return strtotime($date1["AD_DATE"]) - strtotime($date2["AD_DATE"]);
     }
     /**
      *Trim white spaces in array elements
diff --git a/controllers/components/system_component.php b/controllers/components/system_component.php
index bd43554..662f500 100755
--- a/controllers/components/system_component.php
+++ b/controllers/components/system_component.php
@@ -498,6 +498,8 @@ class SystemComponent extends Component
     {
         $parent = $this->parent;
         $profile_model = $parent->model("profile");
+        $role_model = $parent->model("role");
+        $user_id = $_SESSION['USER_ID'];
         $data = array();
         $profile = array();
         $arg = "";
@@ -515,6 +517,19 @@ class SystemComponent extends Component
                     'USE_PROXY'));
                 $old_profile =
                     $profile_model->getProfile(WORK_DIRECTORY);
+                if (strcmp($old_profile["ADVERTISEMENT_TYPE"],
+                        $data["ADVERTISEMENT_TYPE"]) !== 0) {
+                    $business_id = $role_model->getRoleId('Business User');
+                    if (isset($data['ADVERTISEMENT_TYPE']) &&
+                        in_array($data['ADVERTISEMENT_TYPE'],
+                            array('no_advertisements',
+                                'external_advertisements'))
+                    ) {
+                        $role_model->deleteUserRole($user_id, $business_id);
+                    } else {
+                        $role_model->addUserRole($user_id, $business_id);
+                    }
+                }
                 $db_problem = false;
                 if ((isset($profile['DBMS']) &&
                     $profile['DBMS'] != $old_profile['DBMS']) ||
@@ -575,12 +590,26 @@ class SystemComponent extends Component
                 'admin_activation' =>
                     tl('system_component_configure_admin_activation'),
             );
+        $data['ADVERTISEMENT_TYPES'] = array (
+            'no_advertisements' =>
+                tl('system_component_configure_no_advertisements'),
+            'yioop_advertisements' =>
+                tl('system_component_configure_yioop_advertisements'),
+            'external_advertisements' =>
+                tl('system_component_configure_external_advertisements'),
+             );
         $data['show_mail_info'] = "false";
         if (isset($data['REGISTRATION_TYPE']) &&
             in_array($data['REGISTRATION_TYPE'], array(
             'email_registration', 'admin_activation'))) {
             $data['show_mail_info'] = "true";
         }
+        $data['show_ad_info'] = "false";
+        if (isset($data['ADVERTISEMENT_TYPE']) &&
+            in_array($data['ADVERTISEMENT_TYPE'], array(
+                'no_advertisements', 'yioop_advertisements'))) {
+            $data['show_ad_info'] = "true";
+        }
         $data['no_mail_php'] =  ($data["USE_MAIL_PHP"]) ? "false" :"true";
         $data['SCRIPT'] .= <<< EOD
     elt('account-registration').onchange = function () {
@@ -606,6 +635,15 @@ class SystemComponent extends Component
         setDisplay('proxy', (elt('use-proxy').checked) ? true : false);
     };
     setDisplay('proxy', (elt('use-proxy').checked) ? true : false);
+    elt('ad-registration').onchange = function () {
+        var show_ad_info = false;
+        no_external_ad = ['no_advertisements', 'yioop_advertisements'];
+        if (no_external_ad.indexOf(elt('ad-registration').value)
+            < 0) {
+            show_ad_info = true;
+        }
+        setDisplay('ad-location-info', show_ad_info);
+    };
 EOD;
         if (class_exists("Memcache")) {
             $data['SCRIPT'] .= <<< EOD
diff --git a/controllers/search_controller.php b/controllers/search_controller.php
index 35005f8..0874834 100755
--- a/controllers/search_controller.php
+++ b/controllers/search_controller.php
@@ -750,24 +750,24 @@ class SearchController extends Controller implements CrawlConstants
                 }
                 $data['QUERY'] = urlencode($this->clean($query,"string"));
                 $data['ELEMENT'] = "displayadvertisement";
-                $advmetadata_model = $this->model("advmetadata");
+                $admetadata_model = $this->model("admetadata");
                 if (isset($_REQUEST['a']) && $_REQUEST['a'] == ADV_SAVE_CLICK) {
-                    $advmetadata_model = $this->model("advmetadata");
-                    $advmetadata_model -> addClick($arg);
+                    $admetadata_model = $this->model("admetadata");
+                    $admetadata_model -> addClick($arg);
                 } else {
                     $data['RELEVANT_ADVERTISEMENT'] = $this->
                     getRelevantAdvertisements($query);
-                    if ($advmetadata_model->isAdvMetadataPresent(
-                        $data['RELEVANT_ADVERTISEMENT']['ADV_ID'])
+                    if ($admetadata_model->isAdvMetadataPresent(
+                        $data['RELEVANT_ADVERTISEMENT']['AD_ID'])
                     ) {
-                        $advmetadata_model->addImpression(
-                            $data['RELEVANT_ADVERTISEMENT']['ADV_ID'],
+                        $admetadata_model->addImpression(
+                            $data['RELEVANT_ADVERTISEMENT']['AD_ID'],
                             false);
                     } else if (!empty
-                    ($data['RELEVANT_ADVERTISEMENT']['ADV_ID'])
+                    ($data['RELEVANT_ADVERTISEMENT']['AD_ID'])
                     ) {
-                        $advmetadata_model->addImpression
-                        ($data['RELEVANT_ADVERTISEMENT']['ADV_ID'], true);
+                        $admetadata_model->addImpression
+                        ($data['RELEVANT_ADVERTISEMENT']['AD_ID'], true);
                     }
                 }
             break;
@@ -2020,14 +2020,14 @@ class SearchController extends Controller implements CrawlConstants
             uasort($relevant_ads, array($this, 'compare'));
             $max_limit = 0;
             foreach ($relevant_ads as $temp_adv) {
-                $max_limit = $max_limit + $temp_adv['ADV_BUDGET'];
+                $max_limit = $max_limit + $temp_adv['AD_BUDGET'];
             }
             $random_value = mt_rand(0, $max_limit);
             $closest_ad = $relevant_ads[0];
             $min = 0;
             $max = 0;
             foreach ($relevant_ads as $advertisement) {
-                $max = $max + $advertisement['ADV_BUDGET'];
+                $max = $max + $advertisement['AD_BUDGET'];
                 if (($random_value > $min) && ($random_value < $max)) {
                     $closest_ad = $advertisement;
                 }
@@ -2041,10 +2041,10 @@ class SearchController extends Controller implements CrawlConstants
      */
     function compare($adv1, $adv2)
     {
-        if ($adv1['ADV_BUDGET'] == $adv2['ADV_BUDGET']) {
+        if ($adv1['AD_BUDGET'] == $adv2['AD_BUDGET']) {
             return 0;
         }
-        return ($adv1['ADV_BUDGET'] < $adv2['ADV_BUDGET']) ? -1 : 1;
+        return ($adv1['AD_BUDGET'] < $adv2['AD_BUDGET']) ? -1 : 1;
     }
 
 }
diff --git a/css/search.css b/css/search.css
index 7148d49..4a6a946 100755
--- a/css/search.css
+++ b/css/search.css
@@ -2759,7 +2759,7 @@ button.default
     padding: 0.05in;
     position: relative;
     right: 0.5in;
-    top: -0.9in;
+    top: -1.1in;
     max-width:8in;
 }
 .top-ad-static,
diff --git a/data/default.db b/data/default.db
index 8b70282526f5a35739fae1bc334819c871db535b..1343d9a96614223a0a021a57b3084e3de98bed0e 100644
GIT binary patch
diff --git a/lib/upgrade_functions.php b/lib/upgrade_functions.php
index bcba8ce..ea27cfc 100644
--- a/lib/upgrade_functions.php
+++ b/lib/upgrade_functions.php
@@ -1107,21 +1107,21 @@ function upgradeDatabaseVersion32(&$db)
     $db->execute("DELETE FROM VERSION WHERE ID < 31");
     $db->execute("UPDATE VERSION SET ID=32 WHERE ID=31");
     $db->execute("ALTER TABLE USERS ADD COLUMN IS_ADVERTISER INTEGER");
-    $db->execute("CREATE TABLE ADVERTISEMENTS(ADV_ID INTEGER
+    $db->execute("CREATE TABLE ADVERTISEMENTS(AD_ID INTEGER
         PRIMARY KEY $auto_increment, USER_ID INTEGER,
-        ADV_NAME VARCHAR(". ADVERTISEMENT_NAME_LEN ."),
-        ADV_DESCRIPTION VARCHAR(". ADVERTISEMENT_TEXT_LEN ."),
-        ADV_DESTINATION VARCHAR(". ADVERTISEMENT_DESTINATION_LEN ."),
-        ADV_KEYWORDS VARCHAR(". ADVERTISEMENT_KEYWORD_LEN ."),
-        STATUS INTEGER, ADV_BUDGET INTEGER,
-        ADV_DATE VARCHAR(". ADVERTISEMENT_DATE_LEN ."))");
+        AD_NAME VARCHAR(". ADVERTISEMENT_NAME_LEN ."),
+        AD_DESCRIPTION VARCHAR(". ADVERTISEMENT_TEXT_LEN ."),
+        AD_DESTINATION VARCHAR(". ADVERTISEMENT_DESTINATION_LEN ."),
+        AD_KEYWORDS VARCHAR(". ADVERTISEMENT_KEYWORD_LEN ."),
+        STATUS INTEGER, AD_BUDGET INTEGER,
+        AD_DATE VARCHAR(". ADVERTISEMENT_DATE_LEN ."))");
     $db->execute("CREATE TABLE ADVERTISEMENT_KEYWORD
         (ID INTEGER PRIMARY KEY $auto_increment,
         KEYWORD VARCHAR(". ADVERTISEMENT_KEYWORD_LEN ."),
         BID_AMOUNT INTEGER,
         BID_DATE VARCHAR(". ADVERTISEMENT_DATE_LEN ."))");
     $db->execute("CREATE TABLE ADVERTISEMENT_METADATA
-        (ADV_ID INTEGER, CLICKS INTEGER, IMPRESSIONS INTEGER)");
+        (AD_ID INTEGER, CLICKS INTEGER, IMPRESSIONS INTEGER)");
     addActivityAtId($db, 'db_activity_manage_advertisement',
         "manageAdvertisements", 17);
     updateTranslationForStringId($db, 'db_activity_manage_advertisement',
diff --git a/models/adkeyword_model.php b/models/adkeyword_model.php
new file mode 100644
index 0000000..c0a0d60
--- /dev/null
+++ b/models/adkeyword_model.php
@@ -0,0 +1,173 @@
+<?php
+/**
+ * SeekQuarry/Yioop --
+ * Open Source Pure PHP Search Engine, Crawler, and Indexer
+ *
+ * Copyright (C) 2009 - 2015  Chris Pollett chris@pollett.org
+ *
+ * LICENSE:
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * END LICENSE
+ *
+ * @author Pushkar Umaranikar
+ * @license http://www.gnu.org/licenses/ GPL3
+ * @link http://www.seekquarry.com/
+ * @copyright 2009 - 2015
+ * @filesource
+ */
+if (!defined('BASE_DIR')) {echo "BAD REQUEST"; exit();}
+/** Loads the base class */
+require_once BASE_DIR."/models/model.php";
+
+
+/**
+ * This class is used to handle
+ * database statements related to Advertisement_keyword
+ *
+ * @author Pushkar Umaranikar
+ * @package seek_quarry\model
+ */
+class AdKeywordModel extends Model
+{
+    /**
+     * Associations of the form
+     * name of field for web forms => database column names/abbreviations
+     * In this case, things will in general map to the USERS table in the
+     * Yioop data base
+     * var array
+     */
+    var $search_table_column_map = array("id"=>"ID",
+        "keyword" => "KEYWORD", "bid" => "BID_AMOUNT", "date" => "BID_DATE");
+    /**
+     * These fields if present in $search_array (used by @see getRows() ),
+     * but with value "-1", will be skipped as part of the where clause
+     * but will be used for order by clause
+     * @var array
+     */
+    var $any_fields = array("status");
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function selectCallback($args = NULL)
+    {
+        return "ID, KEYWORD, BID_AMOUNT, BID_DATE";
+    }
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function fromCallback($args = NULL)
+    {
+        return "ADVERTISEMENT_KEYWORD";
+    }
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function whereCallback($args = NULL)
+    {
+        return "";
+    }
+    /**
+     * {@inheritDoc}
+     * @param string $adv_keyword list of keywords
+     *
+     */
+    function addKeywords($adv_keyword)
+    {
+        $db = $this->db;
+        $sql = "INSERT INTO ADVERTISEMENT_KEYWORD(KEYWORD, BID_AMOUNT, BID_DATE)
+            VALUES (?, ?, ?)";
+        for ($i=0; $i< count($adv_keyword); $i++ ) {
+           $result = $db->execute($sql, array($adv_keyword[$i]['KEYWORD'],
+               $adv_keyword[$i]['BID_AMOUNT'], $adv_keyword[$i]['BID_DATE']));
+        }
+    }
+    /**
+     * Deletes advertisement
+     *
+     * @param string $ad_id  the id of the advertisement
+     */
+    function deleteKeyword($keyword)
+    {
+        $sql = "DELETE FROM ADVERTISEMENT_KEYWORD WHERE KEYWORD=?";
+        $result = $this->db->execute($sql, array($keyword));
+    }
+    /**
+     * Checks if keyword is present or not
+     *
+     * @param string $keyword the keyword associated with advertisement
+     * @param date $bid_date date associated with keyword
+     * @return true or false representing keyword present or not
+     */
+    function isKeywordPresent($keyword, $bid_date)
+    {
+        $db = $this->db;
+        $sql = "SELECT KEYWORD FROM ADVERTISEMENT_KEYWORD WHERE KEYWORD=? AND
+            BID_DATE= ?";
+        $result = $db->execute($sql,array($keyword, $bid_date));
+        if ($result) {
+            if ($mix = $db->fetchArray($result)) {
+                return true;
+            } else {
+                return false;
+            }
+        }
+    }
+    /**
+     * Returns bid amount associated with keyword
+     *
+     * @param string $keyword the keyword associated with advertisement
+     * @param date $bid_date date associated with keyword
+     * @return integer value representing bid amount
+     */
+    function getBidAmount($keyword,$bid_date)
+    {
+        $db = $this->db;
+        $sql= "SELECT BID_AMOUNT FROM ADVERTISEMENT_KEYWORD WHERE KEYWORD=? AND
+            BID_DATE=?";
+        $result = $db->execute($sql, array($keyword,$bid_date));
+        if (!$result) {
+            return false;
+        }
+        $row = $db->fetchArray($result);
+        return $row['BID_AMOUNT'];
+    }
+    /**
+     * updates the bid amount
+     *
+     * @param string $keyword the keyword associated with advertisement
+     * @param integer $bid_amount associated with keyword
+     * @param date $bid_date associated with keyword
+     */
+    function updateBidAmount($keyword,$bid_amount,$bid_date,$is_new)
+    {
+        $db = $this->db;
+        ($is_new) ?
+        $sql= "UPDATE ADVERTISEMENT_KEYWORD SET BID_AMOUNT= ? WHERE KEYWORD=?
+               AND BID_DATE=?":
+        $sql= "UPDATE ADVERTISEMENT_KEYWORD SET BID_AMOUNT= BID_AMOUNT +? WHERE
+               KEYWORD=? AND BID_DATE=?";
+        $result = $db->execute($sql,array($bid_amount,$keyword,$bid_date));
+    }
+}
diff --git a/models/admetadata_model.php b/models/admetadata_model.php
new file mode 100644
index 0000000..21d3af4
--- /dev/null
+++ b/models/admetadata_model.php
@@ -0,0 +1,145 @@
+<?php
+/**
+ * SeekQuarry/Yioop --
+ * Open Source Pure PHP Search Engine, Crawler, and Indexer
+ *
+ * Copyright (C) 2009 - 2015  Chris Pollett chris@pollett.org
+ *
+ * LICENSE:
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * END LICENSE
+ *
+ * @author Pushkar Umaranikar
+ * @license http://www.gnu.org/licenses/ GPL3
+ * @link http://www.seekquarry.com/
+ * @copyright 2009 - 2015
+ * @filesource
+ */
+if (!defined('BASE_DIR')) {echo "BAD REQUEST"; exit();}
+/** Loads the base class */
+require_once BASE_DIR."/models/model.php";
+
+
+/**
+ * This class is used to handle
+ * database statements related to Advertisement Metadata
+ *
+ * @author Pushkar Umaranikar
+ * @package seek_quarry\model
+ */
+class AdMetaDataModel extends Model
+{
+    /**
+     * Associations of the form
+     *     name of field for web forms => database column names/abbreviations
+     * In this case, things will in general map to the USERS table in the
+     * Yioop data base
+     * var array
+     */
+    var $search_table_column_map = array("id"=>"AD_ID",
+        "clicks" => "CLICKS", "impressions" => "IMPRESSIONS",);
+    /**
+     * These fields if present in $search_array (used by @see getRows() ),
+     * but with value "-1", will be skipped as part of the where clause
+     * but will be used for order by clause
+     * @var array
+     */
+    var $any_fields = array("status");
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function selectCallback($args = NULL)
+    {
+        return "AD_ID, CLICKS, IMPRESSIONS";
+    }
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function fromCallback($args = NULL)
+    {
+        return "ADVERTISEMENT_METADATA";
+    }
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function whereCallback($args = NULL)
+    {
+        return "";
+    }
+    /**
+     * Checks if advertisement metadata present or not
+     *
+     * @param integer $ad_id represents advertisement id
+     * @return boolean value representing metedata present or not
+     */
+    function isAdvMetadataPresent($ad_id)
+    {
+        $db = $this->db;
+        $sql = "SELECT AD_ID FROM ADVERTISEMENT_METADATA WHERE AD_ID = ?";
+        $result = $db->execute($sql,array($ad_id));
+        if ($result) {
+            if ($mix = $db->fetchArray($result)) {
+                return true;
+            } else {
+                return false;
+            }
+        }
+    }
+    /**
+     * Records number of impressions for an advertisement
+     *
+     * @param string $ad_id of an advertisement
+     * @param boolean $is_new Checks if advertisement is newly created or not
+     */
+    function addImpression($ad_id,$is_new)
+    {
+        $db = $this->db;
+        $clicks = 0;
+        $impressions = 1;
+        if ($is_new) {
+            $sql = "INSERT INTO ADVERTISEMENT_METADATA
+            (AD_ID,CLICKS,IMPRESSIONS) VALUES (?, ?, ?)";
+         $result = $db->execute($sql,array(
+             $ad_id,$clicks,$impressions));
+        } else {
+            $sql= "UPDATE ADVERTISEMENT_METADATA SET
+            IMPRESSIONS= IMPRESSIONS +1 WHERE AD_ID = ?";
+            $result = $db->execute($sql,array($ad_id));
+        }
+    }
+    /**
+     * Records the number of clicks for an advertisement
+     *
+     * @param integer $ad_id advertisement id
+     */
+    function addClick($ad_id)
+    {
+        $db = $this->db;
+        $sql = "UPDATE ADVERTISEMENT_METADATA SET CLICKS = CLICKS + 1 WHERE
+        AD_ID = ?";
+        $result = $db->execute($sql,array($ad_id));
+    }
+}
+?>
diff --git a/models/advertisement_model.php b/models/advertisement_model.php
index 0a12116..d85ec56 100644
--- a/models/advertisement_model.php
+++ b/models/advertisement_model.php
@@ -49,10 +49,10 @@ class AdvertisementModel extends Model
      * in the Yioop data base
      * var array
      */
-    var $search_table_column_map = array("name"=>"ADV_NAME",
-        "description" => "ADV_DESCRIPTION", "destination" => "ADV_DESTINATION",
-        "keywords"=>"ADV_KEYWORDS","status"=>"STATUS",
-        "budget" => "ADV_BUDGET");
+    var $search_table_column_map = array("name"=>"AD_NAME",
+        "description" => "AD_DESCRIPTION", "destination" => "AD_DESTINATION",
+        "keywords"=>"AD_KEYWORDS","status"=>"STATUS",
+        "budget" => "AD_BUDGET");
     /**
      * These fields if present in $search_array (used by @see getRows() ),
      * but with value "-1", will be skipped as part of the where clause
@@ -68,8 +68,8 @@ class AdvertisementModel extends Model
      */
     function selectCallback($args = NULL)
     {
-        return "ADV_NAME, ADV_DESTINATION, ADV_KEYWORDS,
-        STATUS, ADV_BUDGET";
+        return "AD_NAME, AD_DESTINATION, AD_KEYWORDS,
+        STATUS, AD_BUDGET";
     }
     /**
      * {@inheritDoc}
@@ -79,8 +79,8 @@ class AdvertisementModel extends Model
      */
     function fromCallback($args = NULL)
     {
-        return "(SELECT DISTINCT ADV_NAME, USER_ID, ADV_DESCRIPTION,
-        ADV_DESTINATION, ADV_KEYWORDS, STATUS, ADV_BUDGET FROM ADVERTISEMENTS)";
+        return "(SELECT DISTINCT AD_NAME, USER_ID, AD_DESCRIPTION,
+        AD_DESTINATION, AD_KEYWORDS, STATUS, AD_BUDGET FROM ADVERTISEMENTS)";
     }
     /**
      * {@inheritDoc}
@@ -101,53 +101,53 @@ class AdvertisementModel extends Model
      * Adds newly created advertisement
      *
      * @param $advertisement_advertisement to be added
-     * @param String $adv_start_date start date for an advertisement
+     * @param String $ad_start_date start date for an advertisement
      * @param String $user_id user id of user who created advertisement
      * @param boolean is_new represents advertisement exists or not
      */
-    function addAdvertisement($advertisement, $adv_start_date, $user_id,
+    function addAdvertisement($advertisement, $ad_start_date, $user_id,
                               $is_new=true)
     {
         $db = $this->db;
         $ad_status = ADVERTISEMENT_ACTIVE_STATUS;
         if ($is_new) {
-            $sql = "INSERT INTO ADVERTISEMENTS(USER_ID, ADV_NAME,
-            ADV_DESCRIPTION,ADV_DESTINATION, ADV_KEYWORDS, STATUS, ADV_BUDGET,
-            ADV_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
+            $sql = "INSERT INTO ADVERTISEMENTS(USER_ID, AD_NAME,
+            AD_DESCRIPTION,AD_DESTINATION, AD_KEYWORDS, STATUS, AD_BUDGET,
+            AD_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
             $result = $db->execute($sql, array($user_id,
-                $advertisement['ADV_NAME'], $advertisement['ADV_DESCRIPTION'],
-                $advertisement['ADV_DESTINATION'],
-                $advertisement['ADV_KEYWORDS'], $ad_status,
-                $advertisement['ADV_BUDGET'], $adv_start_date));
+                $advertisement['AD_NAME'], $advertisement['AD_DESCRIPTION'],
+                $advertisement['AD_DESTINATION'],
+                $advertisement['AD_KEYWORDS'], $ad_status,
+                $advertisement['AD_BUDGET'], $ad_start_date));
         } else {
-            $sql = "INSERT INTO ADVERTISEMENTS(ADV_ID, USER_ID, ADV_NAME,
-            ADV_DESCRIPTION,ADV_DESTINATION, ADV_KEYWORDS, STATUS, ADV_BUDGET,
-            ADV_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
-            $result = $db->execute($sql, array($advertisement['ADV_ID'],
-                $user_id, $advertisement['ADV_NAME'],
-                $advertisement['ADV_DESCRIPTION'],
-                $advertisement['ADV_DESTINATION'],
-                $advertisement['ADV_KEYWORDS'],
-                $ad_status, $advertisement['ADV_BUDGET'], $adv_start_date));
+            $sql = "INSERT INTO ADVERTISEMENTS(AD_ID, USER_ID, AD_NAME,
+            AD_DESCRIPTION, AD_DESTINATION, AD_KEYWORDS, STATUS, AD_BUDGET,
+            AD_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
+            $result = $db->execute($sql, array($advertisement['AD_ID'],
+                $user_id, $advertisement['AD_NAME'],
+                $advertisement['AD_DESCRIPTION'],
+                $advertisement['AD_DESTINATION'],
+                $advertisement['AD_KEYWORDS'],
+                $ad_status, $advertisement['AD_BUDGET'], $ad_start_date));
         }
     }
     /**
      * Deletes advertisement
      *
-     * @param string $adv_id  the id of the advertisement
+     * @param string $ad_id  the id of the advertisement
      */
-    function deleteAdvertisement($adv_ids)
+    function deleteAdvertisement($ad_ids)
     {
-        $sql = "DELETE FROM ADVERTISEMENTS WHERE ADV_ID IN($adv_ids)";
+        $sql = "DELETE FROM ADVERTISEMENTS WHERE AD_ID IN($ad_ids)";
         $result = $this->db->execute($sql);
     }
     /**
      * Update advertisement
      *
      * @param object $advertisement_advertisement to be updated
-     * @param string $adv_ids comma separated list of advertisement ids
+     * @param string $ad_ids comma separated list of advertisement ids
      */
-    function updateAdvertisement($advertisement,$adv_ids)
+    function updateAdvertisement($advertisement,$ad_ids)
     {
         $sql = "UPDATE ADVERTISEMENTS SET ";
         $comma ="";
@@ -158,7 +158,7 @@ class AdvertisementModel extends Model
             $comma = ",";
                 $params[] = $value;
         }
-        $sql .= " WHERE ADV_ID IN($adv_ids)";
+        $sql .= " WHERE AD_ID IN($ad_ids)";
         $db = $this->db;
         $result = $db->execute($sql, $params);
     }
@@ -171,8 +171,8 @@ class AdvertisementModel extends Model
     function getAdvertisementByKeywords($query_chunks)
     {
         $deactivated_status = ADVERTISEMENT_DEACTIVE_STATUS;
-        $sql = "SELECT * FROM ADVERTISEMENTS WHERE ( ADV_KEYWORDS LIKE ";
-        $append_sql = " OR ADV_KEYWORDS LIKE ";
+        $sql = "SELECT * FROM ADVERTISEMENTS WHERE ( AD_KEYWORDS LIKE ";
+        $append_sql = " OR AD_KEYWORDS LIKE ";
         $counter = 1;
         $db = $this->db;
         foreach ($query_chunks as $temp_query) {
@@ -185,8 +185,8 @@ class AdvertisementModel extends Model
                 $counter++;
             }
         }
-        $today_date = date(ADV_DATE_FORMAT);
-        $sql = $sql . ")" . " AND ADV_DATE ="."'".$today_date."'";
+        $today_date = date(AD_DATE_FORMAT);
+        $sql = $sql . ")" . " AND AD_DATE ="."'".$today_date."'";
         $sql = $sql . " AND STATUS != $deactivated_status";
         $result = $db->execute($sql);
         $row = array();
@@ -200,15 +200,15 @@ class AdvertisementModel extends Model
     /**
      * Get advertisements for given advertisement ids
      *
-     * @param string $adv_ids advertisement ids
+     * @param string $ad_ids advertisement ids
      * @return array of advertisements
      */
-    function getAdvertisementByIds($adv_ids)
+    function getAdvertisementByIds($ad_ids)
     {
         $db = $this->db;
-        $sql = "SELECT ADV_NAME, ADV_DESCRIPTION, ADV_DESTINATION, ADV_KEYWORDS,
-        STATUS, ADV_BUDGET, ADV_DATE FROM ADVERTISEMENTS WHERE
-        ADV_ID IN ($adv_ids)";
+        $sql = "SELECT AD_NAME, AD_DESCRIPTION, AD_DESTINATION, AD_KEYWORDS,
+        STATUS, AD_BUDGET, AD_DATE FROM ADVERTISEMENTS WHERE
+        AD_ID IN ($ad_ids)";
         $result = $db->execute($sql);
         $advertisements = array();
         $i = 0;
@@ -221,15 +221,15 @@ class AdvertisementModel extends Model
     /**
      * Gets number of impressions for given advertisement ids
      *
-     * @param string $adv_ids advertisement ids
+     * @param string $ad_ids advertisement ids
      * @return count representing number of impressions
      */
-    function getImpressions($adv_ids)
+    function getImpressions($ad_ids)
     {
         $db = $this->db;
-        $ids = join(',',$adv_ids);
+        $ids = join(',',$ad_ids);
         $sql = "SELECT SUM(IMPRESSIONS) AS IMPRESSIONS FROM
-              ADVERTISEMENT_METADATA WHERE ADV_ID IN ($ids)";
+              ADVERTISEMENT_METADATA WHERE AD_ID IN ($ids)";
         $result = $db->execute($sql);
         $row = $db->fetchArray($result);
         return $row['IMPRESSIONS'];
@@ -237,24 +237,24 @@ class AdvertisementModel extends Model
     /**
      * Gets advertisement ids
      *
-     * @param string $adv_name advertisement name
-     * @param string $adv_destination url of the landing page
-     * @param string $adv_keywords comma separated list of keywords
+     * @param string $ad_name advertisement name
+     * @param string $ad_destination url of the landing page
+     * @param string $ad_keywords comma separated list of keywords
      * @return array of advertisement ids
      */
-    function getAdvertisementIds($adv_name,$adv_destination,$adv_keywords)
+    function getAdvertisementIds($ad_name,$ad_destination,$ad_keywords)
     {
         $db = $this->db;
-        $sql = "SELECT * FROM ADVERTISEMENTS WHERE ADV_NAME=? AND
-               ADV_DESTINATION=? AND ADV_KEYWORDS=?";
-        $result = $db->execute($sql, array($adv_name,$adv_destination,
-            $adv_keywords));
+        $sql = "SELECT * FROM ADVERTISEMENTS WHERE AD_NAME=? AND
+               AD_DESTINATION=? AND AD_KEYWORDS=?";
+        $result = $db->execute($sql, array($ad_name,$ad_destination,
+            $ad_keywords));
         $i = 0;
-        $adv_ids = array();
+        $ad_ids = array();
         while($row[$i] = $db->fetchArray($result)) {
-            array_push($adv_ids,$row[$i]['ADV_ID']);
+            array_push($ad_ids,$row[$i]['AD_ID']);
         }
-        return $adv_ids;
+        return $ad_ids;
     }
     /**
      * Gets all the advertisements for post query callback
@@ -266,18 +266,18 @@ class AdvertisementModel extends Model
     {
         $modified_rows = array();
         foreach ($rows as $row) {
-            $temp_advname = $row['ADV_NAME'];
-            $temp_advdestination = $row['ADV_DESTINATION'];
-            $temp_advkeywords = $row['ADV_KEYWORDS'];
-            $adv_ids = $this->getAdvertisementIds(
-                $temp_advname,$temp_advdestination, $temp_advkeywords);
-            $impressions = $this -> getImpressions($adv_ids);
-            $adv_dates = $this -> getAdvertisementdatesByIds($adv_ids);
-            usort($adv_dates,array("AdvertisementModel",
+            $temp_advname = $row['AD_NAME'];
+            $temp_advdestination = $row['AD_DESTINATION'];
+            $temp_adkeywords = $row['AD_KEYWORDS'];
+            $ad_ids = $this->getAdvertisementIds(
+                $temp_advname,$temp_advdestination, $temp_adkeywords);
+            $impressions = $this -> getImpressions($ad_ids);
+            $ad_dates = $this -> getAdvertisementdatesByIds($ad_ids);
+            usort($ad_dates,array("AdvertisementModel",
                 "sortByDate"));
-            $row['START_DATE'] = $adv_dates[0];
-            $row['END_DATE'] = $adv_dates[count($adv_dates)-1];
-            $row['ADV_IDS'] = join(',',$adv_ids);
+            $row['START_DATE'] = $ad_dates[0];
+            $row['END_DATE'] = $ad_dates[count($ad_dates)-1];
+            $row['AD_IDS'] = join(',',$ad_ids);
             $row['IMPRESSIONS'] = $impressions;
             array_push($modified_rows,$row);
         }
@@ -289,10 +289,10 @@ class AdvertisementModel extends Model
      * @param array of advertisement ids
      * @param integer value representing advertisement status
      */
-    function deactivateAdvertisement($adv_ids,$status)
+    function deactivateAdvertisement($ad_ids,$status)
     {
         $db = $this ->db;
-        $sql = "UPDATE ADVERTISEMENTS SET STATUS= ? WHERE ADV_ID IN ($adv_ids)";
+        $sql = "UPDATE ADVERTISEMENTS SET STATUS= ? WHERE AD_ID IN ($ad_ids)";
         $result = $db->execute($sql, array($status));
         return $result;
     }
@@ -303,17 +303,17 @@ class AdvertisementModel extends Model
      * @param array of advertisement ids
      * @return array of advertisements
      */
-    function getAdvertisementdatesByIds($adv_ids)
+    function getAdvertisementdatesByIds($ad_ids)
     {
         $db = $this ->db;
-        $ids = join(',',$adv_ids);
-        $sql = "SELECT ADV_DATE FROM ADVERTISEMENTS WHERE ADV_ID IN($ids)";
+        $ids = join(',',$ad_ids);
+        $sql = "SELECT AD_DATE FROM ADVERTISEMENTS WHERE AD_ID IN($ids)";
         $result = $db->execute($sql);
-        $adv_dates = array();
+        $ad_dates = array();
         while($row = $db->fetchArray($result)) {
-            array_push($adv_dates,$row['ADV_DATE']);
+            array_push($ad_dates,$row['AD_DATE']);
         }
-        return $adv_dates;
+        return $ad_dates;
     }
     /**
      * Comparator to sort array of advertisements by date
diff --git a/models/advkeyword_model.php b/models/advkeyword_model.php
deleted file mode 100644
index c3b70a3..0000000
--- a/models/advkeyword_model.php
+++ /dev/null
@@ -1,173 +0,0 @@
-<?php
-/**
- * SeekQuarry/Yioop --
- * Open Source Pure PHP Search Engine, Crawler, and Indexer
- *
- * Copyright (C) 2009 - 2015  Chris Pollett chris@pollett.org
- *
- * LICENSE:
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- * END LICENSE
- *
- * @author Pushkar Umaranikar
- * @license http://www.gnu.org/licenses/ GPL3
- * @link http://www.seekquarry.com/
- * @copyright 2009 - 2015
- * @filesource
- */
-if (!defined('BASE_DIR')) {echo "BAD REQUEST"; exit();}
-/** Loads the base class */
-require_once BASE_DIR."/models/model.php";
-
-
-/**
- * This class is used to handle
- * database statements related to Advertisement_keyword
- *
- * @author Pushkar Umaranikar
- * @package seek_quarry\model
- */
-class AdvKeywordModel extends Model
-{
-    /**
-     * Associations of the form
-     * name of field for web forms => database column names/abbreviations
-     * In this case, things will in general map to the USERS table in the
-     * Yioop data base
-     * var array
-     */
-    var $search_table_column_map = array("id"=>"ID",
-        "keyword" => "KEYWORD", "bid" => "BID_AMOUNT", "date" => "BID_DATE");
-    /**
-     * These fields if present in $search_array (used by @see getRows() ),
-     * but with value "-1", will be skipped as part of the where clause
-     * but will be used for order by clause
-     * @var array
-     */
-    var $any_fields = array("status");
-    /**
-     * {@inheritDoc}
-     *
-     * @param mixed $args any additional arguments which should be used to
-     *     determine these tables (in this case none)
-     */
-    function selectCallback($args = NULL)
-    {
-        return "ID, KEYWORD, BID_AMOUNT, BID_DATE";
-    }
-    /**
-     * {@inheritDoc}
-     *
-     * @param mixed $args any additional arguments which should be used to
-     *     determine these tables (in this case none)
-     */
-    function fromCallback($args = NULL)
-    {
-        return "ADVERTISEMENT_KEYWORD";
-    }
-    /**
-     * {@inheritDoc}
-     *
-     * @param mixed $args any additional arguments which should be used to
-     *     determine these tables (in this case none)
-     */
-    function whereCallback($args = NULL)
-    {
-        return "";
-    }
-    /**
-     * {@inheritDoc}
-     * @param string $adv_keyword list of keywords
-     *
-     */
-    function addKeywords($adv_keyword)
-    {
-        $db = $this->db;
-        $sql = "INSERT INTO ADVERTISEMENT_KEYWORD(KEYWORD, BID_AMOUNT, BID_DATE)
-            VALUES (?, ?, ?)";
-        for ($i=0; $i< count($adv_keyword); $i++ ) {
-           $result = $db->execute($sql, array($adv_keyword[$i]['KEYWORD'],
-               $adv_keyword[$i]['BID_AMOUNT'], $adv_keyword[$i]['BID_DATE']));
-        }
-    }
-    /**
-     * Deletes advertisement
-     *
-     * @param string $adv_id  the id of the advertisement
-     */
-    function deleteKeyword($keyword)
-    {
-        $sql = "DELETE FROM ADVERTISEMENT_KEYWORD WHERE KEYWORD=?";
-        $result = $this->db->execute($sql, array($keyword));
-    }
-    /**
-     * Checks if keyword is present or not
-     *
-     * @param string $keyword the keyword associated with advertisement
-     * @param date $bid_date date associated with keyword
-     * @return true or false representing keyword present or not
-     */
-    function isKeywordPresent($keyword, $bid_date)
-    {
-        $db = $this->db;
-        $sql = "SELECT KEYWORD FROM ADVERTISEMENT_KEYWORD WHERE KEYWORD=? AND
-            BID_DATE= ?";
-        $result = $db->execute($sql,array($keyword, $bid_date));
-        if ($result) {
-            if ($mix = $db->fetchArray($result)) {
-                return true;
-            } else {
-                return false;
-            }
-        }
-    }
-    /**
-     * Returns bid amount associated with keyword
-     *
-     * @param string $keyword the keyword associated with advertisement
-     * @param date $bid_date date associated with keyword
-     * @return integer value representing bid amount
-     */
-    function getBidAmount($keyword,$bid_date)
-    {
-        $db = $this->db;
-        $sql= "SELECT BID_AMOUNT FROM ADVERTISEMENT_KEYWORD WHERE KEYWORD=? AND
-            BID_DATE=?";
-        $result = $db->execute($sql, array($keyword,$bid_date));
-        if (!$result) {
-            return false;
-        }
-        $row = $db->fetchArray($result);
-        return $row['BID_AMOUNT'];
-    }
-    /**
-     * updates the bid amount
-     *
-     * @param string $keyword the keyword associated with advertisement
-     * @param integer $bid_amount associated with keyword
-     * @param date $bid_date associated with keyword
-     */
-    function updateBidAmount($keyword,$bid_amount,$bid_date,$is_new)
-    {
-        $db = $this->db;
-        ($is_new) ?
-        $sql= "UPDATE ADVERTISEMENT_KEYWORD SET BID_AMOUNT= ? WHERE KEYWORD=?
-               AND BID_DATE=?":
-        $sql= "UPDATE ADVERTISEMENT_KEYWORD SET BID_AMOUNT= BID_AMOUNT +? WHERE
-               KEYWORD=? AND BID_DATE=?";
-        $result = $db->execute($sql,array($bid_amount,$keyword,$bid_date));
-    }
-}
diff --git a/models/advmetadata_model.php b/models/advmetadata_model.php
deleted file mode 100644
index 6bce101..0000000
--- a/models/advmetadata_model.php
+++ /dev/null
@@ -1,145 +0,0 @@
-<?php
-/**
- * SeekQuarry/Yioop --
- * Open Source Pure PHP Search Engine, Crawler, and Indexer
- *
- * Copyright (C) 2009 - 2015  Chris Pollett chris@pollett.org
- *
- * LICENSE:
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- * END LICENSE
- *
- * @author Pushkar Umaranikar
- * @license http://www.gnu.org/licenses/ GPL3
- * @link http://www.seekquarry.com/
- * @copyright 2009 - 2015
- * @filesource
- */
-if (!defined('BASE_DIR')) {echo "BAD REQUEST"; exit();}
-/** Loads the base class */
-require_once BASE_DIR."/models/model.php";
-
-
-/**
- * This class is used to handle
- * database statements related to Advertisement Metadata
- *
- * @author Pushkar Umaranikar
- * @package seek_quarry\model
- */
-class AdvMetaDataModel extends Model
-{
-    /**
-     * Associations of the form
-     *     name of field for web forms => database column names/abbreviations
-     * In this case, things will in general map to the USERS table in the
-     * Yioop data base
-     * var array
-     */
-    var $search_table_column_map = array("id"=>"ADV_ID",
-        "clicks" => "CLICKS", "impressions" => "IMPRESSIONS",);
-    /**
-     * These fields if present in $search_array (used by @see getRows() ),
-     * but with value "-1", will be skipped as part of the where clause
-     * but will be used for order by clause
-     * @var array
-     */
-    var $any_fields = array("status");
-    /**
-     * {@inheritDoc}
-     *
-     * @param mixed $args any additional arguments which should be used to
-     *     determine these tables (in this case none)
-     */
-    function selectCallback($args = NULL)
-    {
-        return "ADV_ID, CLICKS, IMPRESSIONS";
-    }
-    /**
-     * {@inheritDoc}
-     *
-     * @param mixed $args any additional arguments which should be used to
-     *     determine these tables (in this case none)
-     */
-    function fromCallback($args = NULL)
-    {
-        return "ADVERTISEMENT_METADATA";
-    }
-    /**
-     * {@inheritDoc}
-     *
-     * @param mixed $args any additional arguments which should be used to
-     *     determine these tables (in this case none)
-     */
-    function whereCallback($args = NULL)
-    {
-        return "";
-    }
-    /**
-     * Checks if advertisement metadata present or not
-     *
-     * @param integer $adv_id represents advertisement id
-     * @return boolean value representing metedata present or not
-     */
-    function isAdvMetadataPresent($adv_id)
-    {
-        $db = $this->db;
-        $sql = "SELECT ADV_ID FROM ADVERTISEMENT_METADATA WHERE ADV_ID = ?";
-        $result = $db->execute($sql,array($adv_id));
-        if ($result) {
-            if ($mix = $db->fetchArray($result)) {
-                return true;
-            } else {
-                return false;
-            }
-        }
-    }
-    /**
-     * Records number of impressions for an advertisement
-     *
-     * @param string $adv_id of an advertisement
-     * @param boolean $is_new Checks if advertisement is newly created or not
-     */
-    function addImpression($adv_id,$is_new)
-    {
-        $db = $this->db;
-        $clicks = 0;
-        $impressions = 1;
-        if ($is_new) {
-            $sql = "INSERT INTO ADVERTISEMENT_METADATA
-            (ADV_ID,CLICKS,IMPRESSIONS) VALUES (?, ?, ?)";
-         $result = $db->execute($sql,array(
-             $adv_id,$clicks,$impressions));
-        } else {
-            $sql= "UPDATE ADVERTISEMENT_METADATA SET
-            IMPRESSIONS= IMPRESSIONS +1 WHERE ADV_ID = ?";
-            $result = $db->execute($sql,array($adv_id));
-        }
-    }
-    /**
-     * Records the number of clicks for an advertisement
-     *
-     * @param integer $adv_id advertisement id
-     */
-    function addClick($adv_id)
-    {
-        $db = $this->db;
-        $sql = "UPDATE ADVERTISEMENT_METADATA SET CLICKS = CLICKS + 1 WHERE
-        ADV_ID = ?";
-        $result = $db->execute($sql,array($adv_id));
-    }
-}
-?>
diff --git a/models/profile_model.php b/models/profile_model.php
index 7f282bb..7eedc30 100755
--- a/models/profile_model.php
+++ b/models/profile_model.php
@@ -47,11 +47,11 @@ class ProfileModel extends Model
      * profile.php file
      * @var array
      */
-    var $profile_fields = array('AD_LOCATION','API_ACCESS', 'AUTH_KEY',
-        'AUTHENTICATION_MODE', 'AUXILIARY_CSS', 'BACKGROUND_COLOR',
-        'BACKGROUND_IMAGE', 'CACHE_LINK', 'CAPTCHA_MODE', 'CSRF_TOKEN',
-        'DEBUG_LEVEL', 'DESCRIPTION_WEIGHT', 'DB_HOST', 'DBMS', 'DB_NAME',
-        'DB_PASSWORD', 'DB_USER', 'DEFAULT_LOCALE', 'FAVICON',
+    var $profile_fields = array('AD_LOCATION', 'ADVERTISEMENT_TYPE',
+        'API_ACCESS', 'AUTH_KEY', 'AUTHENTICATION_MODE', 'AUXILIARY_CSS',
+        'BACKGROUND_COLOR', 'BACKGROUND_IMAGE', 'CACHE_LINK', 'CAPTCHA_MODE',
+        'CSRF_TOKEN', 'DEBUG_LEVEL', 'DESCRIPTION_WEIGHT', 'DB_HOST', 'DBMS',
+        'DB_NAME', 'DB_PASSWORD', 'DB_USER', 'DEFAULT_LOCALE', 'FAVICON',
         'FIAT_SHAMIR_MODULUS', 'FOREGROUND_COLOR', 'GLOBAL_ADSCRIPT',
         'GROUP_ITEM', 'IN_LINK','IP_LINK', 'LANDING_PAGE', 'LINK_WEIGHT',
         'LOGO', 'M_LOGO', 'MAIL_PASSWORD',  'MAIL_SECURITY',
@@ -105,21 +105,21 @@ class ProfileModel extends Model
         $this->create_statements = array("ACTIVE_PROCESS" =>
             "CREATE TABLE ACTIVE_PROCESS (NAME VARCHAR(".NAME_LEN.
                 "), ID INTEGER, TYPE VARCHAR(" . NAME_LEN . "))",
-            "ADVERTISEMENTS" => "CREATE TABLE ADVERTISEMENTS(ADV_ID INTEGER
+            "ADVERTISEMENTS" => "CREATE TABLE ADVERTISEMENTS(AD_ID INTEGER
                 PRIMARY KEY AUTOINCREMENT, USER_ID INTEGER,
-                ADV_NAME VARCHAR(". ADVERTISEMENT_NAME_LEN ."),
-                ADV_DESCRIPTION VARCHAR(". ADVERTISEMENT_TEXT_LEN ."),
-                ADV_DESTINATION VARCHAR(". ADVERTISEMENT_DESTINATION_LEN ."),
-                ADV_KEYWORDS VARCHAR(". ADVERTISEMENT_KEYWORD_LEN ."),
-                STATUS INTEGER, ADV_BUDGET INTEGER,
-                ADV_DATE VARCHAR(". ADVERTISEMENT_DATE_LEN ."))",
+                AD_NAME VARCHAR(". ADVERTISEMENT_NAME_LEN ."),
+                AD_DESCRIPTION VARCHAR(". ADVERTISEMENT_TEXT_LEN ."),
+                AD_DESTINATION VARCHAR(". ADVERTISEMENT_DESTINATION_LEN ."),
+                AD_KEYWORDS VARCHAR(". ADVERTISEMENT_KEYWORD_LEN ."),
+                STATUS INTEGER, AD_BUDGET INTEGER,
+                AD_DATE VARCHAR(". ADVERTISEMENT_DATE_LEN ."))",
             "ADVERTISEMENT_KEYWORD" => "CREATE TABLE ADVERTISEMENT_KEYWORD
                 (ID INTEGER PRIMARY KEY AUTOINCREMENT,
                 KEYWORD VARCHAR(". ADVERTISEMENT_KEYWORD_LEN ."),
                 BID_AMOUNT INTEGER,
                 BID_DATE VARCHAR(". ADVERTISEMENT_DATE_LEN ."))",
             "ADVERTISEMENT_METADATA" => "CREATE TABLE ADVERTISEMENT_METADATA
-                (ADV_ID INTEGER, CLICKS INTEGER, IMPRESSIONS INTEGER)",
+                (AD_ID INTEGER, CLICKS INTEGER, IMPRESSIONS INTEGER)",
             "ACTIVITY" => "CREATE TABLE ACTIVITY (ACTIVITY_ID $serial
                 PRIMARY KEY $auto_increment, TRANSLATION_ID INTEGER,
                 METHOD_NAME VARCHAR(".LONG_NAME_LEN."))",
diff --git a/views/elements/displayadvertisement_element.php b/views/elements/displayadvertisement_element.php
index d4ec381..5db0487 100644
--- a/views/elements/displayadvertisement_element.php
+++ b/views/elements/displayadvertisement_element.php
@@ -51,12 +51,12 @@ class DisplayadvertisementElement extends Element
             $token_string_amp = ($logged_in) ?
                 CSRF_TOKEN . "=" . $data[CSRF_TOKEN]."&amp;" : "";
             $destination_url =
-                (strpos($data['RELEVANT_ADVERTISEMENT']['ADV_DESTINATION'],
+                (strpos($data['RELEVANT_ADVERTISEMENT']['AD_DESTINATION'],
                 "http") !== false) ?
-                $data['RELEVANT_ADVERTISEMENT']['ADV_DESTINATION']:
-                "http://". $data['RELEVANT_ADVERTISEMENT']['ADV_DESTINATION'];
+                $data['RELEVANT_ADVERTISEMENT']['AD_DESTINATION']:
+                "http://". $data['RELEVANT_ADVERTISEMENT']['AD_DESTINATION'];
             $url = "?".($token_string_amp)."c=search&a=recordClick&arg=".
-                    $data['RELEVANT_ADVERTISEMENT']['ADV_ID'];
+                    $data['RELEVANT_ADVERTISEMENT']['AD_ID'];
             ?>
             <div class="display-ad">
             <p>
@@ -64,10 +64,10 @@ class DisplayadvertisementElement extends Element
                 <a href="<?php e($destination_url);?>"
                    onclick="recordClick();" <?php if ($data["OPEN_IN_TABS"]) {
                       ?>target="_blank" <?php }?>>
-                      <?php e($data['RELEVANT_ADVERTISEMENT']['ADV_NAME'])?>
+                      <?php e($data['RELEVANT_ADVERTISEMENT']['AD_NAME'])?>
                 </a>
                 <span><?php
-                    e($data['RELEVANT_ADVERTISEMENT']['ADV_DESCRIPTION']);?>
+                    e($data['RELEVANT_ADVERTISEMENT']['AD_DESCRIPTION']);?>
                 </span>
             </p>
             </div>
diff --git a/views/elements/manageaccount_element.php b/views/elements/manageaccount_element.php
index 1dd78ad..2798682 100755
--- a/views/elements/manageaccount_element.php
+++ b/views/elements/manageaccount_element.php
@@ -136,7 +136,8 @@ class ManageaccountElement extends Element
                     <?php e($disabled);?>
                     value="<?php e($data['USER']['EMAIL']); ?>"
                     class="narrow-field"/></td></tr>
-            <?php if (isset($data['EDIT_USER'])) { ?>
+            <?php if (isset($data['EDIT_USER']) &&
+                !empty($data['yioop_advertisement'])) { ?>
             <tr><th class="table-label"><label for="is_advertiser"><?php
                 e(tl('manageaccount_element_is_advertiser'));
                     ?></label></th>
diff --git a/views/elements/manageadvertisements_element.php b/views/elements/manageadvertisements_element.php
index 4d17207..660819c 100644
--- a/views/elements/manageadvertisements_element.php
+++ b/views/elements/manageadvertisements_element.php
@@ -91,7 +91,7 @@ class ManageAdvertisementsElement extends Element
                 }
                 $delete_url = $base_url . "&amp;arg=deleteadvertisement&amp;";
                 $edit_url = $base_url . "&amp;arg=editadvertisement&amp;";
-                $mobile_columns = array('ADV_NAME', 'STATUS');
+                $mobile_columns = array('AD_NAME', 'STATUS');
                 $stretch = (MOBILE) ? 1 : 2;
                 foreach ($data['ADVERTISEMENTS'] as $advertisement) {;
                 echo "<tr>";
@@ -104,8 +104,8 @@ class ManageAdvertisementsElement extends Element
                     if ($colname=="END_DATE") {
                         $expiry_date = $role_column;
                     }
-                    if ($colname != "ADV_IDS" && $colname!="STATUS") {
-                        if ($colname == "ADV_IDS" || (
+                    if ($colname != "AD_IDS" && $colname!="STATUS") {
+                        if ($colname == "AD_IDS" || (
                                 MOBILE && !in_array($colname, $mobile_columns))
                         ) {
                             continue;
@@ -122,8 +122,8 @@ class ManageAdvertisementsElement extends Element
                 ?>
                 <td> <?php if($isActive && (time() <
                             strtotime($expiry_date))) { ?>
-                    <a href="<?php e($edit_url . 'adv_ids=' .
-                        $advertisement['ADV_IDS'])
+                    <a href="<?php e($edit_url . 'ad_ids=' .
+                        $advertisement['AD_IDS'])
                     ?>"><?php
                         e(tl('manageadvertisements_element_edit'));
                         ?></a><?php } else {
@@ -135,7 +135,7 @@ class ManageAdvertisementsElement extends Element
                     <a onclick='javascript:return confirm("<?php
                     e(tl('confirm_deactivate_operation')); ?>");' href="<?php
                     e($delete_url . 'adv=' .
-                        $advertisement['ADV_IDS'].'&amp;'. "status=" .
+                        $advertisement['AD_IDS'].'&amp;'. "status=" .
                         ADVERTISEMENT_DEACTIVE_STATUS); ?>"><?php
                         e(tl('manageadvertisements_element_deactivate'));
                         ?></a><?php }
@@ -144,7 +144,7 @@ class ManageAdvertisementsElement extends Element
                     <a onclick='javascript:return confirm("<?php
                     e(tl('confirm_reactivate_operation')); ?>");' href="<?php
                     e($delete_url . 'adv=' .
-                        $advertisement['ADV_IDS'].'&amp;'. 'status=' .
+                        $advertisement['AD_IDS'].'&amp;'. 'status=' .
                         ADVERTISEMENT_ACTIVE_STATUS); ?>"><?php
                         e(tl('manageadvertisements_element_reactivate'));
                         ?></a>
@@ -198,70 +198,76 @@ class ManageAdvertisementsElement extends Element
             <input type="hidden" name="NEW_KEYWORDS"
             value="<?php isset($data['NEW_KEYWORDS']) ?
                 e($data['NEW_KEYWORDS']):"";?>" />
-            <input type="hidden" name="ADV_MIN_BID"
-               value="<?php isset($data['ADV_MIN_BID']) ?
-                e($data['ADV_MIN_BID']):"";?>" />
+            <input type="hidden" name="AD_MIN_BID"
+               value="<?php isset($data['AD_MIN_BID']) ?
+                e($data['AD_MIN_BID']):"";?>" />
             <table>
             <tr><th class="table-label"><label for="ad-name"><?php
                 e(tl('createadvertisement_element_displayname')); ?>:
             </label></th>
             <td><input type="text" id="ad-name"
-            name="ADV_NAME"  maxlength="<?php e(ADVERTISEMENT_NAME_LEN);?>"
-            value="<?php isset($data['ADV_NAME']) ? e($data['ADV_NAME']):"";?>"
-            class="narrow-field" <?php e($preview_script); ?> />
+            name="AD_NAME"  maxlength="<?php e(ADVERTISEMENT_NAME_LEN);?>"
+            value="<?php isset($data['AD_NAME']) ? e($data['AD_NAME']):"";?>"
+            class="narrow-field" <?php e($preview_script);?>
+            <?php if (isset($data['AD_MIN_BID'])) { e('readonly');}?>/>
             </td></tr>
             <tr><th class="table-label"><label for="ad-description"><?php
                 e(tl('createadvertisement_element_text')); ?>:
             </label></th>
             <td><input type="text" id="ad-description"
-            name="ADV_DESCRIPTION" maxlength=
+            name="AD_DESCRIPTION" maxlength=
                 "<?php e(ADVERTISEMENT_TEXT_LEN);?>"
-            value="<?php isset($data['ADV_DESCRIPTION']) ?
-            e($data['ADV_DESCRIPTION']):"";?>" class="narrow-field"
-            <?php e($preview_script); ?> />
+            value="<?php isset($data['AD_DESCRIPTION']) ?
+            e($data['AD_DESCRIPTION']):"";?>" class="narrow-field"
+            <?php e($preview_script); ?><?php if (isset($data['AD_MIN_BID']))
+                { e('readonly');}?>/>
             </td></tr>
             <tr><th class="table-label"><label for="ad-destination"><?php
             e(tl('createadvertisement_element_landing_page')); ?>:
             </label></th>
-            <td><input type="text" id="ad-destination" name="ADV_DESTINATION"
-            value="<?php isset($data['ADV_DESTINATION']) ?
-            e($data['ADV_DESTINATION']):"";?>" class="narrow-field"
-            <?php e($preview_script2); ?>/>
+            <td><input type="text" id="ad-destination" name="AD_DESTINATION"
+            value="<?php isset($data['AD_DESTINATION']) ?
+            e($data['AD_DESTINATION']):"";?>" class="narrow-field"
+            <?php e($preview_script2); ?>
+            <?php if (isset($data['AD_MIN_BID'])) { e('readonly');}?>/>
             </td></tr>
             <tr><th class="table-label"><label for="ad-start"><?php
                 e(tl('createadvertisement_element_start_date')); ?>:
-            </label></th><td><input type="date" name="ADV_START_DATE"
-                id='ad-start' value="<?php isset($data['ADV_START_DATE']) ?
-                e($data['ADV_START_DATE']):"";?>" placeholder='<?php
+            </label></th><td><input type="date" name="AD_START_DATE"
+                id='ad-start' value="<?php isset($data['AD_START_DATE']) ?
+                e($data['AD_START_DATE']):"";?>" placeholder='<?php
                 e(date("Y-m-d", $data['TODAY'])); ?>'
-            <?php if ($edit_advertisement) { e('disabled');}?> />
+            <?php if ($edit_advertisement || isset($data['AD_MIN_BID']))
+            { e('readonly');}?> />
             </td></tr>
             <tr><th class="table-label"><label for="ad-end"><?php
             e(tl('createadvertisement_element_end_date')); ?>:
-            </label></th><td><input type="date" id="ad-end" name="ADV_END_DATE"
-             value="<?php isset($data['ADV_END_DATE']) ?
-             e($data['ADV_END_DATE']):"";?>" placeholder='<?php
+            </label></th><td><input type="date" id="ad-end" name="AD_END_DATE"
+             value="<?php isset($data['AD_END_DATE']) ?
+             e($data['AD_END_DATE']):"";?>" placeholder='<?php
                 e(date("Y-m-d", $data['TODAY'])); ?>'
-             <?php if ($edit_advertisement) { e('disabled');}?> />
+             <?php if ($edit_advertisement || isset($data['AD_MIN_BID']))
+             { e('readonly');}?> />
              </td></tr>
             <tr><th class="table-label"><label for="ad-keywords"><?php
             e(tl('createadvertisement_element_keywords')); ?>:
             </label></th>
             <td><textarea class="short-text-area" id="ad-keywords"
-            name="ADV_KEYWORDS" placeholder=
+            name="AD_KEYWORDS" placeholder=
             "<?php e(tl('createadvertisement_element_helptext'))?>"
-            <?php if ($edit_advertisement) { e('disabled');}?>
-            ><?php isset($data['ADV_KEYWORDS']) ? e($data['ADV_KEYWORDS']):"";
+            <?php if ($edit_advertisement || isset($data['AD_MIN_BID']))
+            { e('readonly');}?>
+            ><?php isset($data['AD_KEYWORDS']) ? e($data['AD_KEYWORDS']):"";
             ?></textarea></td></tr>
             <tr>
             <?php
-                if (isset($data['ADV_MIN_BID'])) {
+                if (isset($data['AD_MIN_BID'])) {
                 ?><th class="table-label"><label for="ad-min-bid"><?php
                     e(tl('createadvertisement_element_keyword_bid_amount'));
                     ?>:</label></th><td>
-                    <input type="text" id='ad-min-bid' name="ADV_MIN_BID"
-                    value="<?php isset($data['ADV_MIN_BID']) ?
-                    e($data['ADV_MIN_BID']):"";?>"
+                    <input type="text" id='ad-min-bid' name="AD_MIN_BID"
+                    value="<?php isset($data['AD_MIN_BID']) ?
+                    e($data['AD_MIN_BID']):"";?>"
                     class="narrow-field" disabled="true"/></td></tr>
             <tr><th class="table-label"><label for="expensive-word"><?php
                 e(tl('createadvertisement_element_expensive_word')); ?>:
@@ -273,7 +279,7 @@ class ManageAdvertisementsElement extends Element
             class="narrow-field" disabled="true"/></td></tr>
             <?php
               }?>
-            <?php if (!$edit_advertisement) { ?>
+            <?php if (!$edit_advertisement && !isset($data['AD_MIN_BID'])) { ?>
              <tr><td></td>
              <td class="center"><input class="button-box"
               name="keywords" value="<?php e(
@@ -284,27 +290,34 @@ class ManageAdvertisementsElement extends Element
             <?php if (!$edit_advertisement) { ?>
             <tr>
             <td><input type="hidden" id="ad-min-bid"
-            name="ADV_MIN_BID" value="<?php isset($data['ADV_MIN_BID']) ?
-                e($data['ADV_MIN_BID']):"";?>" class="narrow-field" />
+            name="AD_MIN_BID" value="<?php isset($data['AD_MIN_BID']) ?
+                e($data['AD_MIN_BID']):"";?>" class="narrow-field" />
             </td></tr>
-            <?php }?>
+            <?php }
+                if (isset($data['AD_MIN_BID']) && !$edit_advertisement) {?>
             <tr><th class="table-label"><label for="ad-budget"><?php
                 e(tl('createadvertisement_element_budget')); ?>:
             </label></th>
             <td><input type="text" id="ad-budget"
-            name="ADV_BUDGET" value="<?php isset($data['ADV_BUDGET']) ?
-                e($data['ADV_BUDGET']):"";?>" class="narrow-field"
+            name="AD_BUDGET" value="<?php isset($data['AD_BUDGET']) ?
+                e($data['AD_BUDGET']):"";?>" class="narrow-field"
                 <?php if ($edit_advertisement){ e('disabled');} ?> />
             </td></tr>
-            <tr><td></td><td class="center"><input class="button-box"
+            <tr><td></td>
+                <td class="left"><input class="button-box"
+                name="edit-keywords" value="<?php
+                e(tl('createadvertisement_element_edit_keywords'));
+                ?>" type="submit"
+                />
+                </td>
+                <td class="right"><input class="button-box"
                 name="save" value="<?php
                 e(tl('createadvertisement_element_checkout'));
-                ?>" type="submit" <?php 
-                if (!isset($data['ADV_MIN_BID']) && !$edit_advertisement) {
-                    e('disabled');
-                }?>/>
+                ?>" type="submit"
+                />
             </td>
             </tr>
+            <?php } ?>
             </table>
             <?php if(MOBILE) { ?>
                <div class="clear">&nbsp;</div>
diff --git a/views/elements/serversettings_element.php b/views/elements/serversettings_element.php
index ef2bf4f..5b4bc8d 100644
--- a/views/elements/serversettings_element.php
+++ b/views/elements/serversettings_element.php
@@ -263,7 +263,19 @@ class ServersettingsElement extends Element
             e(tl('serversettings_element_adserver_configuration'));
             e("&nbsp;" . $this->view->helper("helpbutton")->render(
                 "Ad Server", $data[CSRF_TOKEN])); ?></legend>
-            <div><b>
+            <div id="ad-register">
+                <legend><label
+                        for="ad-registration"><?php
+                        e(tl('serversettings_element_advertising_source'));
+                        ?></label></legend>
+                <?php $this->view->helper("options")->render(
+                    "ad-registration", "ADVERTISEMENT_TYPE",
+                    $data['ADVERTISEMENT_TYPES'],
+                    $data['ADVERTISEMENT_TYPE']);
+                ?>
+            </div>
+            <div id="ad-location-info">
+            <br /><b>
             <?php e(tl('serversettings_element_ad_location'))
             ?></b><br />
             <input type='radio' name='AD_LOCATION' value="top"
@@ -286,7 +298,6 @@ class ServersettingsElement extends Element
                 e(($data['AD_LOCATION'] == 'none') ?
                     'checked' : ''); ?> /><label for="ad-location-none"><?php
                 e(tl('serversettings_element_none')); ?></label>
-            </div>
             <div id="global-adscript-config">
             <label for="global-adscript"><b><?php
                 e(tl('serversettings_element_global_adscript'));
@@ -308,7 +319,7 @@ class ServersettingsElement extends Element
             <textarea class="short-text-area" id="side-adscript"
                 name="SIDE_ADSCRIPT"><?php
                 e(html_entity_decode($data['SIDE_ADSCRIPT'], ENT_QUOTES))
-            ?></textarea></div>
+            ?></textarea></div></div>
             </fieldset>
             </div>
             <div class="top-margin center">
@@ -322,6 +333,7 @@ class ServersettingsElement extends Element
         window.onload = function()
         {
             showHideScriptdiv();
+            selectAdvertisingSource();
         }
         /**
          * Method to show/block div including text area depending upon location
@@ -354,6 +366,15 @@ class ServersettingsElement extends Element
                 }
             }
         }
+        function selectAdvertisingSource() {
+            var show_ad_info = false;
+            no_external_ad = ['no_advertisements', 'yioop_advertisements'];
+            if (no_external_ad.indexOf(elt('ad-registration').value)
+                < 0) {
+                show_ad_info = true;
+            }
+            setDisplay('ad-location-info', show_ad_info);
+        }
         </script>
     <?php
     }
-- 
1.9.4.msysgit.1

