<?php
/**
 * phpaga
 *
 * Company management functionality.
 *
 * This file contains the necessary routines to manage companies.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: companies.php 684 2006-03-23 21:33:38Z worf $
 *
 * Copyright (c) 2002, Florian Lanthaler <florian@phpaga.net>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *
 *    * Neither the name of Florian Lanthaler nor the names of his
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


/**
 * Gets a list of companies from the database and returns them as an
 * array.
 *
 * @param int    $cpnID    Company's ID
 * @param array  $cpnList  Array of companiesd
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_getCompanyList (&$cpnList)
{
    $cpnList = array();

    phpaga_db_connect($db);

    $query = "SELECT cpn_id, cpn_name, cpn_city ".
        "FROM companies ".
        "ORDER BY cpn_name";

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    while ($qrow = $result->fetchRow())
    {
        $tmp = $qrow["cpn_name"];

        if (isset($qrow["cpn_city"])
            && ($qrow["cpn_city"] != ""))
        {
            $tmp .= " (".$qrow["cpn_city"].")";
        }

        $cpnList[$qrow["cpn_id"]] = $tmp;
    }

    $result->free();
    return PHPAGA_ERR_NONE;
}


/**
 * Gets a company's information
 *
 * @param int    $cpnID   Company ID
 * @param array  $cpnInfo Array containing the results.
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_getInfo ($cpnID = 0,
                                   &$cpnInfo)
{
    $cpnInfo = array();
    $prjInfo = array();
    $billInfo = array();
    $rows = array();
    $count = 0;
    $summary = array();
    $offset = "";

    if (!isset($cpnID) || (!is_numeric($cpnID)))
        return PHPAGA_ERR_COMPANY_INVALIDID;

    phpaga_db_connect($db);


    $query = "SELECT companies.cpn_id, cpn_name, cpn_address, cpn_address2, cpn_city, ".
        "cpn_zip, cpn_region, companies.ctr_id, cpn_defaultpayterm, ".
        "ctr_name, ctr_code, cpn_logoname, ".
        "companies.ccat_id, ccat_title, cpn_taxnr, ".
        "cpn_url, cpn_phone, cpn_fax, cpn_email, cpn_owner_taxnr, companies.pe_id, ".
        "p2.pe_lastname as owner_pe_lastname, ".
        "p2.pe_firstname as owner_pe_firstname ".
        "FROM companies ".
        "LEFT JOIN companycat ON companycat.ccat_id = companies.ccat_id ".
        "LEFT JOIN countries on countries.ctr_id = companies.ctr_id ".
        "LEFT JOIN persons p2 ON p2.pe_id = companies.pe_id ".
        "WHERE companies.cpn_id = ".$db->quoteSmart($cpnID);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() < 1)
        return PHPAGA_ERR_DB_NO_ROWS;

    if ($qrow = $result->fetchRow())
    {
        $qrow["location"] =
            phpaga_getLocation($qrow["cpn_city"],
                               $qrow["cpn_region"]);

        $qrow["full_location"] =
            phpaga_getFullLocation($qrow["cpn_city"],
                                   $qrow["cpn_region"],
                                   $qrow["cpn_zip"],
                                   $qrow["ctr_name"]);

        $qrow["owner_pe_person"] =
            phpaga_persons_formatname($qrow["owner_pe_lastname"],
                                      $qrow["owner_pe_firstname"]);

        $cpnInfo = $qrow;
    }

    $result->free();
    phpaga_sanitizeArray($cpnInfo);

    $billInfo = array("cpn_id" => $cpnID);

    $result = phpaga_bills_search($rows, $count, $billInfo);

    if ($result == PHPAGA_ERR_NONE)
        $cpnInfo["bills"] = $rows;

    $quotInfo = array("cpn_id" => $cpnID);

    $result = phpaga_quotations_search($rows, $count, $quotInfo);

    if ($result == PHPAGA_ERR_NONE)
        $cpnInfo["quotations"] = $rows;

    $prjInfo["cpn_id"] = $cpnID;

    $result = phpaga_projects_search($rows, $count, $duration, $prjIds,
                                     $prjInfo, $offset , PHPAGA_RECORDS_PERPAGE);

    if ($result == PHPAGA_ERR_NONE)
        $cpnInfo["projects"] = $rows;
    elseif ($result != PHPAGA_ERR_DB_NO_ROWS)
        return $result;

    $result = phpaga_bills_getSummaryCpn($cpnID, $summary);

    if ($result == PHPAGA_ERR_NONE)
        $cpnInfo["billing_summary"] = $summary;
    else
        return $result;

    return PHPAGA_ERR_NONE;
}


/**
 * Gets a list of company categories from the database and returns them as the
 * content of an array.
 *
 * @param array $ccatList  List of company categories as content of a <select> field
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_getCategories (&$ccatList)
{
    $ccatList = array();

    phpaga_db_connect($db);

    $query = "SELECT ccat_id, ccat_title ".
        "FROM companycat ".
        "ORDER BY ccat_title";

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() < 1)
        return PHPAGA_ERR_DB_NO_ROWS;

    while ($qrow = $result->fetchRow())
        $ccatList[$qrow["ccat_id"]] = $qrow["ccat_title"];

    $result->free();

    return PHPAGA_ERR_NONE;
}


/**
 * Checks if all fields of a company contain valid values.
 *
 * @param  array  $cpnInfo  Array containing the company's information.
 *
 * @return array  $errors   Array containing error codes
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_validdata ($cpnInfo)
{

    $errors = array();

    if (!is_array($cpnInfo))
        $cpnInfo = array($cpnInfo);

    if (isset($cpnInfo["cpn_email"]) && strlen($cpnInfo["cpn_email"])
        && !phpaga_checkemailaddress($cpnInfo["cpn_email"]))
        $errors[] = PHPAGA_ERR_INVALID_EMAIL;

    if (!isset($cpnInfo["cpn_name"]) || !strlen($cpnInfo["cpn_name"]))
        $errors[] = PHPAGA_ERR_COMPANY_INVALIDNAME;

    if (isset($cpnInfo["ctr_id"]) && !is_numeric($cpnInfo["ctr_id"]))
        $errors[] = PHPAGA_ERR_COUNTRY_INVALIDID;

    if (isset($cpnInfo["ccat_id"]) && !is_numeric($cpnInfo["ccat_id"]))
        $errors[] = PHPAGA_ERR_CCAT_INVALIDID;

    if (isset($cpnInfo["pe_id"]) && !is_numeric($cpnInfo["pe_id"]))
        $errors[] = PHPAGA_ERR_PERSON_INVALIDID;

    return $errors;
}


/**
 * Adds a company to the database
 *
 * @param array  $cpnInfo  Array containing the company information
 * @param int    &$cpn_id  The resulting ID of the newly inserted company
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_add ($cpnInfo, &$cpn_id)
{

    $result = phpaga_companies_validdata($cpnInfo);

    if (count($result) > 0)
        return $result;

    phpaga_db_connect($db);

    $cpn_id = $db->nextId("companies_cpn_id");

    if (!isset($cpnInfo["cpn_name"]) || !strlen($cpnInfo["cpn_name"]))
        $cpnInfo["cpn_name"] = NULL;

    if (!isset($cpnInfo["cpn_address"]) || !strlen($cpnInfo["cpn_address"]))
        $cpnInfo["cpn_address"] = NULL;

    if (!isset($cpnInfo["cpn_address2"]) || !strlen($cpnInfo["cpn_address2"]))
        $cpnInfo["cpn_address2"] = NULL;

    if (!isset($cpnInfo["cpn_city"]) || !strlen($cpnInfo["cpn_city"]))
        $cpnInfo["cpn_city"] = NULL;

    if (!isset($cpnInfo["cpn_zip"]) || !strlen($cpnInfo["cpn_zip"]))
        $cpnInfo["cpn_zip"] = NULL;

    if (!isset($cpnInfo["cpn_region"]) || !strlen($cpnInfo["cpn_region"]))
        $cpnInfo["cpn_region"] = NULL;

    if (!isset($cpnInfo["cpn_taxnr"]) || !strlen($cpnInfo["cpn_taxnr"]))
        $cpnInfo["cpn_taxnr"] = NULL;

    if (!isset($cpnInfo["cpn_url"]) || !strlen($cpnInfo["cpn_url"]))
        $cpnInfo["cpn_url"]  = NULL;

    if (!isset($cpnInfo["cpn_phone"]) || !strlen($cpnInfo["cpn_phone"]))
        $cpnInfo["cpn_phone"] = NULL;

    if (!isset($cpnInfo["cpn_fax"]) || !strlen($cpnInfo["cpn_fax"]))
        $cpnInfo["cpn_fax"] = NULL;

    if (!isset($cpnInfo["cpn_email"]) || !strlen($cpnInfo["cpn_email"]))
        $cpnInfo["cpn_email"] = NULL;

    if (!isset($cpnInfo["cpn_defaultpayterm"]) || !strlen($cpnInfo["cpn_defaultpayterm"]))
        $cpnInfo["cpn_defaultpayterm"] = NULL;

    /* strings are escaped/quoted automatically by autoExecute */

    $fields = array("cpn_id" => $cpn_id,
                    "cpn_name" => $cpnInfo["cpn_name"],
                    "cpn_address" => $cpnInfo["cpn_address"],
                    "cpn_address2" => $cpnInfo["cpn_address2"],
                    "cpn_city" => $cpnInfo["cpn_city"],
                    "cpn_zip" => $cpnInfo["cpn_zip"],
                    "cpn_region" => $cpnInfo["cpn_region"],
                    "ctr_id" => $cpnInfo["ctr_id"],
                    "ccat_id" => $cpnInfo["ccat_id"],
                    "cpn_taxnr" => $cpnInfo["cpn_taxnr"],
                    "cpn_url" => $cpnInfo["cpn_url"],
                    "cpn_phone" => $cpnInfo["cpn_phone"],
                    "cpn_fax" => $cpnInfo["cpn_fax"],
                    "cpn_email" => $cpnInfo["cpn_email"],
                    "pe_id" => $cpnInfo["pe_id"],
                    "cpn_defaultpayterm" => $cpnInfo["cpn_defaultpayterm"]
        );

    $result = $db->autoExecute("companies", $fields, DB_AUTOQUERY_INSERT);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}


