function select($where = "", $group_by = "", $order_by = "", $limit = "")
 {
     global $client;
     if ($where != "") {
         $where = $where . " AND idclient = '" . Contenido_Security::escapeDB($client, NULL) . "'";
     }
     return parent::select($where, $group_by, $order_by, $limit);
 }
 function set($idworkflowitem, $action)
 {
     $this->select("idworkflowitem = '" . Contenido_Security::escapeDB($idworkflowitem, NULL) . "' AND action = '" . Contenido_Security::escapeDB($action, NULL) . "'");
     if (!$this->next()) {
         $newitem = parent::create();
         $newitem->setField("idworkflowitem", $idworkflowitem);
         $newitem->setField("action", $action);
         $newitem->store();
     }
 }
function getGroupIDs(&$db)
{
    global $cfg, $sess, $auth, $group_id, $_arrGroupIDs_gGI;
    if (is_array($_arrGroupIDs_gGI)) {
        return $_arrGroupIDs_gGI;
    }
    $sql = "SELECT group_id FROM " . $cfg["tab"]["groupmembers"] . " WHERE user_id='" . Contenido_Security::escapeDB($auth->auth["uid"], $db) . "'";
    $db->query($sql);
    $_arrGroupIDs_gGI = array();
    while ($db->next_record()) {
        $_arrGroupIDs_gGI[] = $db->f('group_id');
    }
    return $_arrGroupIDs_gGI;
}
 /**
  * Creates a new newsletter
  * @param $name string specifies the newsletter name
  */
 public function create($sName)
 {
     global $client, $lang, $auth;
     $sName = Contenido_Security::escapeDB($sName, null);
     $client = Contenido_Security::toInteger($client);
     $lang = Contenido_Security::toInteger($lang);
     // Check if the newsletter name already exists
     $this->resetQuery;
     $this->setWhere("idclient", $client);
     $this->setWhere("idlang", $lang);
     $this->setWhere("name", $sName);
     $this->query();
     if ($this->next()) {
         return $this->create($sName . "_" . substr(md5(rand()), 0, 10));
     }
     $oItem = parent::create();
     $oItem->set("idclient", $client);
     $oItem->set("idlang", $lang);
     $oItem->set("name", $sName);
     $oItem->set("created", date("Y-m-d H:i:s"), false);
     $oItem->set("author", Contenido_Security::escapeDB($auth->auth["uid"], null));
     $oItem->store();
     return $oItem;
 }
