_binary From 5cd0e243411ee8221132b150b7a9f57bca27b348 Mon Sep 17 00:00:00 2001
From: Pushkar Umaranikar <pushkar.umaranikar@sjsu.edu>
Date: Sat, 9 May 2015 21:48:14 -0700
Subject: [PATCH] 0000169: Advertisement server integration with yioop

---
 configs/config.php                                 |  31 +-
 configs/public_help_pages.php                      |  35 +-
 controllers/admin_controller.php                   |   3 +-
 controllers/components/accountaccess_component.php |  27 +-
 controllers/components/advertisement_component.php | 372 +++++++++++++++++++++
 controllers/search_controller.php                  |  69 +++-
 css/search.css                                     |  48 +++
 data/default.db                                    | Bin 220160 -> 411648 bytes
 lib/upgrade_functions.php                          |  37 ++
 models/advertisement_model.php                     | 334 ++++++++++++++++++
 models/advkeyword_model.php                        | 173 ++++++++++
 models/advmetadata_model.php                       | 146 ++++++++
 models/profile_model.php                           |  15 +
 models/user_model.php                              |   2 +-
 resources/adv-logo.png                             | Bin 0 -> 4915 bytes
 views/elements/displayadvertisement_element.php    |  95 ++++++
 views/elements/manageaccount_element.php           |  21 ++
 views/elements/manageadvertisements_element.php    | 364 ++++++++++++++++++++
 views/search_view.php                              |   3 +
 19 files changed, 1767 insertions(+), 8 deletions(-)
 create mode 100644 controllers/components/advertisement_component.php
 create mode 100644 models/advertisement_model.php
 create mode 100644 models/advkeyword_model.php
 create mode 100644 models/advmetadata_model.php
 create mode 100644 resources/adv-logo.png
 create mode 100644 views/elements/displayadvertisement_element.php
 create mode 100644 views/elements/manageadvertisements_element.php

diff --git a/configs/config.php b/configs/config.php
index fda788c..2559765 100755
--- a/configs/config.php
+++ b/configs/config.php
@@ -85,6 +85,7 @@ $COMPONENT_ACTIVITIES = array(
     "crawl" => array("manageCrawls", "manageClassifiers", "pageOptions",
         "resultsEditor", "searchSources"),
     "social" => array("manageGroups", "groupFeeds", "mixCrawls", "wiki"),
+    "advertisement" => array("manageAdvertisements"),
     "system" => array("manageMachines", "manageLocales",
         "serverSettings", "security", "configure")
 );
@@ -108,9 +109,9 @@ if (MAINTENANCE_MODE && $_SERVER["SERVER_ADDR"] != $_SERVER["REMOTE_ADDR"]) {
 }
 
 if (!defined('WORK_DIRECTORY')) {
-/*+++ The next block of code is machine edited, change at
+/*+++ The next block of code is machine edited, change at 
 your own risk, please use configure web page instead +++*/
-define('WORK_DIRECTORY', '');
+define('WORK_DIRECTORY', 'C:/xampp/htdocs/yioop_data');
 /*++++++*/
 // end machine edited code
 }
@@ -769,3 +770,29 @@ define('NUM_FIELD_LEN', 4);
 define('WRITING_MODE_LEN', 5);
 /* Length of zero knowledge password string */
 define('ZKP_PASSWORD_LEN', 200);
+/* Length of advertisement name string */
+define('ADVERTISEMENT_NAME_LEN',25);
+/* Length of advertisement text description */
+define('ADVERTISEMENT_TEXT_LEN',35);
+/* Length of advertisement keywords */
+define('ADVERTISEMENT_KEYWORD_LEN',60);
+/* Length of advertisement date */
+define('ADVERTISEMENT_DATE_LEN',20);
+/* Length of advertisement destination */
+define('ADVERTISEMENT_DESTINATION_LEN',60);
+/* value used for the created advertisement*/
+define('ADVERTISEMENT_ACTIVE_STATUS',1);
+/* Truncate length for ad description and keywords*/
+define ('ADVERTISEMENT_TRUNCATE_LEN', 8);
+/* Initial bid amount for advertisement keyword */
+define ('ADV_KEYWORD_INIT_BID',1);
+/* advertisement date format for start date and end date*/
+define ('ADV_DATE_FORMAT','Y-m-d');
+/* advertisement save click action */
+define('ADV_SAVE_CLICK','recordClick');
+/* advertisement logo*/
+define('ADV_LOGO','resources/adv-logo.png');
+/* value used to stop advertisement campaign*/
+define('ADVERTISEMENT_DEACTIVE_STATUS',2);
+/* credit card number length */
+define('CREDIT_CARD_NUMBER_LENGTH',10);
diff --git a/configs/public_help_pages.php b/configs/public_help_pages.php
index b536465..f20f8f8 100644
--- a/configs/public_help_pages.php
+++ b/configs/public_help_pages.php
@@ -20,7 +20,7 @@ END_HEAD_VARS
 ==Your request would result in an edit conflict, so will not be processed.==
 EOD;
 $public_pages["en-US"]["Main"] = <<< 'EOD'
-page_type=media_list
+page_type=standard
 
 page_alias=
 