/**
 * Updates a company.
 *
 * @param array  $cpnInfo Array containing the company information
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_update ($cpnInfo)
{

    $result = phpaga_companies_validdata($cpnInfo);

    if (count($result) > 0)
        return $result;

    if (!isset($cpnInfo["cpn_name"]) || !strlen($cpnInfo["cpn_name"]))
        $cpnInfo["cpn_name"] = NULL;

    if (!isset($cpnInfo["cpn_address"]) || !strlen($cpnInfo["cpn_address"]))
        $cpnInfo["cpn_address"] = NULL;

    if (!isset($cpnInfo["cpn_address2"]) || !strlen($cpnInfo["cpn_address2"]))
        $cpnInfo["cpn_address2"] = NULL;

    if (!isset($cpnInfo["cpn_city"]) || !strlen($cpnInfo["cpn_city"]))
        $cpnInfo["cpn_city"] = NULL;

    if (!isset($cpnInfo["cpn_zip"]) || !strlen($cpnInfo["cpn_zip"]))
        $cpnInfo["cpn_zip"] = NULL;

    if (!isset($cpnInfo["cpn_region"]) || !strlen($cpnInfo["cpn_region"]))
        $cpnInfo["cpn_region"] = NULL;

    if (!isset($cpnInfo["cpn_taxnr"]) || !strlen($cpnInfo["cpn_taxnr"]))
        $cpnInfo["cpn_taxnr"] = NULL;

    if (!isset($cpnInfo["cpn_url"]) || !strlen($cpnInfo["cpn_url"]))
        $cpnInfo["cpn_url"]  = NULL;

    if (!isset($cpnInfo["cpn_phone"]) || !strlen($cpnInfo["cpn_phone"]))
        $cpnInfo["cpn_phone"] = NULL;

    if (!isset($cpnInfo["cpn_fax"]) || !strlen($cpnInfo["cpn_fax"]))
        $cpnInfo["cpn_fax"] = NULL;

    if (!isset($cpnInfo["cpn_email"]) || !strlen($cpnInfo["cpn_email"]))
        $cpnInfo["cpn_email"] = NULL;

    if (!isset($cpnInfo["cpn_defaultpayterm"]) || !strlen($cpnInfo["cpn_defaultpayterm"]))
        $cpnInfo["cpn_defaultpayterm"] = NULL;

    /* strings are escaped/quoted automatically by autoExecute */

    $fields = array("cpn_name" => $cpnInfo["cpn_name"],
                    "cpn_address" => $cpnInfo["cpn_address"],
                    "cpn_address2" => $cpnInfo["cpn_address2"],
                    "cpn_city" => $cpnInfo["cpn_city"],
                    "cpn_zip" => $cpnInfo["cpn_zip"],
                    "cpn_region" => $cpnInfo["cpn_region"],
                    "ctr_id" => $cpnInfo["ctr_id"],
                    "ccat_id" => $cpnInfo["ccat_id"],
                    "cpn_taxnr" => $cpnInfo["cpn_taxnr"],
                    "cpn_url" => $cpnInfo["cpn_url"],
                    "cpn_phone" => $cpnInfo["cpn_phone"],
                    "cpn_fax" => $cpnInfo["cpn_fax"],
                    "cpn_email" => $cpnInfo["cpn_email"],
                    "cpn_defaultpayterm" => $cpnInfo["cpn_defaultpayterm"]
        );

    phpaga_db_connect($db);
    $result = $db->autoExecute("companies", $fields, DB_AUTOQUERY_UPDATE,
                               "cpn_id = ".$db->quoteSmart($cpnInfo["cpn_id"]));

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}