function checkLinks()
{
    global $auth, $cfgClient, $client, $cfg, $cronjob, $db, $aErrors, $lang, $langart, $whitelist;
    global $aSearchIDInfosArt, $aSearchIDInfosCat, $aSearchIDInfosCatArt, $aSearchIDInfosNonID;
    if (count($aSearchIDInfosArt) > 0) {
        // Checks idarts
        for ($i = 0; $i < count($aSearchIDInfosArt); $i++) {
            if ($i == 0) {
                $sSearch = Contenido_Security::toInteger($aSearchIDInfosArt[$i]['id']);
            } else {
                $sSearch .= ", " . Contenido_Security::toInteger($aSearchIDInfosArt[$i]['id']);
            }
        }
        // Check articles
        $aFind = array();
        $sql = "SELECT idart, online FROM " . $cfg['tab']['art_lang'] . " WHERE idart IN (" . $sSearch . ")";
        $db->query($sql);
        while ($db->next_record()) {
            $aFind[$db->f("idart")] = array("online" => $db->f("online"));
        }
        for ($i = 0; $i < count($aSearchIDInfosArt); $i++) {
            if (isset($aFind[$aSearchIDInfosArt[$i]['id']]) && $aFind[$aSearchIDInfosArt[$i]['id']]['online'] == 0) {
                $aErrors['art'][] = array_merge($aSearchIDInfosArt[$i], array("error_type" => "offline"));
            } elseif (!isset($aFind[$aSearchIDInfosArt[$i]['id']])) {
                $aErrors['art'][] = array_merge($aSearchIDInfosArt[$i], array("error_type" => "unknown"));
            }
        }
    }
    if (count($aSearchIDInfosCat) > 0) {
        // Checks idcats
        for ($i = 0; $i < count($aSearchIDInfosCat); $i++) {
            if ($i == 0) {
                $sSearch = $aSearchIDInfosCat[$i]['id'];
            } else {
                $sSearch .= ", " . $aSearchIDInfosCat[$i]['id'];
            }
        }
        // Check categorys
        $aFind = array();
        $sql = "SELECT idcat, startidartlang, visible FROM " . $cfg['tab']['cat_lang'] . " WHERE idcat IN (" . $sSearch . ") AND idlang = '" . Contenido_Security::toInteger($lang) . "'";
        $db->query($sql);
        while ($db->next_record()) {
            $aFind[$db->f("idcat")] = array("online" => $db->f("visible"), "startidart" => $db->f("startidartlang"));
        }
        for ($i = 0; $i < count($aSearchIDInfosCat); $i++) {
            if (is_array($aFind[$aSearchIDInfosCat[$i]['id']]) && $aFind[$aSearchIDInfosCat[$i]['id']]['startidart'] == 0) {
                $aErrors['cat'][] = array_merge($aSearchIDInfosCat[$i], array("error_type" => "startart"));
            } elseif (is_array($aFind[$aSearchIDInfosCat[$i]['id']]) && $aFind[$aSearchIDInfosCat[$i]['id']]['online'] == 0) {
                $aErrors['cat'][] = array_merge($aSearchIDInfosCat[$i], array("error_type" => "offline"));
            } elseif (!is_array($aFind[$aSearchIDInfosCat[$i]['id']])) {
                $aErrors['cat'][] = array_merge($aSearchIDInfosCat[$i], array("error_type" => "unknown"));
            }
            if (is_array($aFind[$aSearchIDInfosCat[$i]['id']]) && $aFind[$aSearchIDInfosCat[$i]['id']]['startidart'] != 0) {
                $sql = "SELECT idart FROM " . $cfg['tab']['art_lang'] . " WHERE idartlang = '" . $aFind[$aSearchIDInfosCat[$i]['id']]['startidart'] . "' AND online = '1'";
                $db->query($sql);
                if ($db->num_rows() == 0) {
                    $aErrors['cat'][] = array_merge($aSearchIDInfosCat[$i], array("error_type" => "startart"));
                }
            }
        }
    }
    if (count($aSearchIDInfosCatArt) > 0) {
        // Checks idcatarts
        for ($i = 0; $i < count($aSearchIDInfosCatArt); $i++) {
            if ($i == 0) {
                $sSearch = Contenido_Security::toInteger($aSearchIDInfosCatArt[$i]['id']);
            } else {
                $sSearch .= ", " . Contenido_Security::toInteger($aSearchIDInfosCatArt[$i]['id']);
            }
        }
        // Check articles
        $aFind = array();
        $sql = "SELECT idcatart FROM " . $cfg['tab']['cat_art'] . " WHERE idcatart IN (" . $sSearch . ")";
        $db->query($sql);
        while ($db->next_record()) {
            $aFind[] = $db->f("idcatart");
        }
        for ($i = 0; $i < count($aSearchIDInfosCatArt); $i++) {
            if (!in_array($aSearchIDInfosCatArt[$i]['id'], $aFind)) {
                $aErrors['art'][] = array_merge($aSearchIDInfosCatArt[$i], array("error_type" => "unknown"));
            }
        }
    }
    if (count($aSearchIDInfosNonID) != 0) {
        // Checks other links (e. g. http, www, dfbs)
        // Select userrights (is the user admin or sysadmin?)
        $sql = "SELECT username FROM " . $cfg['tab']['phplib_auth_user_md5'] . " WHERE user_id='" . Contenido_Security::escapeDB($auth->auth['uid'], $db) . "' AND perms LIKE '%admin%'";
        $db->query($sql);
        if ($db->num_rows() > 0 || $cronjob == true) {
            // User is admin when he is or when he run the cronjob
            $iAdmin = true;
        }
        for ($i = 0; $i < count($aSearchIDInfosNonID); $i++) {
            if (url_is_uri($aSearchIDInfosNonID[$i]['url'])) {
                if (substr($aSearchIDInfosNonID[$i]['url'], 0, strlen($aSearchIDInfosNonID[$i]['url'])) == $cfgClient[$client]['path']['htmlpath']) {
                    $iPing = @file_exists(str_replace($cfgClient[$client]['path']['htmlpath'], $cfgClient[$client]['path']['frontend'], $aSearchIDInfosNonID[$i]['url']));
                } else {
                    $iPing = @fopen($aSearchIDInfosNonID[$i]['url'], 'r');
                }
                if (!$iPing) {
                    if (url_is_image($aSearchIDInfosNonID[$i]['url'])) {
                        $aErrors['docimages'][] = array_merge($aSearchIDInfosNonID[$i], array("error_type" => "unknown"));
                    } else {
                        $aErrors['others'][] = array_merge($aSearchIDInfosNonID[$i], array("error_type" => "unknown"));
                    }
                }
            } elseif (substr($aSearchIDInfosNonID[$i]['url'], strlen($aSearchIDInfosNonID[$i]['url']) - 5, 5) == ".html") {
                $iPing = @file_exists($cfgClient[$client]['path']['htmlpath'] . $aSearchIDInfosNonID[$i]['url']);
                if (!$iPing) {
                    $aErrors['art'][] = array_merge($aSearchIDInfosNonID[$i], array("error_type" => "unknown"));
                }
            } elseif (substr($aSearchIDInfosNonID[$i]['url'], 0, 20) == "dbfs.php?file=dbfs:/") {
                $sDBurl = substr($aSearchIDInfosNonID[$i]['url'], 20, strlen($aSearchIDInfosNonID[$i]['url']));
                $iPos = strrpos($sDBurl, '/');
                $sDirname = substr($sDBurl, 0, $iPos);
                $sFilename = substr($sDBurl, $iPos + 1);
                // Check categorys
                $sql = "SELECT iddbfs FROM " . $cfg['tab']['dbfs'] . " WHERE dirname IN('" . $sDirname . "', '" . html_entity_decode($sDirname) . "', '" . urldecode($sDirname) . "') AND filename = '" . $sFilename . "'";
                $db->query($sql);
                if ($db->num_rows() == 0) {
                    $aErrors['docimages'][] = array_merge($aSearchIDInfosNonID[$i], array("error_type" => "dbfs"));
                }
            } else {
                if (!file_exists($cfgClient[$client]['path']['frontend'] . $aSearchIDInfosNonID[$i]['url'])) {
                    if (url_is_image($aSearchIDInfosNonID[$i]['url'])) {
                        $aErrors['docimages'][] = array_merge($aSearchIDInfosNonID[$i], array("error_type" => "unknown"));
                    } else {
                        $aErrors['others'][] = array_merge($aSearchIDInfosNonID[$i], array("error_type" => "unknown"));
                    }
                }
            }
        }
    }
    return $aErrors;
}
            case "Minutes":
                $maxtime = $starttime + $timelimit * 60;
                break;
            case "Hours":
                $maxtime = $starttime + $timelimit * 3600;
                break;
            case "Days":
                $maxtime = $starttime + $timelimit * 86400;
                break;
            case "Weeks":
                $maxtime = $starttime + $timelimit * 604800;
                break;
            case "Months":
                $maxtime = $starttime + $timelimit * 2678400;
                break;
            case "Years":
                $maxtime = $starttime + $timelimit * 31536000;
                break;
            default:
                $maxtime = $starttime + $timelimit;
        }
        if ($maxtime < time()) {
            $pos = $pos + 1;
            $workflowusersequences->select("idworkflowitem = '{$wfitem}' AND position = '" . Contenido_Security::escapeDB($pos, NULL) . "'");
            if ($wfobj = $workflowusersequences->next()) {
                $obj->set("idusersequence", $wfobj->get("idusersequence"));
                $obj->store();
            }
        }
    }
}
 */