@@ -1266,6 +1266,39 @@ There is also a link to the log file of the Media Updater process. Under the Nam
 
 {{right|[[https://www.seekquarry.com/?c=static&amp;p=Documentation#GUI%20for%20Managing%20Machines%20and%20Servers| Learn More.]]}}
 EOD;
+$help_pages["en-US"]["Manage_Advertisements"] = <<< EOD
+page_type=standard
+
+page_alias=
+
+page_border=solid-border
+
+toc=true
+
+title=
+
+author=
+
+robots=
+
+description=
+
+page_header=
+
+page_footer=
+
+END_HEAD_VARS==Manage Advertisements==
+You can create an advertisement, view and edit already created advertisements
+under manage advertisements. You can activate or deactivate advertisements.
+
+==Create Advertisement==
+You need to enter advertisement name, description, destination URL which is a 
+landing page for an advertisement.In addition, you need to enter start and end date for the campaign and associate keywords with it.When you click on &quot;add keywords&quot;, the system calculates the minimum bid required to
+create a campaign along with the most expensive word among keywords that you have entered. You can adjust your bid by altering the keywords association.You can see preview of your campaign under &quot;Preview&quot;.
+
+
+
+EOD;
 $help_pages["en-US"]["Manage_Machines"] = <<< EOD
 page_type=standard
 
diff --git a/controllers/admin_controller.php b/controllers/admin_controller.php
index 3cf3cab..42d6ea4 100755
--- a/controllers/admin_controller.php
+++ b/controllers/admin_controller.php
@@ -348,7 +348,8 @@ class AdminController extends Controller implements CrawlConstants
             "accountaccess" => tl('admin_controller_account_access'),
             "social" => tl('admin_controller_social'),
             "crawl" => tl('admin_controller_crawl_settings'),
-            "system" => tl('admin_controller_system_settings')
+            "system" => tl('admin_controller_system_settings'),
+            "advertisement" => tl('admin_controller_advertisement')
         );
         if (isset($data["ACTIVITIES"])) {
             foreach ($this->component_activities as $component => $activities) {
diff --git a/controllers/components/accountaccess_component.php b/controllers/components/accountaccess_component.php
index e5028dc..60cf23f 100644
--- a/controllers/components/accountaccess_component.php
+++ b/controllers/components/accountaccess_component.php
@@ -69,6 +69,7 @@ class AccountaccessComponent extends Component
         $group_model = $parent->model("group");
         $user_model = $parent->model("user");
         $crawl_model = $parent->model("crawl");
+        $role_model = $parent->model("role");
         $possible_arguments = array("updateuser");
         $data["ELEMENT"] = "manageaccount";
         $data['SCRIPT'] = "";
@@ -185,7 +186,31 @@ class AccountaccessComponent extends Component
                             $data['USER'][$field] =  $user[$field];
                         }
                     }
-                    if (isset($_FILES['user_icon']['name']) &&
+                    $is_buser=false;
+                    if (isset($_REQUEST['BUSINESS_USER'])) {
+                        $user['BUSINESS_USER'] = substr($parent->clean(
+                        $_REQUEST['BUSINESS_USER'], "string"), 0, $len);
+                        $data['USER']['BUSINESS_USER'] =
+                        $user['BUSINESS_USER'];
+                        $is_buser = true;
+                        $role_model->addUserRole($user_id,BUSINESS_ROLE);
+                    }
+                    else {
+                        $user['BUSINESS_USER'] = false;
+                        $data['USER']['BUSINESS_USER'] =
+                        $user['BUSINESS_USER'];
+                        $user['CREDIT_CARD_INFO'] = "";
+                        $data['USER']['CREDIT_CARD_INFO'] =
+                        $user['CREDIT_CARD_INFO'];
+                        $role_model->deleteUserRole($user_id,BUSINESS_ROLE);
+                }
+                    if(isset($_REQUEST['CREDIT_CARD_INFO']) && $is_buser) {
+                        $user['CREDIT_CARD_INFO'] = substr($parent->clean(
+                        $_REQUEST['CREDIT_CARD_INFO'], "string"), 0, $len);
+                        $data['USER']['CREDIT_CARD_INFO'] =
+                        $user['CREDIT_CARD_INFO'];
+                    }
+                    if(isset($_FILES['user_icon']['name']) &&
                         $_FILES['user_icon']['name'] !="") {
                         if (!in_array($_FILES['user_icon']['type'],
                             array('image/png', 'image/gif', 'image/jpeg'))) {
diff --git a/controllers/components/advertisement_component.php b/controllers/components/advertisement_component.php
new file mode 100644
index 0000000..f54108f
--- /dev/null
+++ b/controllers/components/advertisement_component.php
@@ -0,0 +1,372 @@
+<?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();}
+/**
+ * Component of the Yioop control panel used to handle activitys for
+ * managing advertisements. i.e., create advertisement, activate/
+ * deactivate advertisement, edit advertisement.It is used by AdminController
+ *
+ * @author Pushkar Umaranikar
+ * @package seek_quarry\controller\component
+ */
+class AdvertisementComponent extends Component
+{
+    function manageAdvertisements()
+    {
+        $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");
+        $advertisement_model = $parent->model("advertisement");
+        $data['SCRIPT'] = "";
+        $data['MESSAGE'] = "";
+        $data["ELEMENT"] = "manageadvertisements";
+        $data['FORM_TYPE'] = "addadvertisement";
+        $data['NEW_KEYWORDS'] = "";
+        if(isset($_REQUEST['keywords'])) {
+            if(empty($_REQUEST['ADV_NAME']) ||
+                empty($_REQUEST['ADV_DESCRIPTION']) ||
+                empty($_REQUEST['ADV_DESTINATION'])) {
+                $parent->redirectWithMessage(
+                    tl('advertisement_controller_fields_cannot_be_empty'),
+                    array_merge((array)$_REQUEST['arg'],
+                        $request_fields));
+            }
+            if(empty($_REQUEST['ADV_START_DATE']) ||
+               empty($_REQUEST['ADV_END_DATE'])){
+                $parent->redirectWithMessage(
+                    tl('advertisement_controller_date_cannot_be_empty'),
+                    array_merge((array)$_REQUEST['arg'],
+                        $request_fields));
+            }
+            if(empty($_REQUEST['ADV_KEYWORDS'])){
+                $parent->redirectWithMessage(
+                    tl('advertisement_controller_enter_keywords'),
+                    array_merge((array)$_REQUEST['arg'],
+                        $request_fields));
+            }
+            $temp_keywords= explode(",",strtolower(substr($parent->
+            clean($_REQUEST['ADV_KEYWORDS'], "string"), 0,
+                strlen($_REQUEST['ADV_KEYWORDS']))));
+            $new_keywords = array();
+            $adv_fields =  array("ADV_NAME", "ADV_DESTINATION",
+                "ADV_DESCRIPTION", "ADV_KEYWORDS", "ADV_BUDGET",
+                "ADV_START_DATE","ADV_END_DATE");
+            $start_date = substr($parent->clean($_REQUEST['ADV_START_DATE'],
+                "string"), 0, strlen($_REQUEST['ADV_START_DATE']));
+            $end_date = substr($parent->clean($_REQUEST['ADV_END_DATE'],
+                "string"), 0, strlen($_REQUEST['ADV_END_DATE']));
+            $date_diff = strtotime($end_date) - strtotime($start_date);
+            $day_count = $date_diff/(60*60*24)+1;
+            $j=0;
+            $min_bid_reqd=0;
+            $expensive_bid=0;
+            $temp_newwords=array();
+            for( $i = 0; $i < count($temp_keywords); $i++ ) {
+                $temp_date = $start_date;
+                for ( $k = 0; $k < $day_count; $k++ ) {
+                    $keyword_bid_amount=0;
+                    if(!$advkeyword_model->
+                    isKeywordPresent($temp_keywords[$i],$temp_date)){
+                        $new_keywords[$j]['KEYWORD'] = $temp_keywords[$i];
+                        $new_keywords[$j]['BID_AMOUNT'] = ADV_KEYWORD_INIT_BID;
+                        $new_keywords[$j]['BID_DATE'] = $temp_date;
+                        $data['ADVERTISEMENT_KEYWORD'][$temp_keywords[$i]] =
+                            ADV_KEYWORD_INIT_BID;
+                        array_push($temp_newwords,$temp_keywords[$i]);
+                        $j++;
+                        $min_bid_reqd++;
+                    }
+                    else {
+                        $bid_amount =$advkeyword_model->
+                        getBidAmount($temp_keywords[$i],$temp_date);
+                        if ($bid_amount > 1 ) {
+                            $data['ADVERTISEMENT_KEYWORD'][$temp_keywords[$i]] =
+                            $min_bid_reqd = $min_bid_reqd + ($bid_amount/2);
+                            $keyword_bid_amount = $keyword_bid_amount +
+                                ($bid_amount/2);
+                        }
+                        else {
+                                $data['ADVERTISEMENT_KEYWORD']
+                                [$temp_keywords[$i]] =
+                                $min_bid_reqd = $min_bid_reqd + $bid_amount;
+                                $keyword_bid_amount = $keyword_bid_amount +
+                                ($bid_amount/2);
+                        }
+                    }
+                    if ($keyword_bid_amount >= $expensive_bid) {
+                        $expensive_bid = $keyword_bid_amount;
+                        $data['EXPENSIVE_KEYWORD'] = $temp_keywords[$i];
+                    }
+                        $temp_date = date(ADV_DATE_FORMAT,
+                        strtotime($temp_date .' +1 day'));
+                }
+            }
+            $data['ADV_MIN_BID'] = $min_bid_reqd;
+            foreach ($adv_fields as $field) {
+                if(isset($_REQUEST[$field])) {
+                    $data[$field] = substr($parent->
+                    clean($_REQUEST[$field], "string"), 0,
+                        strlen($_REQUEST[$field]));
+                }
+            }
+            if (!empty($temp_keywords)) {
+                $data['NEW_KEYWORDS']= implode(",",$temp_keywords);
+            }
+            if (!empty($new_keywords)) {
+                $advkeyword_model->addKeywords($new_keywords);
+            }
+        }
+        $possible_arguments = array("addadvertisement", 'editadvertisement',
+            "search","deleteadvertisement");
+        $user_id = $_SESSION['USER_ID'];
+        $username = $signin_model->getUserName($user_id);
+        $data["USER"] = $user_model->getUser($username);
+        $data["USER_ID"] = $user_id;
+        $data['PAGING'] = "";
+        $search_array = array();
+        if(isset($_REQUEST['adv'])) {
+            $adv_id = substr($parent->clean($_REQUEST['adv'], "string"),
+                0, strlen($_REQUEST['adv']));
+        } else {
+            $adv_id = "";
+        }
+        if(isset($_REQUEST['arg']) &&
+            in_array($_REQUEST['arg'], $possible_arguments)) {
+            switch($_REQUEST['arg']) {
+                case "addadvertisement":
+                    if(isset($_REQUEST['save'])) {
+                        $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");
+                        foreach ($fields as $field) {
+                            if (isset($_REQUEST[$field])) {
+                                $advertisement[$field] = substr($parent->
+                                clean($_REQUEST[$field], "string"), 0,
+                                    strlen($_REQUEST[$field]));
+                                $data['ADV'][$field] = $advertisement[$field];
+                            }
+                        }
+                        if (empty($_REQUEST['ADV_KEYWORDS'])) {
+                            $parent->redirectWithMessage(
+                                tl('advertisement_controller_enter_keywords'),
+                                array_merge((array)$_REQUEST['arg'],
+                                    $request_fields));
+                        }
+                        $new_keywords = array();
+                        $keywords = array();
+                        if (isset($_REQUEST['NEW_KEYWORDS'])) {
+                            $new_keywords = explode(",", strtolower(
+                                substr($parent->
+                            clean($_REQUEST['NEW_KEYWORDS'], "string"), 0,
+                                strlen($_REQUEST['NEW_KEYWORDS']))));
+                        }
+                        if (isset($_REQUEST['ADV_KEYWORDS'])) {
+                            $keywords = explode(",", strtolower(substr($parent->
+                            clean($_REQUEST['ADV_KEYWORDS'], "string"), 0,
+                                strlen($_REQUEST['ADV_KEYWORDS']))));
+                        }
+                        $budget = substr($parent->
+                        clean($_REQUEST['ADV_BUDGET'], "string"), 0,
+                            strlen($_REQUEST['ADV_BUDGET']));
+                        $min_bid = substr($parent->
+                        clean($_REQUEST['ADV_MIN_BID'], "string"), 0,
+                            strlen($_REQUEST['ADV_MIN_BID']));
+                        $adv_start_date= substr($parent->
+                        clean($_REQUEST['ADV_START_DATE'], "string"), 0,
+                            strlen($_REQUEST['ADV_START_DATE']));
+                        $adv_end_date = substr($parent->
+                        clean($_REQUEST['ADV_END_DATE'], "string"), 0,
+                            strlen($_REQUEST['ADV_END_DATE']));
+                        if ($budget < $min_bid) {
+                            $parent->redirectWithMessage(
+                                tl('advertisement_controller_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/(60*60*24)+1;
+                        foreach ($keywords as $keyword) {
+                            $temp_date = $adv_start_date;
+                            for ( $j = 0 ; $j < $adv_day_count ; $j++ ) {
+                                $day_bid_amt = $advkeyword_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->
+                                        updateBidAmount($keyword,
+                                            $updated_budget, $temp_date, false);
+                                    }
+                                    else {
+                                        $updated_budget =
+                                            ($day_bid_amt/$min_bid)*$budget;
+                                        $advkeyword_model->updateBidAmount(
+                                            $keyword, $updated_budget,
+                                            $temp_date, true);
+                                    }
+                                }
+                                else {
+                                    ($day_bid_amt>1)?
+                                    $updated_budget =
+                                      (($day_bid_amt/2)/$min_bid)*$budget:
+                                    $updated_budget =
+                                        (($day_bid_amt)/$min_bid)*$budget;
+                                    $advkeyword_model->
+                                    updateBidAmount($keyword, $updated_budget,
+                                        $temp_date, false);
+                                }
+                                $temp_date = date(ADV_DATE_FORMAT,
+                                    strtotime($temp_date .' +1 day'));
+                            }
+                        }
+                        $temp_date = $adv_start_date;
+                        for( $k = 0; $k < $adv_day_count; $k++ ) {
+                            $advertisement_model ->
+                            addAdvertisement($advertisement, $temp_date,
+                                $user_id);
+                            $temp_date = date(ADV_DATE_FORMAT,
+                                strtotime($temp_date .' +1 day'));
+                        }
+                        $advertisement['ADV_KEYWORDS'] =
+                            strtolower(implode(",",$associated_keywords));
+                        unset($data['ADVERTISEMENT_KEYWORD']);
+                        $parent->redirectWithMessage(
+                        tl('advertisement_controller_ad_created'),
+                        array_merge((array)$_REQUEST['arg'], $request_fields));
+                    }
+                    break;
+                case "deleteadvertisement":
+                    if ($adv_id <= 0) {
+                        $parent->redirectWithMessage(
+                        tl('advertisement_component_advertisement_doesnt_exists'
+                            ),
+                            array("start_row", "end_row", "num_show"));
+                    } else {
+                        $status = $_REQUEST['status'];
+                        $result = $advertisement_model->
+                        deactivateAdvertisement($adv_id,$status);
+                        if ($result) {
+                         $parent->redirectWithMessage(tl(
+                          'advertisement_component_status_changed'),
+                          array_merge(
+                                 array("start_row", "end_row", "num_show")),
+                                $request_fields);
+                        }
+                    }
+                    break;
+                case "editadvertisement":
+                    $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']));
+                        $advertisement = $advertisement_model->
+                        getAdvertisementByIds($adv_ids);
+                        usort($advertisement, array("AdvertisementComponent",
+                            "dateSortFunc"));
+                        $adv_fields = array("ADV_NAME", "ADV_DESTINATION",
+                            "ADV_DESCRIPTION","ADV_BUDGET","ADV_KEYWORDS",
+                            "ADV_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'];
+                            if ($update) {
+                            $updated_advertisement = array();
+                            $adv_update_fields = array("ADV_NAME",
+                                "ADV_DESCRIPTION","ADV_DESTINATION");
+                                foreach ($adv_update_fields as $field) {
+                                    if (isset($_REQUEST[$field])) {
+                                     $updated_advertisement[$field] =
+                                       substr($parent->clean($_REQUEST[$field],
+                                      "string"), 0, strlen($_REQUEST[$field]));
+                                    }
+                                }
+                                  $advertisement_model ->
+                                   updateAdvertisement($updated_advertisement,
+                                       $adv_ids);
+                                foreach ($request_fields as $field) {
+                                    unset($data[$field]);
+                                }
+                                unset($data['ADV_START_DATE']);
+                                unset($data['ADV_END_DATE']);
+                                $parent->redirectWithMessage(
+                                    tl('advertisement_controller_ad_updated'),
+                                    array_merge((array)$_REQUEST['arg'],
+                                        $request_fields));
+                            }
+                        }
+                    }
+                    break;
+                case "search":
+                    $data["FORM_TYPE"] = "search";
+                    $search_array =
+                        $parent->tableSearchRequestHandler($data,
+                            array('name', 'description', 'destination'));
+                    break;
+            }
+        }
+        if($search_array == array()) {
+            $search_array[] = array("name", "", "", "ASC");
+        }
+        $parent->pagingLogic($data, $advertisement_model, "ADVERTISEMENTS",
+            DEFAULT_ADMIN_PAGING_NUM, $search_array, "");
+
+        return $data;
+    }
+    /**
+     * Comparator to sort array of advertisements by date
+     */
+    function dateSortFunc($date1, $date2)
+    {
+        return strtotime($date1["ADV_DATE"])-strtotime($date2["ADV_DATE"]);
+    }
+}
+
diff --git a/controllers/search_controller.php b/controllers/search_controller.php
index 10024f0..f9ef649 100755
--- a/controllers/search_controller.php
+++ b/controllers/search_controller.php
@@ -56,7 +56,8 @@ class SearchController extends Controller implements CrawlConstants
      * controller will respond to
      * @var array
      */
-    var $activities = array("query", "more", "cache", "related", "signout");
+    var $activities = array("query", "more", "cache", "related", "signout",
+        "recordClick");
     /**
      * Name of the sub-search currently in use
      * @var string
@@ -748,7 +749,28 @@ class SearchController extends Controller implements CrawlConstants
                     $data['PAGING_QUERY'] .= "&amp;s=" . $this->subsearch_name;
                 }
                 $data['QUERY'] = urlencode($this->clean($query,"string"));
-
+                $data['ELEMENT'] = "displayadvertisement";
+                $advmetadata_model = $this->model("advmetadata");
+                if (isset($_REQUEST['a']) && $_REQUEST['a'] == ADV_SAVE_CLICK) {
+                    $advmetadata_model = $this->model("advmetadata");
+                    $advmetadata_model -> addClick($arg);
+                }
+                else {
+                    $data['RELEVANT_ADVERTISEMENT'] = $this->
+                    getRelevantAdvertisements($query);
+                    if ($advmetadata_model->isAdvMetadataPresent(
+                        $data['RELEVANT_ADVERTISEMENT']['ADV_ID'])
+                    ) {
+                        $advmetadata_model->addImpression(
+                            $data['RELEVANT_ADVERTISEMENT']['ADV_ID'],
+                            false);
+                    } else if (!empty
+                    ($data['RELEVANT_ADVERTISEMENT']['ADV_ID'])
+                    ) {
+                        $advmetadata_model->addImpression
+                        ($data['RELEVANT_ADVERTISEMENT']['ADV_ID'], true);
+                    }
+                }
             break;
         }
         $data['VIDEO_SOURCES'] =
@@ -1983,4 +2005,47 @@ class SearchController extends Controller implements CrawlConstants
         $script->setAttributeNS("","src", NAME_SERVER."/scripts/history.js");
         $node->appendChild($script);
     }
+    /**
+     * Gets the relevant advertisement for the entered search query
+     *
+     * @param $query entered by user
+     * @return array of relevant advertisements to the search query
+     */
+    function getRelevantAdvertisements($query)
+    {
+        $query_chunks = preg_split("/[^A-Za-z0-9]/",$query);
+        $advertisement_model = $this->model("advertisement");
+        $relevant_ads = $advertisement_model->getAdvertisementByKeywords(
+           $query_chunks);
+        if (!empty($relevant_ads)) {
+            uasort($relevant_ads, array($this, 'compare'));
+            $max_limit = 0;
+            foreach ($relevant_ads as $temp_adv) {
+                $max_limit = $max_limit + $temp_adv['ADV_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'];
+                if (($random_value > $min) && ($random_value < $max)) {
+                    $closest_ad = $advertisement;
+                }
+                $min = $max + 1;
+            }
+            return $closest_ad;
+        }
+    }
+    /**
+     * Comparator to sort array of advertisements by date
+     */
+    function compare($adv1, $adv2)
+    {
+        if ($adv1['ADV_BUDGET'] == $adv2['ADV_BUDGET']) {
+            return 0;
+        }
+        return ($adv1['ADV_BUDGET'] < $adv2['ADV_BUDGET']) ? -1 : 1;
+    }
+
 }
diff --git a/css/search.css b/css/search.css
index 808fd62..af1a376 100755
--- a/css/search.css
+++ b/css/search.css
@@ -2768,3 +2768,51 @@ button.default
     position:relative;
     top:0px;
 }
+.display-adv p
+{
+    width : 770px;
+    padding-bottom: 10px;
+    padding-top: 10px;
+    margin: inherit;
+    clear: both;
+    top: -0.9in;
+    position: relative;
+    margin-left: 45px;
+}
+.display-adv img
+{
+    height:41px;
+    width:50px;
+    float:left;
+    margin-left: 20px;
+}
+.display-adv label
+{
+    display: block;
+}
+.mobile .display-adv p
+{
+
+    width : auto;
+    max-width: 92%;
+    padding-bottom: 10px;
+    padding-top: 10px;
+    margin: inherit;
+    clear: both;
+    top: -20px;
+    position: relative;
+}
+.adv-preview
+{
+    position: absolute;
+    margin-top: -35%;
+    margin-left: 55%;
+}
+.adv-preview > table
+{
+    font-family: Arial, Helvetica, sans-serif;
+}
+.adv-preview .table-label
+{
+    text-align: left;
+}
\ No newline at end of file
diff --git a/data/default.db b/data/default.db
index 16aa51fe2b573fe0533a348b3510bac4dc2f51f2..a38cc0a7a2f3d3f9a038dbc5cf69e8abbbade0eb 100644
GIT binary patch
diff --git a/lib/upgrade_functions.php b/lib/upgrade_functions.php
index 5f7e3fa..8fabcda 100644
--- a/lib/upgrade_functions.php
+++ b/lib/upgrade_functions.php
@@ -1093,6 +1093,43 @@ function upgradeDatabaseVersion31(&$db)
     $profile_model->updateProfile(WORK_DIRECTORY, array(), $profile);
 }
 /**
+ * Upgrades a Version 31 version of the Yioop! database to a Version 32 version
+ * @param object $db datasource to use to upgrade
+ */
+function upgradeDatabaseVersion32(&$db)
+{
+    /** Get base class for profile_model.php*/
+    require_once BASE_DIR."/models/model.php";
+    /** To adjust MEDIA_MODE in the system profile */
+    require_once BASE_DIR."/models/profile_model.php";
+    $db->execute("DELETE FROM VERSION WHERE ID < 30");
+    $db->execute("UPDATE VERSION SET ID=31 WHERE ID=30");
+    $db->execute("ALTER TABLE USERS ADD COLUMN BUSINESS_USER VARCHAR(5)");
+    $db->execute("ALTER TABLE USERS ADD COLUMN CREDIT_CARD_INFO INTEGER");
+    $db->execute("CREATE TABLE ADVERTISEMENTS(ADV_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 ."))");
+    $db->execute("CREATE TABLE ADVERTISEMENT_KEYWORD
+                  (ID INTEGER PRIMARY KEY AUTOINCREMENT,
+                  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)");
+    addActivityAtId($db, 'db_activity_manage_advertisement',
+        "manageAdvertisement", 17);
+    updateTranslationForStringId($db, 'db_activity_manage_advertisement',
+        'en-US', 'Manage Advertisement');
+    $db->execute("INSERT INTO ROLE(ROLE_ID, NAME) VALUES (3,'Business User')");
+    $db->execute("INSERT INTO ROLE_ACTIVITY(ROLE_ID, ACTIVITY_ID)
+         VALUES (3,17)");
+}
+/**
  * Reads the Help articles from default db and returns the array of pages.
  */
 function getWikiHelpPages()
diff --git a/models/advertisement_model.php b/models/advertisement_model.php
new file mode 100644
index 0000000..af707c8
--- /dev/null
+++ b/models/advertisement_model.php
@@ -0,0 +1,334 @@
+<?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 Advertisements
+ *
+ * @author Pushkar Umaranikar
+ * @package seek_quarry\model
+ */
+class AdvertisementModel 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 ADVERTISEMENTS table
+     * 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");
+    /**
+     * 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_NAME, ADV_DESTINATION, ADV_KEYWORDS,
+        STATUS, ADV_BUDGET";
+    }
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function fromCallback($args = NULL)
+    {
+        return "(SELECT DISTINCT ADV_NAME, USER_ID, ADV_DESCRIPTION,
+        ADV_DESTINATION, ADV_KEYWORDS, STATUS, ADV_BUDGET FROM ADVERTISEMENTS)";
+    }
+    /**
+     * {@inheritDoc}
+     *
+     * @param mixed $args any additional arguments which should be used to
+     *     determine these tables (in this case none)
+     */
+    function whereCallback($args = NULL)
+    {
+        return "USER_ID != '".PUBLIC_USER_ID."'";
+    }
+    function postQueryCallback($rows)
+    {
+       return $rows = $this->getAdvertisements($rows);
+       return $rows;
+    }
+    /**
+     * Adds newly created advertisement
+     *
+     * @param $advertisement_advertisement to be added
+     * @param String $adv_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,
+                              $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 (?, ?, ?, ?, ?, ?, ?, ?)";
+            $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));
+        }
+        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));
+        }
+    }
+    /**
+     * Deletes advertisement
+     *
+     * @param string $adv_id  the id of the advertisement
+     */
+    function deleteAdvertisement($adv_ids)
+    {
+        $sql = "DELETE FROM ADVERTISEMENTS WHERE ADV_ID IN($adv_ids)";
+        $result = $this->db->execute($sql);
+    }
+    /**
+     * Update advertisement
+     *
+     * @param $advertisement_advertisement to be updated
+     * @param String $adv_ids comma separated list of advertisement ids
+     */
+    function updateAdvertisement($advertisement,$adv_ids)
+    {
+        $sql = "UPDATE ADVERTISEMENTS SET ";
+        $comma ="";
+        $params = array();
+        if($advertisement == array()) {return; }
+        foreach($advertisement as $field => $value) {
+            $sql .= "$comma $field=? ";
+            $comma = ",";
+                $params[] = $value;
+        }
+        $sql .= " WHERE ADV_ID IN($adv_ids)";
+        $db = $this->db;
+        $result = $db->execute($sql, $params);
+    }
+    /**
+     * Get advertisements for given advertisement keywords
+     *
+     * @param string $query_chunks words from user entered query
+     * @return array of advertisements
+     */
+    function getAdvertisementByKeywords($query_chunks)
+    {
+        $deactivated_status = ADVERTISEMENT_DEACTIVE_STATUS;
+        $sql = "SELECT * FROM ADVERTISEMENTS WHERE ( ADV_KEYWORDS LIKE ";
+        $append_sql = " OR ADV_KEYWORDS LIKE ";
+        $counter =1;
+        $params = array();
+        $db = $this->db;
+        foreach($query_chunks as $temp_query){
+            if($counter >1){
+                $append_sql = $append_sql. "'%".$temp_query."%'";
+                $sql = $sql.$append_sql;
+                $counter++;
+            }
+            else{
+                $sql = $sql." '%".$temp_query."%'";
+                $counter++;
+            }
+        }
+        $today_date = date(ADV_DATE_FORMAT);
+        $sql = $sql . ")" . " AND ADV_DATE ="."'".$today_date."'";
+        $sql = $sql . " AND STATUS != $deactivated_status";
+        $result = $db->execute($sql);
+        $row = array();
+        $relevant_ads = array();
+        $i=0;
+        while($row[$i] = $db->fetchArray($result)) {
+            array_push($relevant_ads,$row[$i]);
+        }
+        return $relevant_ads;
+    }
+    /**
+     * Get advertisements for given advertisement ids
+     *
+     * @param string $adv_ids advertisement ids
+     * @return array of advertisements
+     */
+    function getAdvertisementByIds($adv_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)";
+        $result = $db->execute($sql);
+        $advertisements = array();
+        $i=0;
+        while($row[$i] = $db->fetchArray($result)) {
+            array_push($advertisements,$row[$i]);
+        }
+        return $advertisements;
+    }
+
+    /**
+     * Gets number of impressions for given advertisement ids
+     *
+     * @param string $adv_ids advertisement ids
+     * @return count representing number of impressions
+     */
+    function getImpressions($adv_ids)
+    {
+        $db = $this->db;
+        $ids = join(',',$adv_ids);
+        $sql = "SELECT SUM(IMPRESSIONS) AS IMPRESSIONS FROM
+              ADVERTISEMENT_METADATA WHERE ADV_ID IN ($ids)";
+        $result = $db->execute($sql);
+        $row = $db->fetchArray($result);
+        return $row['IMPRESSIONS'];
+    }
+    /**
+     * 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
+     * @return array of advertisement ids
+     */
+    function getAdvertisementIds($adv_name,$adv_destination,$adv_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));
+        $i=0;
+        $adv_ids = array();
+        while($row[$i] = $db->fetchArray($result)) {
+            array_push($adv_ids,$row[$i]['ADV_ID']);
+        }
+        return $adv_ids;
+    }
+    /**
+     * Gets all the advertisements for post query callback
+     *
+     * @param array of advertisements from select callback
+     * @return array of advertisements
+     */
+    function getAdvertisements($rows)
+    {
+        $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",
+                "sortByDate"));
+            $row['START_DATE'] = $adv_dates[0];
+            $row['END_DATE'] = $adv_dates[count($adv_dates)-1];
+            $row['ADV_IDS'] = join(',',$adv_ids);
+            $row['IMPRESSIONS'] = $impressions;
+            array_push($modified_rows,$row);
+        }
+        return $modified_rows;
+    }
+    /**
+     * Change advertisement status for input advertisement ids
+     *
+     * @param array of advertisement ids
+     * @param integer value representing advertisement status
+     */
+    function deactivateAdvertisement($adv_ids,$status)
+    {
+        //$status = ADVERTISEMENT_DEACTIVE_STATUS;
+        $db = $this ->db;
+        $sql = "UPDATE ADVERTISEMENTS SET STATUS= ? WHERE ADV_ID IN ($adv_ids)";
+        $result = $db->execute($sql, array($status));
+        return $result;
+    }
+
+    /**
+     * Gets advertisements for input advertisement ids
+     *
+     * @param array of advertisement ids
+     * @return array of advertisements
+     */
+    function getAdvertisementdatesByIds($adv_ids)
+    {
+        $db = $this ->db;
+        $ids = join(',',$adv_ids);
+        $sql = "SELECT ADV_DATE FROM ADVERTISEMENTS WHERE ADV_ID IN($ids)";
+        $result = $db->execute($sql);
+        $row = $db->fetchArray($result);
+        $adv_dates = array();
+        $i=0;
+        while($row[$i] = $db->fetchArray($result)) {
+            array_push($adv_dates,$row[$i]['ADV_DATE']);
+        }
+        return $adv_dates;
+    }
+    /**
+     * Comparator to sort array of advertisements by date
+     *
+     */
+    function sortByDate($date1, $date2)
+    {
+        return strtotime($date1)-strtotime($date2);
+    }
+}
+
diff --git a/models/advkeyword_model.php b/models/advkeyword_model.php
new file mode 100644
index 0000000..9332d0f
--- /dev/null
+++ b/models/advkeyword_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 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 $keyword the keyword associated with advertisement
+     * @param $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 $keyword the keyword associated with advertisement
+     * @param $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 $keyword the keyword associated with advertisement
+     * @param $bid_amount associated with keyword
+     * @param $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
new file mode 100644
index 0000000..fa0eb87
--- /dev/null
+++ b/models/advmetadata_model.php
@@ -0,0 +1,146 @@
+<?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 $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 advertisment
+     *
+     * @param $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 1a54bd2..612182f 100755
--- a/models/profile_model.php
+++ b/models/profile_model.php
@@ -105,6 +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
+                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 ."))",
+            "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)",
             "ACTIVITY" => "CREATE TABLE ACTIVITY (ACTIVITY_ID $serial
                 PRIMARY KEY $auto_increment, TRANSLATION_ID INTEGER,
                 METHOD_NAME VARCHAR(".LONG_NAME_LEN."))",