/**
 * Loads all company categories into an array.
 *
 * @param array  $ccatInfo   Array containing the results
 *
 * @return int   $result       A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_getCpncats (&$ccatInfo)
{
    $ccatInfo = array();

    phpaga_db_connect($db);

    $query = "SELECT ccat_id, ccat_title ".
        "FROM companycat ORDER BY ccat_title ";

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() < 1)
        return PHPAGA_ERR_DB_NO_ROWS;

    while ($qrow = $result->fetchRow())
    {
        phpaga_sanitizeArray($qrow);
        $ccatInfo[] = $qrow;
    }

    $result->free();
    return PHPAGA_ERR_NONE;
}


/**
 * Add a new company category.
 *
 * @param  string  $ccat_title   Company category to be added
 *
 * @return int     $result       A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_addCpncat ($ccat_title)
{

    if (!isset($ccat_title) || !strlen($ccat_title))
        return PHPAGA_ERR_CCAT_INVALIDTITLE;

    phpaga_db_connect($db);

    $fields = array("ccat_id" => $db->nextId("companycat_ccat_id"),
                    "ccat_title" => $ccat_title);

    $result = $db->autoExecute("companycat", $fields, DB_AUTOQUERY_INSERT);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}


/**
 * Delete a company category.
 *
 * @param  int     $ccat_id     Company category to be deleted
 *
 * @return int     $result      A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_deleteCpncat ($ccat_id)
{
    if (!isset($ccat_id) || !is_numeric($ccat_id))
        return PHPAGA_ERR_CCAT_INVALIDID;

    phpaga_db_connect($db);

    /* first check if this ccat is needed by any table relationship
     * if it is not needed, then delete it, otherwise don't */

    $query = "SELECT cpn_id ".
        "FROM companies ".
        "WHERE ccat_id = ".$db->quoteSmart($ccat_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    /* any record matching the query? in that case we cannot delete
     * this company category, as there are dependencies
     */

    if ($result->numRows() > 0)
        return PHPAGA_ERR_DEL_DEPENDENCIES;

    $query = "DELETE FROM companycat WHERE ccat_id = ".
        $db->quoteSmart($ccat_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}

/**
 * Delete a company.
 *
 * @param  int     $cpn_id      Company ID
 *
 * @return int     $result       A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_delete ($cpn_id)
{
    if (!isset($cpn_id) || !is_numeric($cpn_id))
        return PHPAGA_ERR_BILL_INVALID_CPNID;

    phpaga_db_connect($db);

    /* first check, if this company is needed by any table relationship
     * if it is not needed, then delete it, otherwise don't */

    $query = "SELECT cpn_id FROM bills ".
        "WHERE cpn_id = ".$db->quoteSmart($cpn_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() > 0)
        return PHPAGA_ERR_DEL_DEPENDENCIES;

    $query = "SELECT cpn_id FROM quotations ".
        "WHERE cpn_id = ".$db->quoteSmart($cpn_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() > 0)
        return PHPAGA_ERR_DEL_DEPENDENCIES;

    $query = "SELECT cpn_id FROM projects ".
        "WHERE cpn_id = ".$db->quoteSmart($cpn_id).
        " OR cpn_id_issuebill = ".$db->quoteSmart($cpn_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() > 0)
        return PHPAGA_ERR_DEL_DEPENDENCIES;

    $query = "SELECT cpn_id FROM persons ".
        "WHERE cpn_id = ".$db->quoteSmart($cpn_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() > 0)
        return PHPAGA_ERR_DEL_DEPENDENCIES;

    $query = "DELETE FROM companies ".
        "WHERE cpn_id = ".$db->quoteSmart($cpn_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}


/**
 * Gets all companies matching the search parmeters
 * (from $offset to $limit, if set)
 *
 * @param array  $rows      Array containing the results
 * @param int    $count     Number of records matching the query
 * @param array  $cpnInfo   Company information
 * @param array  $cpnIds    IDs of the resulting companies
 * @param int    $order     Specifies the order by field
 *
 * @param int    $offset    Offset (optional)
 * @param int    $limit     Limit (optional)
 *
 * @return int   $result    A result code.
 *
 * @author Mark Parssey <markpa@users.sourceforge.net>
 * @since phpaga 0.3
 */

function phpaga_companies_search (&$rows,
                                 &$count,
                                 &$cpnIds,
                                 $cpnInfo,
                                 $order = 0,
                                 $offset = "",
                                 $limit = "")
{

    $count = 0;
    $rows = array();
    $cpnIds = array();
    $where = array();
    $where_clause = "";

    phpaga_db_connect($db);

    /* how many matching records are there */

    $countquery = "SELECT COUNT(cpn_id) AS count_cpn "."FROM companies ";

    /* select limited number of records */

    $query = "SELECT cpn_id, cpn_name, cpn_address, cpn_address2, cpn_city, ".
        "cpn_region, cpn_zip, companies.ctr_id, ctr_name, ctr_code, ".
        "companies.ccat_id, ccat_title, cpn_taxnr, cpn_url,  ".
        "cpn_phone, cpn_fax, cpn_email, cpn_owner_taxnr, pe_id ".
        "FROM companies ".
        "LEFT JOIN companycat ON companycat.ccat_id = companies.ccat_id ".
        "LEFT JOIN countries ON countries.ctr_id = companies.ctr_id ";

    /* collect elements of the where clause */

    if (isset($cpnInfo["cpn_name"]) && strlen($cpnInfo["cpn_name"]))
        $where[] = "companies.cpn_name like '%".$db->escapeSimple($cpnInfo["cpn_name"])."%'";

    if (isset($cpnInfo["cpn_address"]) && strlen($cpnInfo["cpn_address"]))
        $where[] = "companies.cpn_address like '%".$db->escapeSimple($cpnInfo["cpn_address"])."%'";

    if (isset($cpnInfo["cpn_address2"]) && strlen($cpnInfo["cpn_address2"]))
        $where[] = "companies.cpn_address2 like '%".$db->escapeSimple($cpnInfo["cpn_address2"])."%'";

    if (isset($cpnInfo["cpn_city"]) && strlen($cpnInfo["cpn_city"]))
        $where[] = "companies.cpn_city like '%".$db->escapeSimple($cpnInfo["cpn_city"])."%'";

    if (isset($cpnInfo["cpn_zip"]) && strlen($cpnInfo["cpn_zip"]))
        $where[] = "companies.cpn_zip like '%".$db->escapeSimple($cpnInfo["cpn_zip"])."%'";

    if (isset($cpnInfo["cpn_region"]) && strlen($cpnInfo["cpn_region"]))
        $where[] = "companies.cpn_region like '%".$db->escapeSimple($cpnInfo["cpn_region"])."%'";

    if (isset($cpnInfo["ctr_id"]) && is_numeric($cpnInfo["ctr_id"]))
        $where[] = "companies.ctr_id = ".$db->quoteSmart($cpnInfo["ctr_id"]);

    if (isset($cpnInfo["ccat_id"]) && is_numeric($cpnInfo["ccat_id"]))
        $where[] = "companies.ccat_id = ".$db->quoteSmart($cpnInfo["ccat_id"]);

    if (isset($cpnInfo["cpn_email"]) && ($cpnInfo["cpn_email"]))
        $where[] = "companies.cpn_email like '%".$db->escapeSimple($cpnInfo["cpn_email"])."%'";

    /* build the where clause */
    if (count($where) > 0)
    {
        $query .= "WHERE ".implode(" AND ", $where)." ";
        $countquery .= "WHERE ".implode(" AND ", $where)." ";
    }

    $query .= " ORDER BY ";

    /* build the order-by clause */
    /* check validity of order value, eventually set it to default  */

    if (($order == "") || ($order == 0) || !is_numeric($order))
        $order = ORDER_CPN_NAME_ASC;

    switch ($order)
    {
        case ORDER_CPN_NAME_ASC:
            $query .= "cpn_name ASC";
            break;
        case ORDER_CPN_NAME_DESC:
            $query .= "cpn_name DESC";
            break;
        case ORDER_CPN_ADDRESS_ASC:
            $query .= "cpn_address ASC";
            break;
        case ORDER_CPN_ADDRESS_DESC:
            $query .= "cpn_address DESC";
            break;
        case ORDER_CPN_CITY_ASC:
            $query .= "cpn_city ASC";
            break;
        case ORDER_CPN_CITY_DESC:
            $query .= "cpn_city DESC";
            break;
        case ORDER_CPN_COUNTRY_ASC:
            $query .= "ctr_name ASC";
            break;
        case ORDER_CPN_COUNTRY_DESC:
            $query .= "ctr_name DESC";
            break;
        case ORDER_CPN_CCAT_ASC:
            $query .= "ccat_title ASC";
            break;
        case ORDER_CPN_CCAT_DESC:
            $query .= "ccat_title DESC";
            break;
        case ORDER_CPN_EMAIL_ASC:
            $query .= "cpn_email ASC";
            break;
        case ORDER_CPN_EMAIL_DESC:
            $query .= "cpn_email DESC";
            break;
        default:
            $query .= "cpn_name ASC";
            break;
    }

    /* first do the count stuff */

    $result = $db->query($countquery);

    if ((!DB::isError($result)) && ($result->numRows() > 0)
        && ($countrow = $result->fetchRow()))
    {
        $count = $countrow["count_cpn"];
    }

    /* limit the number of results starting from $offset if both $offset
     * and $limit are set and valid */

    if (isset($offset) && is_numeric($offset) && isset($limit)
        && is_numeric($limit) && ($limit > 0))

        $result = $db->limitQuery($query, $offset, $limit);
    else
        $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() < 1)
        return PHPAGA_ERR_DB_NO_ROWS;

    while ($qrow = $result->fetchRow())
    {

        phpaga_sanitizearray($qrow);

        $qrow["cpn_long_address"] = ($qrow["cpn_address"]);
				if (isset($qrow["cpn_address2"]) && strlen($qrow["cpn_address2"]))
						$qrow["cpn_long_address"] .= "\n\r".$qrow["cpn_address2"];

        $rows[] = $qrow;
        $cpnIds[] = $qrow["cpn_id"];
    }

    $result->free();
    return PHPAGA_ERR_NONE;
}

