Example #1
0
function getResourceMapping($dt_code)
{
    $arrdt = explode(".", $dt_code);
    if (count($arrdt) > 2) {
        $dt_code = array_shift($arrdt);
        // $arrdt[0];
        $resource_rt_id = array_shift($arrdt);
        //$arrdt[1]; //resource record type
        $resource_dt_id = $arrdt[0];
    } else {
        return "  wrong resource mapping " . $dt_code;
    }
    $dt_id = getDetailTypeLocalID($dt_code);
    if ($dt_id == null) {
        return " detail type not found " . $dt_code;
    }
    $res_rt_id = getRecTypeLocalID($resource_rt_id);
    if ($res_rt_id == null) {
        return " resource record type not recognized: " . $resource_rt_id;
    }
    $res_dt_id = getDetailTypeLocalID($resource_dt_id);
    if ($res_dt_id == null) {
        return " detail type for resource not recognized " . $resource_dt_id;
    }
    if (count($arrdt) > 1) {
        // next level
        $subres = getResourceMapping(implode(".", $arrdt));
        if (is_array($subres)) {
            $res = array($dt_id, $res_rt_id, $subres);
        } else {
            return $subres;
        }
    } else {
        //pointer detail type and detail type in resource record
        $res = array($dt_id, $res_rt_id, $res_dt_id);
    }
    return $res;
}
/**
 * Returns the content of template file as text with local IDs replaced by concept IDs or viseverse
 *
 * @param mixed $filename - name of template file
 * @param mixed $mode - 0 - to concept code, 1 - to local code
 */
function convertTemplate($template, $mode)
{
    //1. get template content
    //2. find all texts within {}
    //3. find words within this text
    //4. split by .
    //5. find starting with "f"
    //6. get local DT ID - find Concept Code
    //7. replace
    //1. get template content
    if ($template == null || $template == '') {
        return array("error" => "Template is empty");
    }
    //2. find all texts within {} - expressions
    if (!preg_match_all('/\\{([^}]+)\\}/s', $template, $matches)) {
        return $template;
        // nothing to do -- no substitutions
    }
    $not_found_details = array();
    $replacements_exp = array();
    $len = count($matches[1]);
    for ($i = 0; $i < $len; ++$i) {
        $exp = $matches[1][$i];
        if (!trim($exp)) {
            continue;
        }
        //empty{}
        if (substr($exp, 0, 1) == "*" && substr($exp, -1) == "*") {
            continue;
        }
        //this is comment
        //3. find words within this text
        if (!preg_match_all('/(\\$([a-zA-Z_0-9.])+)/', $exp, $matches2)) {
            continue;
        }
        $replacements = array();
        foreach ($matches2[1] as $var) {
            //4. split by "."
            $parts = explode(".", $var);
            $parts2 = array();
            foreach ($parts as $part) {
                //5. find starting with "f"
                if (strpos($part, 'f') === 0) {
                    $prefix = 'f';
                } else {
                    if (strpos($part, '$f') === 0) {
                        $prefix = '$f';
                    } else {
                        $prefix = null;
                    }
                }
                if ($prefix) {
                    //6. get local DT ID - find Concept Code
                    $code = substr($part, strlen($prefix));
                    if (substr($part, -1) == 's') {
                        $suffix = 's';
                        $code = substr($code, 0, strlen($code) - 1);
                    } else {
                        if (endsWith($part, '_originalvalue')) {
                            $suffix = '_originalvalue';
                            $code = substr($code, 0, strlen($code) - strlen($suffix));
                        } else {
                            $suffix = "";
                        }
                    }
                    if ($mode == 0) {
                        $localID = $code;
                        if (strpos($localID, "_") === false) {
                            $conceptCode = getDetailTypeConceptID($localID);
                            $part = $prefix . str_replace("-", "_", $conceptCode) . $suffix;
                        }
                    } else {
                        $conceptCode = $code;
                        if (strpos($conceptCode, "_") !== false) {
                            $conceptCode = str_replace("_", "-", $conceptCode);
                            $localID = getDetailTypeLocalID($conceptCode);
                            if ($localID == null) {
                                //local code not found - it means that this detail is not in this database
                                array_push($not_found_details, $conceptCode);
                                $part = $prefix . "[[" . $conceptCode . "]]" . $suffix;
                            } else {
                                $part = $prefix . $localID . $suffix;
                            }
                        }
                    }
                }
                array_push($parts2, $part);
            }
            $new_var = implode(".", $parts2);
            if ($var != $new_var) {
                $replacements[$var] = $new_var;
            }
        }
        //for vars
        if (count($replacements) > 0) {
            $new_exp = "{" . array_str_replace(array_keys($replacements), array_values($replacements), $exp) . "}";
            if ($matches[0][$i] != $new_exp) {
                $replacements_exp[$matches[0][$i]] = $new_exp;
            }
        }
    }
    //for expressions
    if (count($replacements_exp) > 0) {
        $template = array_str_replace(array_keys($replacements_exp), array_values($replacements_exp), $template);
    }
    if ($mode == 1) {
        return array("template" => $template, "details_not_found" => $not_found_details);
    } else {
        return $template;
    }
}
/**
 * call back function of classEmailProcessor
 *
 * @param mixed $email
 * @return true - then classEmailProcessor may remove this email
 */