diff --git a/models/user_model.php b/models/user_model.php
index 27c5b01..aabce11 100755
--- a/models/user_model.php
+++ b/models/user_model.php
@@ -54,7 +54,7 @@ class UserModel extends Model
      */
     var $search_table_column_map = array("first"=>"FIRST_NAME",
         "last" => "LAST_NAME", "user" => "USER_NAME", "email"=>"EMAIL",
-        "status"=>"STATUS");
+        "status"=>"STATUS","accounttype" => "BUSINESS_USER","creditinfo" => "CREDIT_CARD_INFO");
     /**
      * These fields if present in $search_array (used by @see getRows() ),
      * but with value "-1", will be skipped as part of the where clause
diff --git a/resources/adv-logo.png b/resources/adv-logo.png
new file mode 100644
index 0000000000000000000000000000000000000000..6f764c114e19caac1d873bbb6820b820f41a5300
GIT binary patch
diff --git a/views/elements/displayadvertisement_element.php b/views/elements/displayadvertisement_element.php
new file mode 100644
index 0000000..6a6c5f7
--- /dev/null
+++ b/views/elements/displayadvertisement_element.php
@@ -0,0 +1,95 @@
+<?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();}
+/**
+ * Element responsible for displaying the advertisement
+ * on the search results page
+ *
+ * @author Pushkar Umaranikar
+ * @package seek_quarry\view\element
+ */
+class DisplayadvertisementElement extends Element
+{
+    /**
+     * Draws relevant advertisement on search results page.
+     *
+     * @param array $data keys are generally the different setting that can
+     *     be set in the crawl.ini file
+     */
+    function render($data)
+    {
+        if (isset($data['RELEVANT_ADVERTISEMENT'])) {
+            $logged_in = isset($data["ADMIN"]) && $data["ADMIN"];
+            $token_string_amp = ($logged_in) ?
+                CSRF_TOKEN . "=" . $data[CSRF_TOKEN]."&amp;" : "";
+            (strpos($data['RELEVANT_ADVERTISEMENT']['ADV_DESTINATION'],
+                "http://")) ?
+                $destination_url =
+                    $data['RELEVANT_ADVERTISEMENT']['ADV_DESTINATION']:
+                $destination_url = "http://".
+                    $data['RELEVANT_ADVERTISEMENT']['ADV_DESTINATION'];
+            $url ="?".($token_string_amp)."c=search&a=recordClick&arg=".
+                    $data['RELEVANT_ADVERTISEMENT']['ADV_ID'];
+            $adv_logo = ADV_LOGO;
+            $background_color = TOPBAR_COLOR;
+         ?>
+            <style type="text/css">
+            .display-adv p
+            {
+                background-color: <?php e($background_color); ?>;
+            }
+            </style>
+            <div class="display-adv">
+            <p>
+                <img
+                    src="<?php e($adv_logo);?>" />
+                <a href="<?php e($destination_url);?>"
+                   onclick="recordClick();" <?php if ($data["OPEN_IN_TABS"]) {
+                      ?>target="_blank" <?php }?>>
+                      <?php e($data['RELEVANT_ADVERTISEMENT']['ADV_NAME'])?>
+                </a>
+                <label for="relevant-advertisement"><?php
+                    e($data['RELEVANT_ADVERTISEMENT']['ADV_DESCRIPTION']);?>
+                </label>
+            </p>
+            </div>
+            <script type="text/javascript">
+                function recordClick() {
+                    var url = <?php echo(json_encode($url));?>;
+                    var http = new XMLHttpRequest();
+                    http.open("POST",url,true);
+                    http.send();
+                }
+            </script>
+        <?php
+        }
+    }
+}
diff --git a/views/elements/manageaccount_element.php b/views/elements/manageaccount_element.php
index 0b9e60e..96301b9 100755
--- a/views/elements/manageaccount_element.php
+++ b/views/elements/manageaccount_element.php
@@ -161,6 +161,27 @@ class ManageaccountElement extends Element
                 <?php
                 }
                 ?>