/**
 * Determine whether some person is the owner of a company record. If
 * pe_id is omitted, the current user's pe_id is used.
 *
 * @param bool   &$isowner  Is pe_id the owner of cpn_id?
 * @param int    $cpn_id    Company ID
 *
 * @param int    $pe_id     Person ID (optional, if omitted, the
 *                          current user's pe_id is used)
 *
 * @return int   $result    A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_isowner (&$isowner, $cpn_id, $pe_id = null)
{

    $isowner = false;

    if (($pe_id == null) && isset($_SESSION["auth_user"])
        && isset($_SESSION["auth_user"]["pe_id"])
        && is_numeric($_SESSION["auth_user"]["pe_id"]))

        $pe_id = $_SESSION["auth_user"]["pe_id"];

    phpaga_db_connect($db);

    $cpnpe_id = $db->getOne("SELECT pe_id FROM companies WHERE cpn_id = ".
                            $db->quoteSmart($cpn_id));

    if (DB::isError($cpnpe_id))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    $isowner = ($cpnpe_id == $pe_id);

    return PHPAGA_ERR_NONE;
}


/**
 * Determine the default term of payment for a given company.
 *
 * @param int    $cpn_id    Company ID
 *
 * @return int   $result    Default term of payment or null
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_getdefaultpayterm ($cpn_id)
{

    if (!strlen($cpn_id) || !is_numeric($cpn_id))
        return null;

    phpaga_db_connect($db);

    $payterm = $db->getOne("SELECT cpn_defaultpayterm FROM companies WHERE cpn_id = ".
                            $db->quoteSmart($cpn_id));

    if (DB::isError($payterm))
        return null;

    return $payterm;
}

?>