if (!defined('CON_FRAMEWORK')) {
    die('Illegal call');
}
$nav = new Contenido_Navigation();
$parentarea = getParentAreaID($area);
$sql = "SELECT\n                idarea\n            FROM\n                " . $cfg["tab"]["area"] . " AS a\n            WHERE\n                a.name = '" . Contenido_Security::escapeDB($parentarea, $db) . "' OR\n                a.parent_id = '" . Contenido_Security::escapeDB($parentarea, $db) . "'\n            ORDER BY\n                idarea";
$db->query($sql);
$in_str = "";
while ($db->next_record()) {
    $in_str .= $db->f('idarea') . ',';
}
$len = strlen($in_str) - 1;
$in_str = substr($in_str, 0, $len);
$in_str = '(' . $in_str . ')';
$sql = "SELECT\n                b.location AS location,\n                a.name AS name\n            FROM\n                " . $cfg["tab"]["area"] . " AS a,\n                " . $cfg["tab"]["nav_sub"] . " AS b\n            WHERE\n                b.idarea IN " . Contenido_Security::escapeDB($in_str, $db) . " AND\n                b.idarea = a.idarea AND\n                b.level = 1\n            ORDER BY\n                b.idnavs";
$db->query($sql);
while ($db->next_record()) {
    # Extract caption from
    # the xml language file
    $caption = $nav->getName($db->f("location"));
    $tmp_area = $db->f("name");
    # Set template data
    $tpl->set("d", "ID", 'c_' . $tpl->dyn_cnt[0]);
    $tpl->set("d", "CLASS", '');
    $tpl->set("d", "OPTIONS", '');
    $tpl->set("d", "CAPTION", '<a class="white" onclick="sub.clicked(this)" target="right_bottom" href="' . $sess->url("main.php?area={$tmp_area}&frame=4&idworkflow={$idworkflow}") . '">' . $caption . '</a>');
    if ($area == $tmp_area) {
        $tpl->set('s', 'DEFAULT', markSubMenuItem($tpl->dyn_cnt[0], true));
    }
    $tpl->next();
    }
}
// function url_is_uri
function url_is_uri($sUrl)
{
    if (substr($sUrl, 0, 4) == "file" || substr($sUrl, 0, 3) == "ftp" || substr($sUrl, 0, 4) == "http" || substr($sUrl, 0, 2) == "ww") {
        return true;
    } else {
        return false;
    }
}
/* Check: Changes after last check? */
$sql = "SELECT lastmodified FROM " . $cfg['tab']['content'] . " content\n\t\tLEFT JOIN " . $cfg['tab']['art_lang'] . " art ON (art.idartlang = content.idartlang)\n\t\tWHERE art.online = '1'";
/* Whitelist: Add */
if (!empty($_GET['whitelist'])) {
    $sql = "INSERT INTO " . $cfg['tab']['whitelist'] . " VALUES ('" . Contenido_Security::escapeDB(base64_decode($_GET['whitelist']), $db) . "', '" . time() . "')";
    $db->query($sql);
}
/* Whitelist: Get */
$sql = "SELECT url FROM " . $cfg['tab']['whitelist'] . " WHERE lastview < " . (time() + $iWhitelist_timeout) . "\n\t\tAND lastview > " . (time() - $iWhitelist_timeout);
$db->query($sql);
$aWhitelist = array();
while ($db->next_record()) {
    $aWhitelist[] = $db->f("url");
}
/* Get all links */
// Cache errors
$sCache_errors = $oCache->get($aCacheName['errors'], intval($_GET['mode']));
// Search if cache doesn't exist or we're in live mode
if ($sCache_errors && $_GET['live'] != 1) {
    $aErrors = unserialize($sCache_errors);
function prepareWorkflowItems()
{
    global $action, $lang, $modidcat, $workflowSelectBox, $workflowworkflows, $client, $tpl, $cfg;
    $workflowworkflows = new Workflows();
    if ($action === 'workflow_inherit_down') {
        $tmp = strDeeperCategoriesArray($modidcat);
        $asworkflow = getWorkflowForCat($modidcat);
        $wfa = new WorkflowAllocations();
        foreach ($tmp as $tmp_cat) {
            $idcatlang = getCatLang($tmp_cat, $lang);
            if ($asworkflow == 0) {
                $wfa->select("idcatlang = '{$idcatlang}'");
                if ($item = $wfa->next()) {
                    $wfa->delete($item->get("idallocation"));
                    # delete user sequences for listing in tasklist for each included article
                    $oArticles = new ArticleCollection(array('idcat' => $idcatlang, 'start' => true, 'offline' => true));
                    while ($oArticle = $oArticles->nextArticle()) {
                        setUserSequence($oArticle->getField('idartlang'), -1);
                    }
                }
            } else {
                $wfa->select("idcatlang = '{$idcatlang}'");
                if ($item = $wfa->next()) {
                    $item->setWorkflow($asworkflow);
                    $item->store();
                } else {
                    $wfa->create($asworkflow, $idcatlang);
                    # generate user sequences for listing in tasklist for each included article
                    $oArticles = new ArticleCollection(array('idcat' => $tmp_cat, 'start' => true, 'offline' => true));
                    while ($oArticle = $oArticles->nextArticle()) {
                        setUserSequence($oArticle->getField('idartlang'), $asworkflow);
                    }
                }
            }
        }
    }
    if ($action == "workflow_cat_assign") {
        $seltpl = "wfselect" . $modidcat;
        $wfa = new WorkflowAllocations();
        $idcatlang = getCatLang($modidcat, $lang);
        #associate workflow with category
        if ($GLOBALS[$seltpl] != 0) {
            $wfa->select("idcatlang = '{$idcatlang}'");
            if ($item = $wfa->next()) {
                $item->setWorkflow($GLOBALS[$seltpl]);
                $item->store();
            } else {
                $wfa->create($GLOBALS[$seltpl], $idcatlang);
            }
            # generate user sequences for listing in tasklist for each included article
            $oArticles = new ArticleCollection(array('idcat' => $modidcat, 'start' => true, 'offline' => true));
            while ($oArticle = $oArticles->nextArticle()) {
                setUserSequence($oArticle->getField('idartlang'), $GLOBALS[$seltpl]);
            }
            #unlink workflow with category
        } else {
            $wfa->select("idcatlang = '{$idcatlang}'");
            if ($item = $wfa->next()) {
                $alloc = $item->get("idallocation");
            }
            $wfa->delete($alloc);
            # delete user sequences for listing in tasklist for each included article
            $oArticles = new ArticleCollection(array('idcat' => $modidcat, 'start' => true, 'offline' => true));
            while ($oArticle = $oArticles->nextArticle()) {
                setUserSequence($oArticle->getField('idartlang'), -1);
            }
        }
    }
    $workflowSelectBox = new cHTMLSelectElement("foo");
    $workflowSelectBox->setClass("text_medium");
    $workflowworkflows->select("idclient = '{$client}' AND idlang = '" . Contenido_Security::escapeDB($lang, null) . "'");
    $workflowOption = new cHTMLOptionElement("--- " . i18n("None", "workflow") . " ---", 0);
    $workflowSelectBox->addOptionElement(0, $workflowOption);
    while ($workflow = $workflowworkflows->next()) {
        $workflowOption = new cHTMLOptionElement($workflow->get("name"), $workflow->get("idworkflow"));
        $workflowSelectBox->addOptionElement($workflow->get("idworkflow"), $workflowOption);
    }
    $workflowSelectBox->updateAttributes(array("id" => "wfselect{IDCAT}"));
    $workflowSelectBox->updateAttributes(array("name" => "wfselect{IDCAT}"));
    $tpl->set('s', 'PLUGIN_WORKFLOW', $workflowSelectBox->render() . '<a href="javascript:setWorkflow({IDCAT}, \\\'wfselect{IDCAT}\\\')"><img src="' . $cfg["path"]["images"] . 'submit.gif" class="spaced"></a>');
    $tpl->set('s', 'PLUGIN_WORKFLOW_TRANSLATION', i18n("Inherit workflow down", "workflow"));
}
if (!defined('CON_FRAMEWORK')) {
    die('Illegal call');
}
$plugin_name = "linkchecker";
$iWhitelist_timeout = 2592000;
// 30 days
global $perm;
if (!$perm->have_perm_area_action($plugin_name, $plugin_name)) {
    exit;
}
// Template-definition
$tpl->set('s', 'CONTENIDO_URL', $cfg['path']['contenido_fullhtml']);
$tpl->set('s', 'SID', $sess->id);
/* Whitelist: Delete */
if (!empty($_GET['url_to_delete'])) {
    $sql = "DELETE FROM " . $cfg['tab']['whitelist'] . " WHERE url = '" . Contenido_Security::escapeDB(base64_decode($_GET['url_to_delete']), $db) . "'";
    $db->query($sql);
}
// Get whitelist
$sql = "SELECT url, lastview FROM " . $cfg['tab']['whitelist'] . " WHERE lastview < " . (time() + $iWhitelist_timeout) . "\n\t\tAND lastview > " . (time() - $iWhitelist_timeout) . " ORDER BY lastview DESC";
$db->query($sql);
while ($db->next_record()) {
    $tpl2 = new Template();
    $tpl2->reset();
    $tpl2->set('s', 'CONTENIDO_URL', $cfg['path']['contenido_fullhtml']);
    $tpl2->set('s', 'SID', $sess->id);
    $tpl2->set('s', 'URL', $db->f("url"));
    $tpl2->set('s', 'URL_ENCODE', base64_encode($db->f("url")));
    $tpl2->set('s', 'ENTRY', strftime(i18n('%Y-%m-%d, %I:%M%S %p', $plugin_name), $db->f("lastview")));
    $aWhitelist .= $tpl2->generate($cfg['templates']['linkchecker_whitelist_urls'], 1);
}
 /**
  * Deletes all corresponding informations to this workflow and delegate call to parent
  * @param integer $idWorkflow - id of workflow to delete
  */
 function delete($idWorkflow)
 {
     global $cfg;
     $oDb = new DB_Contenido();
     $aItemIdsDelete = array();
     $sSql = 'SELECT idworkflowitem FROM ' . $cfg["tab"]["workflow_items"] . ' WHERE idworkflow = ' . Contenido_Security::toInteger($idWorkflow) . ';';
     $oDb->query($sSql);
     while ($oDb->next_record()) {
         array_push($aItemIdsDelete, Contenido_Security::escapeDB($oDb->f('idworkflowitem'), $oDb));
     }
     $aUserSequencesDelete = array();
     $sSql = 'SELECT idusersequence FROM ' . $cfg["tab"]["workflow_user_sequences"] . ' WHERE idworkflowitem in (' . implode(',', $aItemIdsDelete) . ');';
     $oDb->query($sSql);
     while ($oDb->next_record()) {
         array_push($aUserSequencesDelete, Contenido_Security::escapeDB($oDb->f('idusersequence'), $oDb));
     }
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_user_sequences"] . ' WHERE idworkflowitem in (' . implode(',', $aItemIdsDelete) . ');';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_actions"] . ' WHERE idworkflowitem in (' . implode(',', $aItemIdsDelete) . ');';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_items"] . ' WHERE idworkflow = ' . Contenido_Security::toInteger($idWorkflow) . ';';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_allocation"] . ' WHERE idworkflow = ' . Contenido_Security::toInteger($idWorkflow) . ';';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_art_allocation"] . ' WHERE idusersequence in (' . implode(',', $aUserSequencesDelete) . ');';
     $oDb->query($sSql);
     parent::delete($idWorkflow);
 }
 function storeItem($treeItem)
 {
     if (!$treeItem['idpica_alloc']) {
         // insert
         $treeItem['idpica_alloc'] = $this->db->nextid($this->table['pica_alloc']);
         $treeItem['sortorder'] = $this->_fetchMaxOrder($treeItem['parentid']) + 1;
         if ($treeItem['parentid'] == 'root') {
             $treeItem['parentid'] = 'NULL';
         }
         $treeItem['name'] = $this->_inFilter($treeItem['name']);
         $sql = "INSERT INTO " . $this->table['pica_alloc'] . "\n\t\t\t\t\t(idpica_alloc, parentid, sortorder)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(" . Contenido_Security::toInteger($treeItem['idpica_alloc']) . ", " . Contenido_Security::toInteger($treeItem['parentid']) . ", " . Contenido_Security::toInteger($treeItem['sortorder']) . ")";
         $this->db->query($sql);
         $sql = "INSERT INTO " . $this->table['pica_lang'] . "\n\t\t\t\t\t(idpica_alloc, idlang, name)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(" . Contenido_Security::toInteger($treeItem['idpica_alloc']) . ", " . Contenido_Security::toInteger($this->lang) . ", '" . Contenido_Security::escapeDB($treeItem['name'], $this->db) . "')";
         $this->db->query($sql);
     } else {
         // update
         $treeItem['name'] = $this->_inFilter($treeItem['name']);
         $sql = "SELECT * FROM " . $this->table['pica_lang'] . " WHERE idpica_alloc = " . Contenido_Security::toInteger($treeItem['idpica_alloc']) . " AND idlang = " . Contenido_Security::toInteger($this->lang);
         $this->db->query($sql);
         if ($this->db->num_rows() > 0) {
             #Update existing translation
             $sql = "UPDATE " . $this->table['pica_lang'] . " SET name = '" . Contenido_Security::escapeDB($treeItem['name'], $this->db) . "' WHERE idpica_alloc = " . Contenido_Security::toInteger($treeItem['idpica_alloc']) . "\n                        AND idlang = " . Contenido_Security::toInteger($this->lang);
         } else {
             #Get current online status for item
             $sql = "SELECT * FROM " . $this->table['pica_lang'] . " WHERE idpica_alloc = " . $treeItem['idpica_alloc'] . " ORDER BY idlang";
             $this->db->query($sql);
             if ($this->db->next_record()) {
                 $online_status = $this->db->f('online');
             } else {
                 $online_status = 0;
             }
             #Insert new translation
             $sql = "INSERT INTO " . $this->table['pica_lang'] . "(idpica_alloc, idlang, name, online) VALUES ( " . Contenido_Security::toInteger($treeItem['idpica_alloc']) . ", " . Contenido_Security::toInteger($this->lang) . ",\n                        '" . Contenido_Security::escapeDB($treeItem['name'], $this->db) . "', " . Contenido_Security::toInteger($online_status) . ")";
         }
         $this->db->query($sql);
     }
     return $treeItem;
 }
 function updateArtAllocation($idworkflowitem, $delete = false)
 {
     global $idworkflow, $cfg;
     $oDb = new DB_Contenido();
     $aUserSequences = array();
     $sSql = 'SELECT idusersequence FROM ' . $cfg["tab"]["workflow_user_sequences"] . ' WHERE idworkflowitem = ' . Contenido_Security::escapeDB($idworkflowitem, $oDb) . ';';
     $oDb->query($sSql);
     while ($oDb->next_record()) {
         array_push($aUserSequences, Contenido_Security::escapeDB($oDb->f('idusersequence'), $oDb));
     }
     $aIdArtLang = array();
     if (count($aUserSequences) > 0) {
         $sSql = 'SELECT idartlang FROM ' . $cfg["tab"]["workflow_art_allocation"] . ' WHERE idusersequence in (' . implode(',', $aUserSequences) . ');';
         $oDb->query($sSql);
         while ($oDb->next_record()) {
             array_push($aIdArtLang, $oDb->f('idartlang'));
         }
         $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_art_allocation"] . ' WHERE idusersequence in (' . implode(',', $aUserSequences) . ');';
         $oDb->query($sSql);
     }
     if ($delete) {
         parent::delete($idworkflowitem);
     }
     foreach ($aIdArtLang as $iIdArtLang) {
         setUserSequence($iIdArtLang, $idworkflow);
     }
 }
 /**
  * Overriden store function to send mails 
  * @param none
  */
 function store()
 {
     global $cfg, $encoding, $lang;
     $sMailhost = getSystemProperty('system', 'mail_host');
     if ($sMailhost == '') {
         $sMailhost = 'localhost';
     }
     //modified : 2008-06-25 - use php mailer class instead of mail()
     $oMail = new PHPMailer();
     $oMail->CharSet = isset($encoding[$lang]) ? $encoding[$lang] : 'UTF-8';
     $oMail->Host = $sMailhost;
     $oMail->IsHTML(0);
     $oMail->WordWrap = 1000;
     $oMail->IsMail();
     if (array_key_exists("idusersequence", $this->modifiedValues)) {
         $usersequence = new WorkflowUserSequence();
         $usersequence->loadByPrimaryKey($this->values["idusersequence"]);
         $email = $usersequence->get("emailnoti");
         $escal = $usersequence->get("escalationnoti");
         if ($email == 1 || $escal == 1) {
             /* Grab the required informations */
             $curEditor = getGroupOrUserName($usersequence->get("iduser"));
             $idartlang = $this->get("idartlang");
             $timeunit = $usersequence->get("timeunit");
             $timelimit = $usersequence->get("timelimit");
             $db = new DB_Contenido();
             $sql = "SELECT author, title, idart FROM " . $cfg["tab"]["art_lang"] . " WHERE idartlang = '" . Contenido_Security::escapeDB($idartlang, $db) . "'";
             $db->query($sql);
             if ($db->next_record()) {
                 $idart = $db->f("idart");
                 $title = $db->f("title");
                 $author = $db->f("author");
             }
             /* Extract category */
             $sql = "SELECT idcat FROM " . $cfg["tab"]["cat_art"] . " WHERE idart = '" . Contenido_Security::escapeDB($idart, $db) . "'";
             $db->query($sql);
             if ($db->next_record()) {
                 $idcat = $db->f("idcat");
             }
             $sql = "SELECT name FROM " . $cfg["tab"]["cat_lang"] . " WHERE idcat = '" . Contenido_Security::escapeDB($idcat, $db) . "'";
             $db->query($sql);
             if ($db->next_record()) {
                 $catname = $db->f("name");
             }
             $starttime = $this->get("starttime");
             $starttime = strtotime(substr_replace(substr(substr($starttime, 0, 2) . chunk_split(substr($starttime, 2, 6), 2, "-") . chunk_split(substr($starttime, 8), 2, ":"), 0, 19), " ", 10, 1));
             switch ($timeunit) {
                 case "Seconds":
                     $maxtime = $starttime + $timelimit;
                     break;
                 case "Minutes":
                     $maxtime = $starttime + $timelimit * 60;
                     break;
                 case "Hours":
                     $maxtime = $starttime + $timelimit * 3600;
                     break;
                 case "Days":
                     $maxtime = $starttime + $timelimit * 86400;
                     break;
                 case "Weeks":
                     $maxtime = $starttime + $timelimit * 604800;
                     break;
                 case "Months":
                     $maxtime = $starttime + $timelimit * 2678400;
                     break;
                 case "Years":
                     $maxtime = $starttime + $timelimit * 31536000;
                     break;
                 default:
                     $maxtime = $starttime + $timelimit;
             }
             if ($email == 1) {
                 $email = i18n("Hello %s,\n\n" . "you are assigned as the next editor for the Article %s.\n\n" . "More informations:\n" . "Article: %s\n" . "Category: %s\n" . "Editor: %s\n" . "Author: %s\n" . "Editable from: %s\n" . "Editable to: %s\n");
                 $filledMail = sprintf($email, $curEditor, $title, $title, $catname, $curEditor, $author, date("Y-m-d H:i:s", $starttime), date("Y-m-d H:i:s", $maxtime));
                 $user = new User();
                 if (isGroup($usersequence->get("iduser"))) {
                     $sql = "select idgroupuser, user_id FROM " . $cfg["tab"]["groupmembers"] . " WHERE\n            \t\t\t\t\t\tgroup_id = '" . Contenido_Security::escapeDB($usersequence->get("iduser"), $db) . "'";
                     $db->query($sql);
                     while ($db->next_record()) {
                         $user->loadUserByUserID($db->f("user_id"));
                         //modified : 2008-06-25 - use php mailer class instead of mail()
                         $oMail->AddAddress($user->getField("email"), "");
                         $oMail->Subject = stripslashes(i18n('Workflow notification', "workflow"));
                         $oMail->Body = $filledMail;
                         $oMail->Send();
                     }
                 } else {
                     $user->loadUserByUserID($usersequence->get("iduser"));
                     //modified : 2008-06-25 - use php mailer class instead of mail()
                     $oMail->AddAddress($user->getField("email"), "");
                     $oMail->Subject = stripslashes(i18n('Workflow notification', "workflow"));
                     $oMail->Body = $filledMail;
                     $oMail->Send();
                 }
             } else {
                 $email = "Hello %s,\n\n" . "you are assigned as the escalator for the Article %s.\n\n" . "More informations:\n" . "Article: %s\n" . "Category: %s\n" . "Editor: %s\n" . "Author: %s\n" . "Editable from: %s\n" . "Editable to: %s\n";
                 $filledMail = sprintf($email, $curEditor, $title, $title, $catname, $curEditor, $author, date("Y-m-d H:i:s", $starttime), date("Y-m-d H:i:s", $maxtime));
                 $user = new User();
                 if (isGroup($usersequence->get("iduser"))) {
                     $sql = "select idgroupuser, user_id FROM " . $cfg["tab"]["groupmembers"] . " WHERE\n            \t\t\t\t\t\tgroup_id = '" . Contenido_Security::escapeDB($usersequence->get("iduser"), $db) . "'";
                     $db->query($sql);
                     while ($db->next_record()) {
                         $user->loadUserByUserID($db->f("user_id"));
                         echo "mail to " . $user->getField("email") . "<br>";
                         //modified : 2008-06-25 - use php mailer class instead of mail()
                         $oMail->AddAddress($user->getField("email"), "");
                         $oMail->Subject = stripslashes(i18n('Workflow escalation', "workflow"));
                         $oMail->Body = $filledMail;
                         $oMail->Send();
                     }
                 } else {
                     $user->loadUserByUserID($usersequence->get("iduser"));
                     echo "mail to " . $user->getField("email") . "<br>";
                     //modified : 2008-06-25 - use php mailer class instead of mail()
                     $oMail->AddAddress($user->getField("email"), "");
                     $oMail->Subject = stripslashes(i18n('Workflow escalation', "workflow"));
                     $oMail->Body = $filledMail;
                     $oMail->Send();
                 }
             }
         }
     }
     return parent::store();
 }
 /**
  * Creates a newsletter job
  * @param $name        string    Specifies the name of the newsletter, the same name may be used more than once
  * @param $idnews    integer Newsletter id
  */
 public function create($iIDNews, $iIDCatArt, $sName = "")
 {
     global $client, $lang, $cfg, $cfgClient, $auth;
     $oNewsletter = new Newsletter();
     if ($oNewsletter->loadByPrimaryKey($iIDNews)) {
         $iIDNews = Contenido_Security::toInteger($iIDNews);
         $iIDCatArt = Contenido_Security::toInteger($iIDCatArt);
         $lang = Contenido_Security::toInteger($lang);
         $client = Contenido_Security::toInteger($client);
         $sName = Contenido_Security::escapeDB($sName, null);
         $oItem = parent::create();
         $oItem->set("idnews", $iIDNews);
         $oItem->set("idclient", $client);
         $oItem->set("idlang", $lang);
         if ($sName == "") {
             $oItem->set("name", $oNewsletter->get("name"));
         } else {
             $oItem->set("name", $sName);
         }
         $oItem->set("type", $oNewsletter->get("type"));
         $oItem->set("use_cronjob", $oNewsletter->get("use_cronjob"));
         $oLang = new cApiLanguage($lang);
         $oItem->set("encoding", $oLang->get("encoding"));
         unset($oLang);
         $oItem->set("idart", $oNewsletter->get("idart"));
         $oItem->set("subject", $oNewsletter->get("subject"));
         // Precompile messages
         #$sPath = $cfgClient[$client]["path"]["htmlpath"]."front_content.php?changelang=".$lang."&idcatart=".$iIDCatArt."&";
         $sPath = Contenido_Url::getInstance()->build(array('idcatart' => $iIDCatArt, 'client' => $client, 'lang' => $lang), true);
         $sPath .= strpos($sPath, '?') === false ? '?' : '&';
         $sMessageText = $oNewsletter->get("message");
         // Preventing double lines in mail, you may wish to disable this function on windows servers
         if (!getSystemProperty("newsletter", "disable-rn-replacement")) {
             $sMessageText = str_replace("\r\n", "\n", $sMessageText);
         }
         $oNewsletter->_replaceTag($sMessageText, false, "unsubscribe", $sPath . "unsubscribe={KEY}");
         $oNewsletter->_replaceTag($sMessageText, false, "change", $sPath . "change={KEY}");
         $oNewsletter->_replaceTag($sMessageText, false, "stop", $sPath . "stop={KEY}");
         $oNewsletter->_replaceTag($sMessageText, false, "goon", $sPath . "goon={KEY}");
         $oItem->set("message_text", $sMessageText);
         if ($oNewsletter->get("type") == "text") {
             // Text newsletter, no html message
             $sMessageHTML = "";
         } else {
             // HTML newsletter, get article content
             $sMessageHTML = $oNewsletter->getHTMLMessage();
             if ($sMessageHTML) {
                 $oNewsletter->_replaceTag($sMessageHTML, true, "name", "MAIL_NAME");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "number", "MAIL_NUMBER");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "date", "MAIL_DATE");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "time", "MAIL_TIME");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "unsubscribe", $sPath . "unsubscribe={KEY}");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "change", $sPath . "change={KEY}");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "stop", $sPath . "stop={KEY}");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "goon", $sPath . "goon={KEY}");
                 // Replace plugin tags by simple MAIL_ tags
                 if (getSystemProperty("newsletter", "newsletter-recipients-plugin") == "true") {
                     if (is_array($cfg['plugins']['recipients'])) {
                         foreach ($cfg['plugins']['recipients'] as $sPlugin) {
                             plugin_include("recipients", $sPlugin . "/" . $sPlugin . ".php");
                             if (function_exists("recipients_" . $sPlugin . "_wantedVariables")) {
                                 $aPluginVars = array();
                                 $aPluginVars = call_user_func("recipients_" . $sPlugin . "_wantedVariables");
                                 foreach ($aPluginVars as $sPluginVar) {
                                     $oNewsletter->_replaceTag($sMessageHTML, true, $sPluginVar, "MAIL_" . strtoupper($sPluginVar));
                                 }
                             }
                         }
                     }
                 }
             } else {
                 // There was a problem getting html message (maybe article deleted)
                 // Cancel job generation
                 return false;
             }
         }
         $oItem->set("message_html", $sMessageHTML);
         $oItem->set("newsfrom", $oNewsletter->get("newsfrom"));
         if ($oNewsletter->get("newsfromname") == "") {
             $oItem->set("newsfromname", $oNewsletter->get("newsfrom"));
         } else {
             $oItem->set("newsfromname", $oNewsletter->get("newsfromname"));
         }
         $oItem->set("newsdate", date("Y-m-d H:i:s"), false);
         //$oNewsletter->get("newsdate"));
         $oItem->set("dispatch", $oNewsletter->get("dispatch"));
         $oItem->set("dispatch_count", $oNewsletter->get("dispatch_count"));
         $oItem->set("dispatch_delay", $oNewsletter->get("dispatch_delay"));
         // Store "send to" info in serialized array (just info)
         $aSendInfo = array();
         $aSendInfo[] = $oNewsletter->get("send_to");
         switch ($oNewsletter->get("send_to")) {
             case "selection":
                 $oGroups = new RecipientGroupCollection();
                 $oGroups->setWhere("idnewsgroup", unserialize($oNewsletter->get("send_ids")), "IN");
                 $oGroups->setOrder("groupname");
                 $oGroups->query();
                 #$oGroups->select("idnewsgroup IN ('" . implode("','", unserialize($oNewsletter->get("send_ids"))) . "')", "", "groupname");
                 while ($oGroup = $oGroups->next()) {
                     $aSendInfo[] = $oGroup->get("groupname");
                 }
                 unset($oGroup);
                 unset($oGroups);
                 break;
             case "single":
                 if (is_numeric($oNewsletter->get("send_ids"))) {
                     $oRcp = new Recipient($oNewsletter->get("send_ids"));
                     if ($oRcp->get("name") == "") {
                         $aSendInfo[] = $oRcp->get("email");
                     } else {
                         $aSendInfo[] = $oRcp->get("name");
                     }
                     $aSendInfo[] = $oRcp->get("email");
                     unset($oRcp);
                 }
                 break;
             default:
         }
         $oItem->set("send_to", serialize($aSendInfo), false);
         $oItem->set("created", date("Y-m-d H:i:s"), false);
         $oItem->set("author", $auth->auth["uid"]);
         $oItem->set("authorname", $auth->auth["uname"]);
         unset($oNewsletter);
         // Not needed anymore
         // Adds log items for all recipients and returns recipient count
         $oLogs = new cNewsletterLogCollection();
         $iRecipientCount = $oLogs->initializeJob($oItem->get($oItem->primaryKey), $iIDNews);
         unset($oLogs);
         $oItem->set("rcpcount", $iRecipientCount);
         $oItem->set("sendcount", 0);
         $oItem->set("status", 1);
         // Waiting for sending; note, that status will be set to 9, if $iRecipientCount = 0 in store() method
         $oItem->store();
         return $oItem;
     } else {
         return false;
     }
 }