+                  <tr><th class="table-label"><label for="business-user"><?php
+                    e(tl('manageaccount_element_is_business_user'));
+                        ?></label></th>
+                        <td><input type="checkbox" id="business-user"
+                            name="BUSINESS_USER" value="true"
+                            onclick="toggleDisplay('credit-card','block')" 
+                            <?php if(isset($data['USER']['BUSINESS_USER'])){
+                                if($data['USER']['BUSINESS_USER']==true){
+                        e("checked='checked'");}
+                }?>/>
+                </td></tr>
+                <div id="credit-info">
+                <tr><th class="table-label"><label for="credit-card"><?php
+                    e(tl('manageaccount_element_credit_card_info')); ?></label>
+                </th><td><input type="text" id="credit-card" style=<?php
+                (isset($data['USER']['BUSINESS_USER']) &&
+                $data['USER']['BUSINESS_USER']==true) ?
+                e("display:block;") : e("display:none;");?>
+                    name="CREDIT_CARD_INFO" maxlength="<?php e(CREDIT_CARD_NUMBER_LENGTH);?>"
+                    value="<?php e($data['USER']['CREDIT_CARD_INFO']);?>"
+                    class="narrow-field" /></td></tr></div>
             <tr><td></td>
                 <td class="center"><button
                     class="button-box" type="submit"><?php