function add_email_as_record($email)
{
    global $emails_processed, $emails_failed, $attachment_size_max, $sys_sender, $ownership, $oldFileArray;
    $emails_processed++;
    $description = $email->getBody();
    $rec_id = null;
    /* use UNIX-style lines
    		$description=str_replace("\r\n", "\n", $description);
    		$description=str_replace("\r", "\n", $description);
    		*/
    /*****DEBUG****/
    //error_log(">>>desc:".$description);
    $description = str_replace("\r\n", "", $description);
    $description = str_replace("\r", "", $description);
    $arr = json_decode($description, true);
    /*****DEBUG****/
    //error_log("arr=>>>>".is_array($arr)."  ".count($arr)."  ".print_r($arr, true));
    // assume all id (rtID, dtID, trmID and ontID) are all concept ids (dbID - ID)
    // get rectype concept id and  convert to local id or notes
    // for each detail type: convert to local ids
    //if type is file the save Attachment first
    //if type is enum then convert term ID to local
    // for any id that doesn't convert, save info in scratch in record.
    if (is_array($arr) && count($arr) > 2) {
        //this is from export record from another heurist instance
        $key_file = null;
        //id of field type for assoc files (attachments)
        $arrnew = array();
        //convert all global id to local id
        foreach ($arr as $key => $value) {
            $pos = strpos($key, "type:");
            /*****DEBUG****/
            error_log(">>>> " . (is_numeric($pos) && $pos == 0) . "    " . $pos);
            if (is_numeric($pos) && $pos == 0) {
                //@todo we have to convert the content of fields as well -
                // since it may contain terms and references to other rectypes !!!1
                $typeid = substr($key, 5);
                // temporay code to translate existing reports
                switch ($typeid) {
                    case "2-221":
                    case "68-221":
                        $typeid = DT_BUG_REPORT_FILE;
                        $oldFileArray = true;
                        break;
                    case "2-179":
                    case "68-179":
                        $typeid = DT_BUG_REPORT_NAME;
                        break;
                    case "2-303":
                    case "68-303":
                        $typeid = DT_BUG_REPORT_DESCRIPTION;
                        break;
                    case "2-560":
                    case "68-560":
                        $typeid = DT_BUG_REPORT_STEPS;
                        break;
                    case "2-725":
                    case "68-725":
                        $typeid = DT_BUG_REPORT_STATUS;
                        break;
                }
                $newkey = getDetailTypeLocalID($typeid);
                /*****DEBUG****/
                error_log(">>>> " . $newkey . "  dettype=" . $typeid);
                $value = str_replace("&#13;", "\n", $value);
                if ($newkey) {
                    $arrnew["type:" . $newkey] = $value;
                    if ($newkey == DT_FILE_RESOURCE) {
                        $key_file = "type:" . $newkey;
                    }
                } else {
                    $email->setErrorMessage("Can't find the local id for fieldtype #" . $typeid);
                    $key_file = null;
                    //avoid processing attachments
                    break;
                }
            } else {
                $arrnew[$key] = $value;
            }
        }
        //for
        $rectype = $arr["rectype"];
        switch ($rectype) {
            case "2-216":
            case "68-216":
                $rectype = RT_BUG_REPORT;
        }
        $newrectype = getRecTypeLocalID($rectype);
        if ($newrectype) {
            $arrnew["rectype"] = $newrectype;
            if ($rectype == RT_BUG_REPORT) {
            }
        } else {
            $email->setErrorMessage("Can't find the local id for rectype #" . $_POST["rectype"]);
            $key_file = null;
            //avoid processing attachments
            exit;
        }
        /*****DEBUG****/
        //error_log("KEY FILE ".$key_file);
        //assosiated files
        if ($key_file) {
            $files_arr = $arrnew[$key_file];
            if ($files_arr && count($files_arr) > 0) {
                /*****DEBUG****/
                //error_log(">>>>files_arr=".print_r($files_arr[0], true));
                $arrnew[$key_file] = saveAttachments($files_arr, $email);
                if ($arrnew[$key_file] == 0) {
                    return false;
                }
            } else {
                unset($arrnew[$key_file]);
            }
        }
        /*$bug_descr = $arrnew["type:".DT_BUG_REPORT_DESCRIPTION];
        		if($bug_descr){
        			$bug_descr = str_replace("<br>","\n",$bug_descr);
        			$arrnew["type:".DT_BUG_REPORT_DESCRIPTION] = $bug_descr;
        		}*/
        /*****DEBUG****/
        //error_log(">>>>ARRAY=".print_r($arrnew, true));
        $_POST = $arrnew;
        $statusKey = getDetailTypeLocalID(DT_BUG_REPORT_STATUS);
        /*****DEBUG****/
        //error_log("status key ".print_r($statusKey,true));
        if ($statusKey) {
            $_POST["type:" . $statusKey] = array("Received");
        }
    } else {
        if (defined('RT_NOTE')) {
            // this is from usual email - we will add email rectype
            //error_log(" in emailProccesor as Note");
            // liposuction away those unsightly double, triple and quadruple spaces
            $description = preg_replace('/ +/', ' ', $description);
            // trim() each line
            $description = preg_replace('/^[ \\t\\v\\f]+|[ \\t\\v\\f]+$/m', '', $description);
            $description = preg_replace('/^\\s+|\\s+$/s', '', $description);
            // reduce anything more than two newlines in a row
            $description = preg_replace("/\n\n\n+/s", "\n\n", $description);
            //consider this message as usual email and
            $_POST["save-mode"] = "new";
            $_POST["notes"] = "";
            $_POST["rec_url"] = "";
            /* FOR EMAIL RECORD TYPE  - BUT IAN REQUIRES POST "NOTE" RECORDTYPE
            			$_POST["type:160"] = array($email->getSubject());
            			$_POST["type:166"] = array(date('Y-m-d H:i:s')); //date sent
            			$_POST["type:521"] = array($email->getFrom()); //email owner
            			$_POST["type:650"] = array($email->getFrom()); //email sender
            			$_POST["type:651"] = array("*****@*****.**"); //recipients
            			//$_POST["type:221"] = array(); //attachments
            			$_POST["type:560"] = array($description);
            
            			$_POST["rectype"]="183";  //EMAIL
            			*/
            if (defined('DT_NAME')) {
                $_POST["type:" . DT_NAME] = array($email->getSubject());
            }
            //title
            //$_POST["type:158"] = array("email harvesting"); //creator (recommended)
            if (defined('DT_DATE')) {
                $_POST["type:" . DT_DATE] = array(date('Y-m-d H:i:s'));
            }
            //specific date
            if (defined('DT_SHORT_SUMMARY')) {
                $_POST["type:" . DT_SHORT_SUMMARY] = array($email->getFrom() . " " . $description);
            }
            //notes
            $_POST["rectype"] = RT_NOTE;
            //NOTE
            $_POST["check-similar"] = "1";
            $arr = saveAttachments(null, $email);
            if ($arr == 0) {
                return false;
            } else {
                if (count($arr) > 0) {
                    if (defined('DT_FILE_RESOURCE')) {
                        $_POST['type:' . DT_FILE_RESOURCE] = $arr;
                    }
                    //array_push($_POST['type:221'], $arr);
                    /*****DEBUG****/
                    //error_log(">>>>>>>>>ARRAY>>".print_r($arr, true));
                }
            }
            /*****DEBUG****/
            //error_log(">>>>>>>>>HERE>>>>>>".print_r($_POST['type:221'],true));
        }
    }
    if ($email->getErrorMessage() == null) {
        $_POST["owner"] = get_user_id();
        $sss = $email->getFrom();
        if (is_array($sys_sender)) {
            foreach ($sys_sender as $sys_sender_email) {
                if ($sys_sender_email == $sss || strpos($sss, "<" + $sys_sender_email + ">") >= 0) {
                    $_POST["owner"] = $ownership;
                    break;
                }
            }
        }
        $_POST["visibility"] = 'hidden';
        /*****DEBUG****/
        //error_log(">>>>before insert POST=".print_r($_POST, true));
        $updated = insertRecord($_POST['rectype']);
        //from saveRecordDetails.php
        if ($updated) {
            $rec_id = $_REQUEST["recID"];
            $email->setRecId($rec_id);
        }
        /*****DEBUG****/
        //error_log("updated = $updated  recID = $rec_id ");
    }
    printEmail($email);
    //$rec_id=null;
    if ($rec_id) {
        //($rec_id){
        return true;
    } else {
        $emails_failed++;
        return false;
    }
}