function doWorkflowAction($idartlang, $action)
{
    global $cfg, $idcat;
    switch ($action) {
        case "last":
            $artAllocations = new WorkflowArtAllocations();
            $artAllocations->select("idartlang = '{$idartlang}'");
            if ($obj = $artAllocations->next()) {
                $usersequence = new WorkflowUserSequence();
                $usersequence->loadByPrimaryKey($obj->get("idusersequence"));
                $workflowitem = $usersequence->getWorkflowItem();
                $idworkflow = $workflowitem->get("idworkflow");
                $newpos = $workflowitem->get("position") - 1;
                if ($newpos < 1) {
                    $newpos = 1;
                }
                $workflowitems = new WorkflowItems();
                $workflowitems->select("idworkflow = '{$idworkflow}' AND position = '" . Contenido_Security::escapeDB($newpos, NULL) . "'");
                if ($nextObj = $workflowitems->next()) {
                    $userSequences = new WorkflowUserSequences();
                    $idworkflowitem = $nextObj->get("idworkflowitem");
                    $userSequences->select("idworkflowitem = '{$idworkflowitem}'");
                    if ($nextSeqObj = $userSequences->next()) {
                        $obj->set("lastusersequence", $obj->get("idusersequence"));
                        $obj->set("idusersequence", $nextSeqObj->get("idusersequence"));
                        $obj->set("laststatus", "last");
                        $obj->store();
                    }
                }
            }
            break;
        case "next":
            $artAllocations = new WorkflowArtAllocations();
            $artAllocations->select("idartlang = '{$idartlang}'");
            if ($obj = $artAllocations->next()) {
                $usersequence = new WorkflowUserSequence();
                $usersequence->loadByPrimaryKey($obj->get("idusersequence"));
                $workflowitem = $usersequence->getWorkflowItem();
                $idworkflow = $workflowitem->get("idworkflow");
                $newpos = $workflowitem->get("position") + 1;
                $workflowitems = new WorkflowItems();
                $workflowitems->select("idworkflow = '{$idworkflow}' AND position = '" . Contenido_Security::escapeDB($newpos, NULL) . "'");
                if ($nextObj = $workflowitems->next()) {
                    $userSequences = new WorkflowUserSequences();
                    $idworkflowitem = $nextObj->get("idworkflowitem");
                    $userSequences->select("idworkflowitem = '{$idworkflowitem}'");
                    if ($nextSeqObj = $userSequences->next()) {
                        $obj->set("lastusersequence", '10');
                        $obj->set("idusersequence", $nextSeqObj->get("idusersequence"));
                        $obj->set("laststatus", "confirm");
                        $obj->store();
                    }
                } else {
                    $workflowitems->select("idworkflow = '{$idworkflow}' AND position = '" . Contenido_Security::escapeDB($workflowitem->get("position"), NULL) . "'");
                    if ($nextObj = $workflowitems->next()) {
                        $userSequences = new WorkflowUserSequences();
                        $idworkflowitem = $nextObj->get("idworkflowitem");
                        $userSequences->select("idworkflowitem = '{$idworkflowitem}'");
                        if ($nextSeqObj = $userSequences->next()) {
                            $obj->set("lastusersequence", $obj->get("idusersequence"));
                            $obj->set("idusersequence", $nextSeqObj->get("idusersequence"));
                            $obj->set("laststatus", "confirm");
                            $obj->store();
                        }
                    }
                }
            }
            break;
        case "reject":
            $artAllocations = new WorkflowArtAllocations();
            $artAllocations->select("idartlang = '{$idartlang}'");
            if ($obj = $artAllocations->next()) {
                $usersequence = new WorkflowUserSequence();
                $usersequence->loadByPrimaryKey($obj->get("idusersequence"));
                $workflowitem = $usersequence->getWorkflowItem();
                $idworkflow = $workflowitem->get("idworkflow");
                $newpos = 1;
                $workflowitems = new WorkflowItems();
                $workflowitems->select("idworkflow = '{$idworkflow}' AND position = '" . Contenido_Security::escapeDB($newpos, NULL) . "'");
                if ($nextObj = $workflowitems->next()) {
                    $userSequences = new WorkflowUserSequences();
                    $idworkflowitem = $nextObj->get("idworkflowitem");
                    $userSequences->select("idworkflowitem = '{$idworkflowitem}'");
                    if ($nextSeqObj = $userSequences->next()) {
                        $obj->set("lastusersequence", $obj->get("idusersequence"));
                        $obj->set("idusersequence", $nextSeqObj->get("idusersequence"));
                        $obj->set("laststatus", "reject");
                        $obj->store();
                    }
                }
            }
            break;
        case "revise":
            $db = new DB_Contenido();
            $sql = "SELECT idart, idlang FROM " . $cfg["tab"]["art_lang"] . " WHERE idartlang = '" . Contenido_Security::escapeDB($idartlang, $db) . "'";
            $db->query($sql);
            $db->next_record();
            $idart = $db->f("idart");
            $idlang = $db->f("idlang");
            $newidart = conCopyArticle($idart, $idcat, "foo");
            break;
        default:
    }
}
        $wfu->select("idusersequence = '{$value}'");
        if ($obj = $wfu->next()) {
            $userids[$key] = $obj->get("iduser");
        }
    }
}
if (is_array($userids)) {
    foreach ($userids as $key => $value) {
        $isCurrent[$key] = false;
        if ($usershow == $value) {
            $isCurrent[$key] = true;
        }
        if ($users->loadUserByUserID($value) == false) {
            /* Yes, it's a group. Let's try to load the group members! */
            $sql = "SELECT user_id FROM " . $cfg["tab"]["groupmembers"] . "\n                WHERE group_id = '" . $value . "'";
            $db2->query(Contenido_Security::escapeDB($sql, $db2));
            while ($db2->next_record()) {
                if ($db2->f("user_id") == $usershow) {
                    $isCurrent[$key] = true;
                }
            }
        } else {
            if ($value == $usershow) {
                $isCurrent[$key] = true;
            }
        }
        if ($lastusersequence[$key] == $usersequence[$key]) {
            $isCurrent[$key] = false;
        }
    }
}