diff --git a/views/elements/manageadvertisements_element.php b/views/elements/manageadvertisements_element.php
new file mode 100644
index 0000000..b735739
--- /dev/null
+++ b/views/elements/manageadvertisements_element.php
@@ -0,0 +1,364 @@
+<?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();}
+/**
+ * Element responsible for displaying advertisements information
+ * that someone can create, view, and modify for their own
+ * SeekQuarry/Yioop account.
+ *
+ * @author Pushkar Umaranikar
+ * @package seek_quarry\view\element
+ */
+class ManageAdvertisementsElement extends Element
+{
+    /**
+     *
+     * @param array $data anti-CSRF token
+     */
+    function render($data)
+    {?>
+        <div class="current-activity">
+            <?php
+            if ($data['FORM_TYPE'] == "search") {
+                $this->renderSearchForm($data);
+            } else {
+                $this->renderAdvertisementForm($data);
+            }
+            $data['TABLE_TITLE'] = tl('manageadvertisements_element_list');
+            $data['ACTIVITY'] = 'manageAdvertisements';
+            $data['VIEW'] = $this->view;
+            $this->view->helper("pagingtable")->render($data);
+            ?>
+            <table class="role-table">
+                <tr>
+                    <th><?php e(tl('manageadvertisements_element_adname'));?>
+                    </th>
+                    <?php if (!MOBILE) { ?>
+                        <th><?php
+                            e(tl('manageadvertisements_element_destination_url')
+                            ); ?></th>
+                        <th>
+                            <?php
+                            e(tl('manageadvertisements_element_keywords')); ?>
+                        </th>
+                    <?php } ?>
+                    <th><?php
+                        e(tl('manageadvertisements_element_budget'));?></th>
+                    <th><?php
+                        e(tl('manageadvertisements_element_start_date'));?></th>
+                    <th><?php
+                        e(tl('manageadvertisements_element_end_date'));?></th>
+                    <th><?php
+                        e(tl('manageadvertisements_element_impressions'))?></th>
+                    <th colspan='2'><?php
+                        e(tl('manageadvertisements_element_actions'));?></th>
+                </tr>
+                <?php
+                $base_url = "?c=admin&amp;" . CSRF_TOKEN . "=" .
+                    $data[CSRF_TOKEN] . "&amp;a=manageAdvertisements";
+                if (isset($data['START_ROW'])) {
+                    $base_url .= "&amp;start_row=" . $data['START_ROW'] .
+                        "&amp;end_row=" . $data['END_ROW'] .
+                        "&amp;num_show=" . $data['NUM_SHOW'];
+                }
+                $delete_url = $base_url . "&amp;arg=deleteadvertisement&amp;";
+                $edit_url = $base_url . "&amp;arg=editadvertisement&amp;";
+                $mobile_columns = array('ADV_NAME', 'STATUS');
+                $stretch = (MOBILE) ? 1 : 2;
+                foreach ($data['ADVERTISEMENTS'] as $advertisement) {;
+                echo "<tr>";
+                $isActive = true;
+                $expiry_date = '';
+                foreach ($advertisement as $colname => $role_column) {
+                    if ($colname=="STATUS" && $role_column == 2) {
+                        $isActive = false;
+                    }
+                    if($colname=="END_DATE"){
+                        $expiry_date = $role_column;
+                    }
+                    if ($colname != "ADV_IDS" && $colname!="STATUS") {
+                        if ($colname == "ADV_IDS" || (
+                                MOBILE && !in_array($colname, $mobile_columns))
+                        ) {
+                            continue;
+                        }
+                        if (strlen($role_column) >
+                            $stretch * ADVERTISEMENT_TRUNCATE_LEN
+                        ) {
+                            $role_column = substr($role_column, 0,
+                                 $stretch * ADVERTISEMENT_TRUNCATE_LEN) . "..";
+                        }
+                        echo "<td>$role_column</td>";
+                    }
+                }
+                ?>
+                <td> <?php if($isActive) { ?>
+                    <a href="<?php e($edit_url . 'adv_ids=' .
+                            $advertisement['ADV_IDS'])
+                    ?>"><?php
+                        e(tl('manageadvertisements_element_edit'));
+                        ?></a><?php }
+                    else {
+                    e(tl('manageadvertisements_element_edit'));
+                    }?>
+                </td>
+                <td> <?php if($isActive && (time() <
+                            strtotime($expiry_date))) { ?>
+                    <a onclick='javascript:return confirm("<?php
+                    e(tl('confirm_deactivate_operation')); ?>");' href="<?php
+                    e($delete_url . 'adv=' .
+                        $advertisement['ADV_IDS'].'&amp;'. "status=" .
+                        ADVERTISEMENT_DEACTIVE_STATUS); ?>"><?php
+                        e(tl('manageadvertisements_element_deactivate'));
+                        ?></a><?php }
+                    else if(!$isActive && (time() <
+                            strtotime($expiry_date))){ ?>
+                    <a onclick='javascript:return confirm("<?php
+                    e(tl('confirm_reactivate_operation')); ?>");' href="<?php
+                    e($delete_url . 'adv=' .
+                        $advertisement['ADV_IDS'].'&amp;'. 'status=' .
+                        ADVERTISEMENT_ACTIVE_STATUS); ?>"><?php
+                        e(tl('manageadvertisements_element_reactivate'));
+                        ?></a>
+                    <?php }
+                    else {
+                        e(tl('manageadvertisements_element_deactivate'));
+                    }?>
+                </td>
+                </tr><?php } ?>
+            </table>
+        </div>
+    <?php
+}
+    function renderAdvertisementForm($data)
+    {
+        $base_url = "?c=admin&amp;".CSRF_TOKEN."=".$data[CSRF_TOKEN].
+            "&amp;a=manageAdvertisements";
+        $paging = "";
+        if(isset($data['START_ROW'])) {
+            $paging = "&amp;start_row=".$data['START_ROW'].
+                "&amp;end_row=".$data['END_ROW'].
+                "&amp;num_show=".$data['NUM_SHOW'];
+            $base_url .= $paging;
+        }
+        $editadvertisement = ($data['FORM_TYPE'] == "editadvertisement") ?
+            true: false;
+        if($editadvertisement) {
+            e("<div class='float-opposite'><a href='$base_url'>".
+                tl('manageadvertisement_element_addadvertisement_form')."</a>
+                </div>");
+            e("<h2>".tl('manageadvertisement_element_adv_info'));
+            e("&nbsp;".$this->view->helper("helpbutton")->render(
+                    "Manage Advertisements", $data[CSRF_TOKEN]). "</h2>");
+        } else {
+            e("<h2>".tl('manageadvertisement_element_title'));
+            e("&nbsp;".$this->view->helper("helpbutton")->render(
+                    "Manage Advertisements", $data[CSRF_TOKEN]). "</h2>");
+        }
+        ?>
+        <form id="createAdvertisementForm" name="createAdvertisementForm"
+        method="post" autocomplete="off" enctype="multipart/form-data">
+            <input type="hidden" name="c" value="admin" />
+            <input type="hidden" name="<?php e(CSRF_TOKEN); ?>" value="<?php
+            e($data[CSRF_TOKEN]); ?>" />
+            <input type="hidden" name="a" value="manageAdvertisements"/>
+            <input type="hidden" name="arg" value="<?php
+            e($data['FORM_TYPE']);?>"/>
+            <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']):"";?>" />
+            <table class="adv-table">
+            <tr><th class="table-label"><label for="adv-name"><?php
+                e(tl('createadvertisement_element_displayname')); ?>:
+            </label></th>
+            <td><input type="text" id="adv-name"
+            name="ADV_NAME"  maxlength="<?php e(ADVERTISEMENT_NAME_LEN);?>"
+            value="<?php isset($data['ADV_NAME']) ? e($data['ADV_NAME']):"";?>"
+            class="narrow-field" onkeyup="preview(this);"/>
+            </td></tr>
+            <tr><th class="table-label"><label for="adv-description"><?php
+                e(tl('createadvertisement_element_text')); ?>:
+            </label></th>
+            <td><input type="text" id="adv-description"
+            name="ADV_DESCRIPTION" maxlength=
+                "<?php e(ADVERTISEMENT_TEXT_LEN);?>"
+            value="<?php isset($data['ADV_DESCRIPTION']) ?
+            e($data['ADV_DESCRIPTION']):"";?>" class="narrow-field"
+            onkeyup="preview(this);"/>
+            </td></tr>
+            <tr><th class="table-label"><label for="adv-destination"><?php
+            e(tl('createadvertisement_element_landing_page')); ?>:
+            </label></th>
+            <td><input type="text" id="adv-destination" name="ADV_DESTINATION"
+            value="<?php isset($data['ADV_DESTINATION']) ?
+            e($data['ADV_DESTINATION']):"";?>" class="narrow-field"
+            onkeyup="preview(this,'adv-name')"/>
+            </td></tr>
+            <tr><th class="table-label"><label for="adv-start"><?php
+                e(tl('createadvertisement_element_start_date')); ?>:
+            </label></th><td><input type="date" name="ADV_START_DATE"
+            value="<?php isset($data['ADV_START_DATE']) ?
+            e($data['ADV_START_DATE']):"";?>"
+            <?php if ($editadvertisement){ e('disabled');}?> >
+            </td></tr>
+
+            <tr><th class="table-label"><label for="adv-end"><?php
+            e(tl('createadvertisement_element_end_date')); ?>:
+            </label></th><td><input type="date" name="ADV_END_DATE"
+             value="<?php isset($data['ADV_END_DATE']) ?
+             e($data['ADV_END_DATE']):"";?>"
+             <?php if ($editadvertisement){ e('disabled');}?> >
+             </td></tr>
+            <tr><th class="table-label"><label for="adv-keywords"><?php
+            e(tl('createadvertisement_element_keywords')); ?>:
+            </label></th>
+            <td><textarea class="short-text-area" id="adv-keywords"
+            name="ADV_KEYWORDS" placeholder=
+            "<?php e(tl('createadvertisement_element_helptext'))?>"
+            <?php if ($editadvertisement){ e('disabled');}?>
+            ><?php isset($data['ADV_KEYWORDS']) ? e($data['ADV_KEYWORDS']):"";
+            ?></textarea></td></tr>
+            <tr>
+            <?php
+                if(isset($data['ADV_MIN_BID'])) {
+                ?><th class="table-label"><label for="min-bid"><?php
+                      e(tl('createadvertisement_element_keyword_bid_amount'));
+                      ?>:</label></th><td>
+                  <input type="text" id="" name="ADV_MIN_BID"
+                  value="<?php isset($data['ADV_MIN_BID']) ?
+                  e($data['ADV_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')); ?>:
+            </label></th>
+            <td><input type="text" id="expensive-word"
+            name="EXPENSIVE_WORD"
+            value="<?php isset($data['EXPENSIVE_KEYWORD']) ?
+                    e($data['EXPENSIVE_KEYWORD']):"";?>"
+            class="narrow-field" disabled="true"/></td></tr>
+            <?php
+              }?>
+            <?php if(!$editadvertisement) { ?>
+             <tr><td></td>
+             <td class="center"><input class="button-box"
+              name="keywords" value="<?php e(
+                  tl('createadvertisement_element_addkeywords')); ?>"
+              type="submit"/></td></tr>
+            <?php
+            }?>
+            <?php if(!$editadvertisement){?>
+            <td><input type="hidden" id="adv-min-bid"
+            name="ADV_MIN_BID" value="<?php isset($data['ADV_MIN_BID']) ?
+                    e($data['ADV_MIN_BID']):"";?>" class="narrow-field" />
+            </td></tr>
+            <?php }?>
+            <tr><th class="table-label"><label for="adv-type"><?php
+            e(tl('createadvertisement_element_advtype')); ?>:
+            </label></th>
+            <td><input type="text" id="adv-type"
+                name="ADV_TYPE" value="Text Ad"
+                class="narrow-field" disabled="true" /></td></tr>
+            <tr><th class="table-label"><label for="adv-budget"><?php
+                e(tl('createadvertisement_element_budget')); ?>:
+            </label></th>
+            <td><input type="text" id="adv-budget"
+            name="ADV_BUDGET" value="<?php isset($data['ADV_BUDGET']) ?
+                    e($data['ADV_BUDGET']):"";?>" class="narrow-field"
+                    <?php if ($editadvertisement){ e('disabled');} ?> />
+            </td></tr>
+            <tr><td></td><td class="center"><input class="button-box"
+            name="save" value="<?php e(tl('createadvertisement_element_save'));
+             ?>" type="submit"
+             <?php if(!isset($data['ADV_MIN_BID']) && !$editadvertisement) {
+                 e('disabled');}?>/>
+            </td>
+            </tr>
+            </table>
+            <?php if(MOBILE) { ?>
+               <div class="clear">&nbsp;</div>
+            <?php } ?>
+        </form>
+        <?php if(!$editadvertisement){ ?>
+        <div class="adv-preview">
+            <table>
+             <tr><th class="table-label">
+            <label id="adv-preview-label" for="adv-preview-label">
+                <?php e(tl('createadvertisement_element_preview')); ?>:
+            </label></th></tr><tr><td></td></tr>
+            <tr><td>
+           <a id="adv-name-preview" href="./" class="adv-preview-anchor"
+              target="_blank">
+           </a></td></tr>
+            <tr><td>
+            <label id="adv-description-preview"></label></td></tr>
+            </table>
+        </div>
+        <?php } ?>
+        <script type="text/javascript">
+            function preview(obj) {
+                var previewStr = "-preview";
+                if( arguments.length>1) {
+                    var previewId = arguments[1].concat(previewStr);
+                    var prefix = 'http://';
+                    var protocol= (obj.value.substr
+                    (0,prefix.length)!="http://") ?
+                    "http://" : "";
+                    elt(previewId).href=protocol+obj.value ;
+                }
+                else {
+                    var previewId = obj.id.concat(previewStr);
+                    elt(previewId).innerHTML = obj.value;
+                }
+            }
+        </script>
+        <?php
+    }
+    function renderSearchForm($data)
+    {
+        $controller = "admin";
+        $activity = "manageAdvertisements";
+        $view = $this->view;
+        $title = tl('manageadvertisements_element_search_advertisement');
+        $return_form_name =
+            tl('manageadvertisement_element_addadvertisement_form');
+        $fields = array(
+            tl('manageadvertisements_element_adname') => "name",
+            tl('manageadvertisements_element_description') => "description",
+            tl('manageadvertisements_element_destination_url') => "destination",
+        );
+        $view->helper("searchform")->render($data, $controller, $activity,
+            $view, $title, $return_form_name, $fields);
+    }
+}
+
diff --git a/views/search_view.php b/views/search_view.php
index fd05b51..0340f08 100755
--- a/views/search_view.php
+++ b/views/search_view.php
@@ -206,6 +206,9 @@ class SearchView extends View implements CrawlConstants
         <?php
         } ?>
         <?php
+        if (!$is_landing) {
+            $this->element("displayadvertisement")->render($data);
+        }
         $similar_words = $data['THESAURUS_VARIANTS'];
         $use_thesaurus = WORD_SUGGEST && count($similar_words) > 0 && !MOBILE;
         if ($use_thesaurus) { ?>
-- 
1.9.4.msysgit.1

