Example #1
0
 public function debit()
 {
     $this->fondos_model->extract(CFG_COSTO_CUENTAPLUS);
     $user_id = $this->session->userdata('user_id');
     $date_end = add_date(date('d-m-Y'), 0, 0, CFG_TIME_CUENTAPLUS);
     $query = $this->db->get_where(TBL_CUENTAPLUS, array('user_id' => $user_id));
     if ($query->num_rows == 0) {
         $sql = "INSERT INTO " . TBL_CUENTAPLUS . "(user_id, date_start, date_end) VALUES(";
         $sql .= $user_id . ",";
         $sql .= "now(),";
         $sql .= "'" . $date_end . "'";
         $sql .= ")";
         if (!$this->db->query($sql)) {
             display_error(__FILE__, "debit", ERR_DB_INSERT, array(TBL_CUENTAPLUS));
         }
     } else {
         $sql = "UPDATE " . TBL_CUENTAPLUS . " SET ";
         $sql .= "date_start = now(),";
         $sql .= "date_end = '" . $date_end . "' ";
         $sql .= "WHERE user_id=" . $user_id;
         if (!$this->db->query($sql)) {
             display_error(__FILE__, "debit", ERR_DB_UPDATE, array(TBL_CUENTAPLUS));
         }
     }
     return true;
 }
function get_edition_data($edition_num, $is_package)
{
    $pages = array();
    $num_pages = get_number_of_pages($edition_num);
    for ($page_num = 1; $page_num <= $num_pages; $page_num++) {
        $pages[] = get_page_id($edition_num, $page_num);
    }
    $cycle = $edition_num % 10 + 1;
    $edition_date = add_date(time(), $edition_num);
    return array('key' => get_edition_id($edition_num), 'date' => $edition_date, 'title' => "Edition Number {$edition_num}", 'modified' => time(), 'packaged' => time(), 'status' => 'published', 'price' => 'FREE', 'thumbnail' => "http://lorempixel.com/600/800/abstract/{$cycle}/Issue-{$edition_num}-{$edition_date}/", 'newsstand_cover_art_icon_source' => "http://dummyimage.com/768x1024/000000/ffffff.png?text=Newstand+Cover+768x1024+Issue+{$edition_num}/", 'summary' => "Summary Number {$edition_num}", 'tombstone' => FALSE, 'url_type' => $is_package ? 'application/pugpigpkg+xml' : 'application/atom+xml', 'url' => "edition/{$edition_num}/" . ($is_package ? 'package.xml' : 'content.xml'), 'newsstand_summary' => "Newsstand sumamry number {$edition_num}", 'page_ids' => $pages);
}
Example #3
0
 public function disting($prop_id)
 {
     $date_end = substr(add_date(date('d-m-Y'), 0, CFG_TIME_DISTPROP), 0, 10);
     $this->fondos_model->extract(CFG_COSTO_PROPDISTING);
     $sql = "INSERT INTO " . TBL_PROPERTIES_DISTING . "(prop_id, date_start, date_end) VALUES";
     foreach ($prop_id as $id) {
         $sql .= "(";
         $sql .= $id . ",";
         $sql .= "now(),";
         $sql .= "'" . $date_end . "'";
         $sql .= "),";
     }
     $sql = substr($sql, 0, -1);
     if (!$this->db->query($sql)) {
         display_error(__FILE__, "disting", ERR_DB_INSERT, array(TBL_PROPERTIES_DISTING));
     }
     return true;
 }
Example #4
0
 /**
  * Display employee attendance
  * 
  * @param string $employeenumber
  * @param date $start
  * @param date $end
  * @return string
  */
 public function attendance($employeenumber, $start = NULL, $end = NULL)
 {
     $sdate = iif(isset($start), date_format(date_create($start), 'm/d/Y'), date('m/d/Y'));
     $edate = iif(isset($end), date_format(date_create($end), 'm/d/Y'), add_date(14, date_create($start), 'm/d/Y'));
     $empty[] = array('No results found.', '', '', '', '');
     $params = array('header' => $this->_attendance, 'class' => array('table table-striped table-bordered dt-table'), 'id' => 'agent-attendance');
     $this->_ci->load->library('MY_table', $params, 'attendance');
     $attendance = $this->_ci->employeelogs->getattendance($employeenumber, $sdate, $edate);
     if (isset($attendance) && !empty($attendance)) {
         for ($i = 0; $i < count($attendance); $i++) {
             if (!is_null($attendance[$i]->TimeIn)) {
                 $tabledata[] = array($attendance[$i]->Day, $attendance[$i]->Schedule, iif($attendance[$i]->Late * 60 >= 1, 'Late', ''), iif(!is_null($attendance[$i]->TimeIn), convert_date($attendance[$i]->TimeIn, 'M d, Y H:i:s'), ''), iif(!is_null($attendance[$i]->Timeout), convert_date($attendance[$i]->Timeout, 'M d, Y H:i:s'), ''));
             }
         }
         if (isset($tabledata) && !empty($tabledata)) {
             return $this->_ci->attendance->generate($tabledata);
         } else {
             return $this->_ci->attendance->generate($empty);
         }
     } else {
         return $this->_ci->attendance->generate($empty);
     }
 }
Example #5
0
function ajouter_emploi($emp, $fil, $conn)
{
    $str = $emp;
    $time = array("1" => 8, "2" => 10, "3" => 13, "4" => 15);
    $php = json_decode($str);
    $json = json_encode($php, JSON_PRETTY_PRINT);
    $dsemestre = "2015-09-14";
    $dsemestre = new DateTime($dsemestre);
    $id_f = $fil;
    $dsemestre = $dsemestre->format("Y-m-d h:i:s");
    $sql_s = 'INSERT INTO `disponibilite` (`id_s`, `id_ens`, `id_mat`, `sdebut`, `sfin`, `hour`, `day`,`id_f`) VALUES ';
    $sql = "INSERT INTO emplois (id_m,id_f,id_e,date_debut,date_fin,id_s) VALUES ";
    foreach ($php as $key => $day) {
        $weekdate = add_date($dsemestre, $key - 1);
        //echo $weekdate .' week date <br>';
        foreach ($day as $keey => $class) {
            // $keey => séance key
            foreach ($class as $clas) {
                $daydate = add_date($weekdate, ($clas->sdebut - 1) * 7);
                //echo $daydate .' day date <br>';
                $sdate = $daydate;
                $sql_s .= '(' . $clas->salle . ',' . $clas->enseignant . ',' . $clas->matiere . ',' . $clas->sdebut . ',' . $clas->sfin . ',' . $keey . ',' . $key . ',' . $fil . '),';
                for ($i = 0; $i < $clas->sfin - $clas->sdebut + 1; $i++) {
                    //echo $sdate .' Semaine '. ($class[0]->sdebut+$i) .' <br>';
                    $sql .= '(' . $clas->matiere . ',' . $id_f . ',' . $clas->enseignant . ',"' . add_hours($sdate, $time[$keey]) . '","' . add_hours($sdate, $time[$keey] + 2) . '",' . $clas->salle . '),';
                    $sdate = add_date($sdate, 7);
                }
            }
        }
    }
    $sql = rtrim($sql, ',');
    $sql_s = rtrim($sql_s, ',');
    $request = $conn->query($sql);
    $request_s = $conn->query($sql_s);
    echo "1";
}
Example #6
0
function get_visits($fields_result, $data, $first_event_id)
{
	$vals_array = array();
	while ($fields = db_fetch_assoc($fields_result)) {
		foreach ($data AS $subject_id => $subject) {
			$dsstdtc = $subject[$first_event_id]['consent_dssstdtc'];
			$rfstdtc = $subject[$first_event_id]['dm_rfstdtc'];
			$usubjid = $subject[$first_event_id]['dm_usubjid'];
			foreach ($subject AS $event_id => $event) {
				$inner_vals = array();
				/**
				 * events with date for this field, and the date is not prior to baseline
				 */
				if ($event[$fields['svstdtc']] != '' && ($event[$fields['svstdtc']] >= $rfstdtc || $event[$fields['svstdtc']] >= $dsstdtc)) {
					/**
					 * set up date objects and interval
					 */
					$rfstdtc_ob = new DateTime($rfstdtc);
					$visit_date_ob = new DateTime($event[$fields['svstdtc']]);
					$interval_ob = $rfstdtc_ob->diff($visit_date_ob, false);
					$interval = $interval_ob->format('%r%a');
					/**
					 * Because TARGET is observational/standard of care, and such things are not defined by the protocol,
					 * we can't call them planned visits, so they're defined as 'expected'
					 */
					$expected_visits = array(28 => 'WEEK 4', 56 => 'WEEK 8', 84 => 'WEEK 12', 168 => 'WEEK24');
					$visit_data = array();
					$visit_week = NULL;
					/**
					 * iterate the expected visits
					 */
					foreach ($expected_visits AS $day => $week) {
						/**
						 * test fit of date to expected visits
						 */
						if (add_date($rfstdtc, $day) == $event[$fields['svstdtc']]) {
							/**
							 * exact fit
							 * the tested date is exactly $day days after $rfstdtc
							 */
							$visit_week = $week;
							$visit_data['visitdy'] = $day;
							/**
							 * if a previous date was fit to this $week, delete it and use this one
							 */
							$have_week_index = array_search_recursive($week, $vals_array[$usubjid]);
							if (false !== $have_week_index) {
								unset($vals_array[$usubjid][$have_week_index]);
							}
						} elseif ((($day - 6) < $interval) && ($interval <= $day + 7) && false === array_search_recursive($week, $vals_array[$usubjid])) {
							/**
							 * loose fit
							 * the tested date is within the $week, and we haven't already assigned this $week to another date
							 */
							$visit_week = $week;
							$visit_data['visitdy'] = $day;
						}
					}
					$visit_data['visit'] = $visit_week;
					$visit_data['svstdy'] = $interval;
					/**
					 * assign attributes to this visit
					 */
					switch ($fields['svstdtc']) {
						case 'consent_dssstdtc':
							/**
							 * handle consent_dssstdtc exception
							 */
							$inner_vals['visit'] = 'CONSENT';
							$inner_vals['svstdtc'] = $event[$fields['svstdtc']];
							$inner_vals['svstdy'] = $visit_data['svstdy'];
							$inner_vals['visitdy'] = $visit_data['svstdy'];
							break;
						case 'dm_rfstdtc':
							/**
							 * handle dm_rfstdtc exception
							 */
							$inner_vals['visit'] = 'DAY 1';
							$inner_vals['svstdtc'] = $event[$fields['svstdtc']];
							$inner_vals['svstdy'] = 1;
							$inner_vals['visitdy'] = 1;
							break;
						default:
							/**
							 * all other fields
							 */
							if (false === array_search_recursive($event[$fields['svstdtc']], $vals_array[$usubjid])) {
								$inner_vals['visit'] = $visit_data['visit'];
								$inner_vals['svstdtc'] = $event[$fields['svstdtc']];
								$inner_vals['svstdy'] = $visit_data['svstdy'];
								$inner_vals['visitdy'] = $visit_data['visitdy'];
								if (!isset($visit_data['visit'])) {
									switch ($fields['svstdtc']) {
										case 'ae_aestdtc':
											$inner_vals['svupdes'] = 'Adverse event';
											break;
										case 'chem_lbdtc':
										case 'chem_im_lbdtc':
										case 'cbc_lbdtc':
										case 'cbc_im_lbdtc':
										case 'hcv_lbdtc':
										case 'hcv_im_lbdtc':
										case 'inr_lbdtc':
										case 'inr_im_lbdtc':
											$inner_vals['svupdes'] = 'Labs collected';
											break;
										default:
											break;
									}
								}
							}
							break;
					}
					$vals_array[$usubjid][] = $inner_vals;
				}
			}
			/**
			 * sort $vals_array[$usubjid] by date
			 */
			$sorter = new FieldSorter('svstdtc');
			usort($vals_array[$usubjid], array($sorter, "cmp"));
		}
	}
	return $vals_array;
}
Example #7
0
                                        Forecast Monthly Consumption
                                    </th>
                                    <th style="text-align:right">
                                        Stock on Hand
                                    </th>
                                    <th style="text-align:right">
                                        Forecast Month of Stock(mos)
                                    </th>

                                </tr>
                                </thead>
                                <tbody>
                                <?php 
    if (!empty($period)) {
        foreach ($period as $p) {
            $pd = add_date($p->forecast_start_date, $p->forecast_period * 12);
            if ($pe <= $pd) {
                echo "<tr>";
                ?>

                                        <td>
                                            <?php 
                echo $p->commodity_name;
                ?>
                                        </td>

                                        <td>
                                            <?php 
                $fmc = ceil($p->forecast_monthly_consumption);
                echo number_format($fmc);
                ?>
include 'connect.php';
include 'facility_level_year.php';
//API login Credentials
$username = "******";
$password = "******";
$html = json_decode($period_json);
function add_date($date, $interval)
{
    $date = $date;
    $date = substr_replace($date, "-", 4, 0);
    //echo($date);
    $newdate = strtotime('+' . $interval . ' month', strtotime($date));
    $newdate = date('Y-m', $newdate);
    return str_replace("-", null, $newdate);
}
$last_month = add_date($html[0], 1);
//print_r($last_month);
//HTTP GET request -Using Curl -Response JSON
$url = "http://test.hiskenya.org/api/analytics?dimension=dx:BnGDrFwyQp9;c0MB4RmVjxk;qnZmg5tNSMy;gVp1KSFI69G;cPlWFYbBacW&dimension=pe:LAST_12_MONTHS&dimension=co&filter=ou:HfVjCurKxh2&displayProperty=NAME";
// $url_orgUnit="http://test.hiskenya.org/api/organisationUnits";
// $data = array("dataSet" => "$dataset", "period" => "$period", "orgUnit" => "$orgUnit");
// $data_string = http_build_query($data);
// $url.="$data_string";
// initailizing curl
$ch = curl_init();
//curl options
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
function add_xml_observations()
{
    global $baseURL, $entryMessage, $objSession, $mailTo, $mailFrom, $loggedUser, $objConstellation, $objObject, $objCatalog, $objLocation, $objInstrument, $objFilter, $objEyepiece, $objLens, $objDatabase, $objObserver, $objObservation;
    if ($_FILES['xml']['tmp_name'] != "") {
        $xmlfile = $_FILES['xml']['tmp_name'];
    } else {
        $entryMessage .= LangXMLError3;
        $_GET['indexAction'] = "add_xml";
        return;
    }
    // Make a DomDocument from the file.
    $dom = new DomDocument();
    $xmlfile = realpath($xmlfile);
    // Load the xml document in the DOMDocument object
    $dom->Load($xmlfile);
    $searchNode = $dom->getElementsByTagName("observations");
    $version = $searchNode->item(0)->getAttribute("version");
    if ($version == "2.0" || $version == "2.1") {
    } else {
        $entryMessage .= LangXMLError1;
        $_GET['indexAction'] = "add_xml";
        return;
    }
    // Use the correct schema definition to check the xml file.
    $xmlschema = str_replace(' ', '/', $searchNode->item(0)->getAttribute("xsi:schemaLocation"));
    $xmlschema = $baseURL . "xml/oal21/oal21.xsd";
    // Validate the XML file against the schema
    if ($dom->schemaValidate($xmlschema)) {
        // The XML file is valid. Let's start reading in the file.
        // Only 2.0 and 2.1 files!
        // Check the observers -> In OpenAstronomyLog 2.0 the deepskylog_id is also added
        $searchNode = $dom->getElementsByTagName("observers");
        $observer = $searchNode->item(0)->getElementsByTagName("observer");
        $observerArray = array();
        $id = "";
        foreach ($observer as $observer) {
            $tmpObserverArray = array();
            // Get the id and the name of the observers in the comast file
            $comastid = $observer->getAttribute("id");
            $name = htmlentities($observer->getElementsByTagName("name")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            $tmpObserverArray['name'] = $name;
            $surname = htmlentities($observer->getElementsByTagName("surname")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            $tmpObserverArray['surname'] = $surname;
            if ($observer->getElementsByTagName("fstOffset")->item(0)) {
                $fstOffset[$comastid] = $observer->getElementsByTagName("fstOffset")->item(0)->nodeValue;
            } else {
                $fstOffset[$comastid] = 0.0;
            }
            $observerid = $observer->getElementsByTagName("account");
            $obsid = "";
            foreach ($observerid as $observerid) {
                if ($observerid->getAttribute("name") == "www.deepskylog.org") {
                    $obsid = $observerid->nodeValue;
                }
            }
            // Get the name of the observer which is logged in in DeepskyLog
            $deepskylog_username = $objObserver->getObserverProperty($_SESSION['deepskylog_id'], 'firstname') . " " . $objObserver->getObserverProperty($_SESSION['deepskylog_id'], 'name');
            if ($obsid != "") {
                if ($obsid == $_SESSION['deepskylog_id']) {
                    $id = $comastid;
                }
            } else {
                if ($deepskylog_username == $name . " " . $surname) {
                    $id = $comastid;
                }
            }
            $observerArray[$comastid] = $tmpObserverArray;
        }
        if ($id == "") {
            $entryMessage .= LangXMLError2 . $deepskylog_username . LangXMLError2a;
            $_GET['indexAction'] = "add_xml";
            return;
        } else {
            $objObserver->setObserverProperty($_SESSION['deepskylog_id'], 'fstOffset', $fstOffset[$id]);
        }
        $targets = $dom->getElementsByTagName("targets");
        $target = $targets->item(0)->getElementsByTagName("target");
        $targetArray = array();
        foreach ($target as $target) {
            $targetInfoArray = array();
            $targetid = $target->getAttribute("id");
            $targetInfoArray["name"] = $target->getElementsByTagName("name")->item(0)->nodeValue;
            $aliases = $target->getElementsByTagName("alias");
            $aliasesArray = array();
            $cnt = 0;
            foreach ($aliases as $aliases) {
                $aliasesArray["alias" . $cnt] = $aliases->nodeValue;
                $cnt = $cnt + 1;
            }
            // Check if the datasource is defined. If this is the case, get it. Otherwise, set to OAL
            if ($target->getElementsByTagName("datasource")->item(0)) {
                $targetInfoArray["datasource"] = $target->getElementsByTagName("datasource")->item(0)->nodeValue;
            } else {
                $targetInfoArray["datasource"] = "OAL";
            }
            $valid = true;
            // Get the type
            if ($target->getAttribute("xsi:type")) {
                $type = $target->getAttribute("xsi:type");
                $next = 1;
                if ($type == "oal:deepSkyAS") {
                    $targetInfoArray["type"] = "ASTER";
                } else {
                    if ($type == "oal:deepSkyDS") {
                        $targetInfoArray["type"] = "AA2STAR";
                    } else {
                        if ($type == "oal:deepSkySC" || $type == "oal:deepSkyOC") {
                            $targetInfoArray["type"] = "OPNCL";
                        } else {
                            if ($type == "oal:deepSkyGC") {
                                $targetInfoArray["type"] = "GLOCL";
                            } else {
                                if ($type == "oal:deepSkyGX") {
                                    $targetInfoArray["type"] = "GALXY";
                                } else {
                                    if ($type == "oal:deepSkyCG") {
                                        $targetInfoArray["type"] = "GALCL";
                                    } else {
                                        if ($type == "oal:deepSkyGN") {
                                            $targetInfoArray["type"] = "BRTNB";
                                        } else {
                                            if ($type == "oal:deepSkyGN") {
                                                $targetInfoArray["type"] = "BRTNB";
                                            } else {
                                                if ($type == "oal:deepSkyPN") {
                                                    $targetInfoArray["type"] = "PLNNB";
                                                } else {
                                                    if ($type == "oal:deepSkyQS") {
                                                        $targetInfoArray["type"] = "QUASR";
                                                    } else {
                                                        if ($type == "oal:deepSkyDN") {
                                                            $targetInfoArray["type"] = "DRKNB";
                                                        } else {
                                                            if ($type == "oal:deepSkyNA") {
                                                                $targetInfoArray["type"] = "NONEX";
                                                            } else {
                                                                $next = 0;
                                                                $valid = false;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                $valid = false;
            }
            $targetInfoArray["known"] = $next;
            if ($valid) {
                // Get Ra and convert it to degrees
                if (!$target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)) {
                    $valid = false;
                } else {
                    $unit = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->getAttribute("unit");
                    if ($unit == "deg") {
                        $ra = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue;
                    } else {
                        if ($unit == "rad") {
                            $ra = Rad2Deg($target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue);
                        } else {
                            if ($unit == "arcmin") {
                                $ra = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue / 60.0;
                            } else {
                                if ($unit == "arcsec") {
                                    $ra = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue / 3600.0;
                                }
                            }
                        }
                    }
                    $targetInfoArray["ra"] = $ra / 15.0;
                }
                if (!$target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)) {
                    $valid = false;
                } else {
                    // Get Dec and convert it to degrees
                    $unit = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->getAttribute("unit");
                    if ($unit == "deg") {
                        $dec = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue;
                    } else {
                        if ($unit == "rad") {
                            $dec = Rad2Deg($target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue);
                        } else {
                            if ($unit == "arcmin") {
                                $dec = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue / 60.0;
                            } else {
                                if ($unit == "arcsec") {
                                    $dec = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue / 3600.0;
                                }
                            }
                        }
                    }
                    $targetInfoArray["dec"] = $dec;
                }
                $targetInfoArray['constellation'] = $objConstellation->getConstellationFromCoordinates($targetInfoArray["ra"], $targetInfoArray["dec"]);
                // Check if the magnitude is defined. If this is the case, get it. Otherwise, set to 99.9
                if ($target->getElementsByTagName("visMag")->item(0)) {
                    $targetInfoArray["mag"] = $target->getElementsByTagName("visMag")->item(0)->nodeValue;
                } else {
                    $targetInfoArray["mag"] = "99.9";
                }
                // Check if the surface brightness is defined. If this is the case, get it. Otherwise, set to 99.9
                if ($target->getElementsByTagName("surfBr")->item(0)) {
                    // Get surface brightness and convert it
                    $unit = $target->getElementsByTagName("surfBr")->item(0)->getAttribute("unit");
                    if ($unit == "mags-per-squarearcmin") {
                        $subr = $target->getElementsByTagName("surfBr")->item(0)->nodeValue;
                    } else {
                        $subr = $target->getElementsByTagName("surfBr")->item(0)->nodeValue - 8.890000000000001;
                    }
                    $targetInfoArray["subr"] = $subr;
                } else {
                    $targetInfoArray["subr"] = "99.9";
                }
                // Check if the position angle is defined. If this is the case, get it. Otherwise, set to 999
                if ($target->getElementsByTagName("pa")->item(0)) {
                    $targetInfoArray["pa"] = $target->getElementsByTagName("pa")->item(0)->nodeValue;
                } else {
                    $targetInfoArray["pa"] = "999";
                }
                // Check if the largeDiameter is defined. If this is the case, get it. Otherwise, set to 0
                if ($target->getElementsByTagName("largeDiameter")->item(0)) {
                    // Get Dec and convert it to arcseconds
                    $unit = $target->getElementsByTagName("largeDiameter")->item(0)->getAttribute("unit");
                    if ($unit == "deg") {
                        $diam1 = $target->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 3600.0;
                    } else {
                        if ($unit == "rad") {
                            $diam1 = Rad2Deg($target->getElementsByTagName("largeDiameter")->item(0)->nodeValue) * 3600.0;
                        } else {
                            if ($unit == "arcmin") {
                                $diam1 = $target->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 60.0;
                            } else {
                                if ($unit == "arcsec") {
                                    $diam1 = $target->getElementsByTagName("largeDiameter")->item(0)->nodeValue;
                                }
                            }
                        }
                    }
                    $targetInfoArray["diam1"] = $diam1;
                } else {
                    $targetInfoArray["diam1"] = "0";
                }
                // Check if the smallDiameter is defined. If this is the case, get it. Otherwise, set to 0
                if ($target->getElementsByTagName("smallDiameter")->item(0)) {
                    // Get Dec and convert it to arcseconds
                    $unit = $target->getElementsByTagName("smallDiameter")->item(0)->getAttribute("unit");
                    if ($unit == "deg") {
                        $diam2 = $target->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 3600.0;
                    } else {
                        if ($unit == "rad") {
                            $diam2 = Rad2Deg($target->getElementsByTagName("smallDiameter")->item(0)->nodeValue) * 3600.0;
                        } else {
                            if ($unit == "arcmin") {
                                $diam2 = $target->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 60.0;
                            } else {
                                if ($unit == "arcsec") {
                                    $diam2 = $target->getElementsByTagName("smallDiameter")->item(0)->nodeValue;
                                }
                            }
                        }
                    }
                    $targetInfoArray["diam2"] = $diam2;
                } else {
                    $targetInfoArray["diam2"] = "0";
                }
            }
            $targetInfoArray["valid"] = $valid;
            $targetInfoArray["aliases"] = $aliasesArray;
            $targetArray[$targetid] = $targetInfoArray;
        }
        // SITES
        $sites = $dom->getElementsByTagName("sites");
        $site = $sites->item(0)->getElementsByTagName("site");
        $siteArray = array();
        foreach ($site as $site) {
            $siteInfoArray = array();
            $siteid = $site->getAttribute("id");
            $siteInfoArray["name"] = htmlentities($site->getElementsByTagName("name")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            // Get longitude and convert it to degrees
            $unit = $site->getElementsByTagName("longitude")->item(0)->getAttribute("unit");
            if ($unit == "deg") {
                $longitude = $site->getElementsByTagName("longitude")->item(0)->nodeValue;
            } else {
                if ($unit == "rad") {
                    $longitude = Rad2Deg($site->getElementsByTagName("longitude")->item(0)->nodeValue);
                } else {
                    if ($unit == "arcmin") {
                        $longitude = $site->getElementsByTagName("longitude")->item(0)->nodeValue / 60.0;
                    } else {
                        if ($unit == "arcsec") {
                            $longitude = $site->getElementsByTagName("longitude")->item(0)->nodeValue / 3600.0;
                        }
                    }
                }
            }
            $siteInfoArray["longitude"] = $longitude;
            // Get latitude and convert it to degrees
            $unit = $site->getElementsByTagName("latitude")->item(0)->getAttribute("unit");
            if ($unit == "deg") {
                $latitude = $site->getElementsByTagName("latitude")->item(0)->nodeValue;
            } else {
                if ($unit == "rad") {
                    $latitude = Rad2Deg($site->getElementsByTagName("latitude")->item(0)->nodeValue);
                } else {
                    if ($unit == "arcmin") {
                        $latitude = $site->getElementsByTagName("latitude")->item(0)->nodeValue / 60.0;
                    } else {
                        if ($unit == "arcsec") {
                            $latitude = $site->getElementsByTagName("latitude")->item(0)->nodeValue / 3600.0;
                        }
                    }
                }
            }
            $siteInfoArray["latitude"] = $latitude;
            // Get the timezone
            $xmlfile2 = "http://api.geonames.org/timezone?lat=" . $latitude . "&lng=" . $longitude . "&username=deepskylog";
            $timezones = simplexml_load_file($xmlfile2);
            $siteInfoArray["timezone"] = $timezones->timezone->timezoneId;
            $siteInfoArray["country"] = $timezones->timezone->countryName;
            $siteInfoArray["country"] = $timezones->timezone->countryName;
            if ($siteInfoArray["timezone"] == "") {
                $siteInfoArray["timezone"] = "UTC";
            }
            $siteArray[$siteid] = $siteInfoArray;
        }
        // SESSIONS
        $sessions = $dom->getElementsByTagName("sessions");
        $session = $sessions->item(0)->getElementsByTagName("session");
        $sessionArray = array();
        foreach ($session as $session) {
            $sessionInfoArray = array();
            $sessionid = $session->getAttribute("id");
            $sessionLang = $session->getAttribute("lang");
            $sessionInfoArray['lang'] = $sessionLang;
            // Get the begindate and convert it to the DeepskyLog format
            $tmpBegin = $session->getElementsByTagName("begin")->item(0)->nodeValue;
            $beginDate = substr($tmpBegin, 0, 10);
            $beginTime = substr($tmpBegin, 11, 8);
            $timeDiff = substr($tmpBegin, 19, 6);
            $timeDiffHours = substr($timeDiff, 0, 3);
            $timeDiffMinutes = substr($timeDiff, 4, 2);
            if ($timeDiffHours > 0) {
                $beginDate2 = add_date($beginDate . " " . $beginTime, -$timeDiffHours, -$timeDiffMinutes);
            } else {
                $beginDate2 = add_date($beginDate . " " . $beginTime, -$timeDiffHours, $timeDiffMinutes);
            }
            $sessionInfoArray["begindate"] = $beginDate2;
            $tmpEnd = $session->getElementsByTagName("end")->item(0)->nodeValue;
            $endDate = substr($tmpEnd, 0, 10);
            $endTime = substr($tmpEnd, 11, 8);
            $timeDiff = substr($tmpEnd, 19, 6);
            $timeDiffHours = substr($timeDiff, 0, 3);
            $timeDiffMinutes = substr($timeDiff, 4, 2);
            if ($timeDiffHours > 0) {
                $endDate2 = add_date($endDate . " " . $endTime, -$timeDiffHours, -$timeDiffMinutes);
            } else {
                $endDate2 = add_date($endDate . " " . $endTime, -$timeDiffHours, $timeDiffMinutes);
            }
            $sessionInfoArray["enddate"] = $endDate2;
            // Get siteid -> Maybe we still have to add the site later
            $siteid = $session->getElementsByTagName("site")->item(0)->nodeValue;
            $sessionInfoArray["site"] = $siteid;
            // Get all coObservers
            if ($session->getElementsByTagName("coObserver")->item(0)) {
                $coObs = $session->getElementsByTagName("coObserver");
                $coObsArray = array();
                foreach ($coObs as $coObs) {
                    $coObsArray[] = $coObs->nodeValue;
                }
                $sessionInfoArray["coObservers"] = $coObsArray;
            }
            // Get weather
            if ($session->getElementsByTagName("weather")->item(0)) {
                $sessionInfoArray["weather"] = htmlentities($session->getElementsByTagName("weather")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            }
            // Get the equipment
            if ($session->getElementsByTagName("equipment")->item(0)) {
                $sessionInfoArray["equipment"] = htmlentities($session->getElementsByTagName("equipment")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            }
            // Get the comments
            if ($session->getElementsByTagName("comments")->item(0)) {
                $sessionInfoArray["comments"] = htmlentities($session->getElementsByTagName("comments")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            }
            // We don't use the image tag of the session element to import, only to export
            $sessionArray[$sessionid] = $sessionInfoArray;
        }
        // SCOPES
        $scopes = $dom->getElementsByTagName("scopes");
        $scope = $scopes->item(0)->getElementsByTagName("scope");
        $scopeArray = array();
        foreach ($scope as $scope) {
            $scopeInfoArray = array();
            $scopeid = $scope->getAttribute("id");
            $scopeInfoArray["name"] = htmlentities($scope->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            $scopeInfoArray["diameter"] = $scope->getElementsByTagName("aperture")->item(0)->nodeValue;
            $tp = $scope->getAttribute("xsi:type");
            if ($tp == "oal:scopeType") {
                if ($scope->getElementsByTagName("focalLength")->item(0)) {
                    $type = $scope->getElementsByTagName("type")->item(0)->nodeValue;
                    if ($type == "A" || $type == "Naked Eye") {
                        $typeToSave = InstrumentNakedEye;
                    } else {
                        if ($type == "B" || $type == "Binoculars") {
                            $typeToSave = InstrumentBinoculars;
                        } else {
                            if ($type == "R" || $type == "Refractor") {
                                $typeToSave = InstrumentRefractor;
                            } else {
                                if ($type == "N" || $type == "Newton") {
                                    $typeToSave = InstrumentReflector;
                                } else {
                                    if ($type == "C" || $type == "Cassegrain") {
                                        $typeToSave = InstrumentCassegrain;
                                    } else {
                                        if ($type == "K" || $type == "Kutter") {
                                            $typeToSave = InstrumentKutter;
                                        } else {
                                            if ($type == "M" || $type == "Maksutov") {
                                                $typeToSave = InstrumentMaksutov;
                                            } else {
                                                if ($type == "S" || $type == "Schmidt-Cassegrain") {
                                                    $typeToSave = InstrumentSchmidtCassegrain;
                                                } else {
                                                    $typeToSave = InstrumentOther;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    $typeToSave = InstrumentOther;
                }
            } else {
                $typeToSave = InstrumentBinoculars;
            }
            $scopeInfoArray["type"] = $typeToSave;
            // Check if the focal length exists. If so, we are using a telescope, else a binocular
            if ($scope->getElementsByTagName("focalLength")->item(0)) {
                $fl = $scope->getElementsByTagName("focalLength")->item(0)->nodeValue;
                $scopeInfoArray["fd"] = $fl / $scopeInfoArray["diameter"];
                $scopeInfoArray["fixedMagnification"] = 0;
            } else {
                $scopeInfoArray["fd"] = 0;
                $scopeInfoArray["fixedMagnification"] = $scope->getElementsByTagName("magnification")->item(0)->nodeValue;
            }
            $scopeArray[$scopeid] = $scopeInfoArray;
        }
        // EYEPIECES
        $eyepieces = $dom->getElementsByTagName("eyepieces");
        $eyepiece = $eyepieces->item(0)->getElementsByTagName("eyepiece");
        $eyepieceArray = array();
        foreach ($eyepiece as $eyepiece) {
            $eyepieceInfoArray = array();
            $eyepieceid = $eyepiece->getAttribute("id");
            $eyepieceInfoArray["name"] = htmlentities($eyepiece->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            $eyepieceInfoArray["focalLength"] = $eyepiece->getElementsByTagName("focalLength")->item(0)->nodeValue;
            // Check if the maximal focal length exists. If so, we are using a zoom eyepiece
            if ($eyepiece->getElementsByTagName("maxFocalLength")->item(0)) {
                $eyepieceInfoArray["maxFocalLength"] = $eyepiece->getElementsByTagName("maxFocalLength")->item(0)->nodeValue;
            } else {
                $eyepieceInfoArray["maxFocalLength"] = -1;
            }
            // Get focal length and convert it to degrees
            if (!$target->getElementsByTagName("apparentFOV")->item(0)) {
                $fov = 60.0;
            } else {
                $unit = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->getAttribute("unit");
                if ($unit == "deg") {
                    $fov = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue;
                } else {
                    if ($unit == "rad") {
                        $fov = Rad2Deg($eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue);
                    } else {
                        if ($unit == "arcmin") {
                            $fov = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue / 60.0;
                        } else {
                            if ($unit == "arcsec") {
                                $fov = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue / 3600.0;
                            }
                        }
                    }
                }
            }
            $eyepieceInfoArray["apparentFOV"] = $fov;
            $eyepieceArray[$eyepieceid] = $eyepieceInfoArray;
        }
        // LENSES
        $lenses = $dom->getElementsByTagName("lenses");
        $lens = $lenses->item(0)->getElementsByTagName("lens");
        $lensArray = array();
        foreach ($lens as $lens) {
            $lensInfoArray = array();
            $lensid = $lens->getAttribute("id");
            $lensInfoArray["name"] = htmlentities($lens->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            $lensInfoArray["factor"] = $lens->getElementsByTagName("factor")->item(0)->nodeValue;
            $lensArray[$lensid] = $lensInfoArray;
        }
        // FILTERS
        $filters = $dom->getElementsByTagName("filters");
        $filter = $filters->item(0)->getElementsByTagName("filter");
        $filterArray = array();
        foreach ($filter as $filter) {
            $filterInfoArray = array();
            $filterid = $filter->getAttribute("id");
            $filterInfoArray["name"] = htmlentities($filter->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0);
            $type = $filter->getElementsByTagName("type")->item(0)->nodeValue;
            if ($type == "other") {
                $typeInfo = 0;
            } else {
                if ($type == "broad band") {
                    $typeInfo = 1;
                } else {
                    if ($type == "narrow band") {
                        $typeInfo = 2;
                    } else {
                        if ($type == "O-III") {
                            $typeInfo = 3;
                        } else {
                            if ($type == "H-beta") {
                                $typeInfo = 4;
                            } else {
                                if ($type == "H-alpha") {
                                    $typeInfo = 5;
                                } else {
                                    if ($type == "color") {
                                        $typeInfo = 6;
                                    } else {
                                        if ($type == "neutral") {
                                            $typeInfo = 7;
                                        } else {
                                            if ($type == "corrective") {
                                                $typeInfo = 8;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $filterInfoArray["type"] = $typeInfo;
            if ($filter->getElementsByTagName("wratten")->item(0)) {
                $filterInfoArray["wratten"] = $filter->getElementsByTagName("wratten")->item(0)->nodeValue;
            } else {
                $filterInfoArray["wratten"] = "";
            }
            if ($filter->getElementsByTagName("schott")->item(0)) {
                $filterInfoArray["schott"] = $filter->getElementsByTagName("schott")->item(0)->nodeValue;
            } else {
                $filterInfoArray["schott"] = "";
            }
            if ($filter->getElementsByTagName("color")->item(0)) {
                $color = $filter->getElementsByTagName("color")->item(0)->nodeValue;
                if ($color == "light red") {
                    $filterInfoArray["color"] = 1;
                } else {
                    if ($color == "red") {
                        $filterInfoArray["color"] = 2;
                    } else {
                        if ($color == "deep red") {
                            $filterInfoArray["color"] = 3;
                        } else {
                            if ($color == "orange") {
                                $filterInfoArray["color"] = 4;
                            } else {
                                if ($color == "light yellow") {
                                    $filterInfoArray["color"] = 5;
                                } else {
                                    if ($color == "deep yellow") {
                                        $filterInfoArray["color"] = 6;
                                    } else {
                                        if ($color == "yellow") {
                                            $filterInfoArray["color"] = 7;
                                        } else {
                                            if ($color == "yellow-green") {
                                                $filterInfoArray["color"] = 8;
                                            } else {
                                                if ($color == "light green") {
                                                    $filterInfoArray["color"] = 9;
                                                } else {
                                                    if ($color == "green") {
                                                        $filterInfoArray["color"] = 10;
                                                    } else {
                                                        if ($color == "medium blue") {
                                                            $filterInfoArray["color"] = 11;
                                                        } else {
                                                            if ($color == "pale blue") {
                                                                $filterInfoArray["color"] = 12;
                                                            } else {
                                                                if ($color == "blue") {
                                                                    $filterInfoArray["color"] = 13;
                                                                } else {
                                                                    if ($color == "deep blue") {
                                                                        $filterInfoArray["color"] = 14;
                                                                    } else {
                                                                        if ($color == "voilet") {
                                                                            $filterInfoArray["color"] = 15;
                                                                        } else {
                                                                            $filterInfoArray["color"] = 0;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                $filterInfoArray["color"] = 0;
            }
            $filterArray[$filterid] = $filterInfoArray;
        }
        // Add the sessions
        while (list($key, $value) = each($sessionArray)) {
            if (count($objDatabase->selectRecordArray("SELECT * from sessions where begindate = \"" . $sessionArray[$key]['begindate'] . "\" and enddate = \"" . $sessionArray[$key]['enddate'] . "\";")) == 0) {
                $sessionid = 0;
            } else {
                $sessionid = $objDatabase->selectRecordArray("SELECT * from sessions where begindate = \"" . $sessionArray[$key]['begindate'] . "\" and enddate = \"" . $sessionArray[$key]['enddate'] . "\";");
                $sessionid = $sessionid['id'];
            }
            $beginday = substr($sessionArray[$key]['begindate'], 8, 2);
            $beginmonth = substr($sessionArray[$key]['begindate'], 5, 2);
            $beginyear = substr($sessionArray[$key]['begindate'], 0, 4);
            $beginhours = substr($sessionArray[$key]['begindate'], 11, 2);
            $beginminutes = substr($sessionArray[$key]['begindate'], 14, 2);
            $endday = substr($sessionArray[$key]['enddate'], 8, 2);
            $endmonth = substr($sessionArray[$key]['enddate'], 5, 2);
            $endyear = substr($sessionArray[$key]['enddate'], 0, 4);
            $endhours = substr($sessionArray[$key]['enddate'], 11, 2);
            $endminutes = substr($sessionArray[$key]['enddate'], 14, 2);
            $location = $sessionArray[$key]['site'];
            // Check if the site already exists in DeepskyLog
            $site = $siteArray[$sessionArray[$key]['site']]["name"];
            $sa = $siteArray[$sessionArray[$key]['site']];
            if (count($objDatabase->selectRecordArray("SELECT * from locations where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";")) > 0) {
                // Update the coordinates
                $run = $objDatabase->selectRecordset("SELECT id FROM locations WHERE observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";");
                $get = $run->fetch(PDO::FETCH_OBJ);
                $locId = $get->id;
                $objLocation->setLocationProperty($locId, "longitude", $sa["longitude"]);
                $objLocation->setLocationProperty($locId, "latitude", $sa["latitude"]);
                $objLocation->setLocationProperty($locId, "timezone", $sa["timezone"]);
                $objLocation->setLocationProperty($locId, "country", $sa["country"]);
            } else {
                // Add the new site!
                $locId = $objLocation->addLocation($sa["name"], $sa["longitude"], $sa["latitude"], "", $sa["country"], $sa["timezone"], 0);
                $objDatabase->execSQL("update locations set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $locId . "\";");
                $objDatabase->execSQL("update locations set checked = \"0\" where id = \"" . $locId . "\";");
            }
            $location = $locId;
            if (array_key_exists('weather', $sessionArray[$key])) {
                $weather = $sessionArray[$key]['weather'];
            } else {
                $weather = "";
            }
            if (array_key_exists('equipment', $sessionArray[$key])) {
                $equipment = $sessionArray[$key]['equipment'];
            } else {
                $equipment = "";
            }
            if (array_key_exists('comments', $sessionArray[$key])) {
                $comments = $sessionArray[$key]['comments'];
            } else {
                $comments = "";
            }
            // $language
            $language = $sessionArray[$key]['lang'];
            // If the observers exist, add them to the session
            $observers = array();
            if (array_key_exists('coObservers', $sessionArray[$key])) {
                for ($cnt = 0; $cnt < count($sessionArray[$key]['coObservers']); $cnt++) {
                    $name = $observerArray[$sessionArray[$key]['coObservers'][$cnt]]['surname'];
                    $firstname = $observerArray[$sessionArray[$key]['coObservers'][$cnt]]['name'];
                    $foundUser = $objDatabase->selectRecordArray("SELECT * from observers where name = \"" . $name . "\" and firstname = \"" . $firstname . "\"");
                    if (count($foundUser) > 0) {
                        $observers[] = $foundUser['id'];
                    }
                }
            }
            if ($sessionid == 0) {
                // Add new session
                $objSession->addSession("", $beginday, $beginmonth, $beginyear, $beginhours, $beginminutes, $endday, $endmonth, $endyear, $endhours, $endminutes, $location, $weather, $equipment, $comments, $language, $observers, 0);
            } else {
                // Adapt sessions
                $objSession->updateSession($sessionid, "", $sessionArray[$key]['begindate'], $sessionArray[$key]['enddate'], $location, $weather, $equipment, $comments, $language);
            }
        }
        // Check if there are observations for the given observer
        $searchNode = $dom->getElementsByTagName("observations");
        $observation = $searchNode->item(0)->getElementsByTagName("observation");
        foreach ($observation as $observation) {
            $siteValid = true;
            if ($observation->getElementsByTagName("site")->item(0)) {
                $observerid = $observation->getElementsByTagName("observer")->item(0)->nodeValue;
                if ($observerid == $id) {
                    // Check if the site already exists in DeepskyLog
                    $site = $siteArray[$observation->getElementsByTagName("site")->item(0)->nodeValue]["name"];
                    $sa = $siteArray[$observation->getElementsByTagName("site")->item(0)->nodeValue];
                    if (count($objDatabase->selectRecordArray("SELECT * from locations where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";")) > 0) {
                        // Update the coordinates
                        $run = $objDatabase->selectRecordset("SELECT id FROM locations WHERE observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";");
                        $get = $run->fetch(PDO::FETCH_OBJ);
                        $locId = $get->id;
                        $objLocation->setLocationProperty($locId, "longitude", $sa["longitude"]);
                        $objLocation->setLocationProperty($locId, "latitude", $sa["latitude"]);
                        $objLocation->setLocationProperty($locId, "timezone", $sa["timezone"]);
                    } else {
                        // Add the new site!
                        $locId = $objLocation->addLocation($sa["name"], $sa["longitude"], $sa["latitude"], "", $sa["country"], $sa["timezone"]);
                        $objDatabase->execSQL("update locations set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $locId . "\";");
                    }
                } else {
                    $siteValid = false;
                }
                $instId = -1;
                // Check if the instrument already exists in DeepskyLog
                if ($observation->getElementsByTagName("scope")->item(0)) {
                    $instrument = $scopeArray[$observation->getElementsByTagName("scope")->item(0)->nodeValue]["name"];
                    $ia = $scopeArray[$observation->getElementsByTagName("scope")->item(0)->nodeValue];
                    if (count($objDatabase->selectRecordArray("SELECT * from instruments where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $instrument . "\";")) > 0) {
                        // Update
                        $instId = $objInstrument->getInstrumentId($ia["name"], $_SESSION['deepskylog_id']);
                        $objInstrument->setInstrumentProperty($instId, "name", $ia["name"]);
                        $objInstrument->setInstrumentProperty($instId, "diameter", $ia["diameter"]);
                        $objInstrument->setInstrumentProperty($instId, "fd", $ia["fd"]);
                        $objInstrument->setInstrumentProperty($instId, "type", $ia["type"]);
                        $objInstrument->setInstrumentProperty($instId, "fixedMagnification", $ia["fixedMagnification"]);
                    } else {
                        // Add the new instrument!
                        $instId = $objInstrument->addInstrument($ia["name"], $ia["diameter"], $ia["fd"], $ia["type"], $ia["fixedMagnification"], $_SESSION['deepskylog_id']);
                    }
                } else {
                    // No scope defined, so this is a naked eye observation
                    $instrument = "Naked eye";
                    if (count($objDatabase->selectRecordArray("SELECT * from instruments where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $instrument . "\";")) > 0) {
                        $instId = $objInstrument->getInstrumentId($instrument, $_SESSION['deepskylog_id']);
                    } else {
                        // Add the new instrument!
                        $instId = $objInstrument->addInstrument($instrument, 7, 1, 0, 1, $_SESSION['deepskylog_id']);
                    }
                }
                // Filter is not mandatory
                if ($observation->getElementsByTagName("filter")->item(0)) {
                    // Check if the filter already exists in DeepskyLog
                    $filter = $filterArray[$observation->getElementsByTagName("filter")->item(0)->nodeValue]["name"];
                    $fa = $filterArray[$observation->getElementsByTagName("filter")->item(0)->nodeValue];
                    if (count($objDatabase->selectRecordArray("SELECT * from filters where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $filter . "\";")) > 0) {
                        // Update the filter
                        $filtId = $objFilter->getFilterId($fa["name"], $_SESSION['deepskylog_id']);
                        $objFilter->setFilterProperty($filtId, "name", $fa["name"]);
                        $objFilter->setFilterProperty($filtId, "type", $fa["type"]);
                        $objFilter->setFilterProperty($filtId, "color", $fa["color"]);
                        $objFilter->setFilterProperty($filtId, "wratten", $fa["wratten"]);
                        $objFilter->setFilterProperty($filtId, "schott", $fa["schott"]);
                    } else {
                        // Add the new filter!
                        $filtId = $objFilter->addFilter($fa["name"], $fa["type"], $fa["color"], $fa["wratten"], $fa["schott"]);
                        $objDatabase->execSQL("update filters set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $filtId . "\";");
                    }
                }
                // Eyepiece is not mandatory
                if ($observation->getElementsByTagName("eyepiece")->item(0)) {
                    // Check if the eyepiece already exists in DeepskyLog
                    $eyepiece = $eyepieceArray[$observation->getElementsByTagName("eyepiece")->item(0)->nodeValue]["name"];
                    $ea = $eyepieceArray[$observation->getElementsByTagName("eyepiece")->item(0)->nodeValue];
                    if (count($objDatabase->selectRecordArray("SELECT * from eyepieces where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $ea["name"] . "\";")) > 0) {
                        // Update the eyepiece
                        $eyepId = $objEyepiece->getEyepieceId($ea["name"], $_SESSION['deepskylog_id']);
                        $objEyepiece->setEyepieceProperty($eyepId, "name", $ea["name"]);
                        $objEyepiece->setEyepieceProperty($eyepId, "focalLength", $ea["focalLength"]);
                        $objEyepiece->setEyepieceProperty($eyepId, "apparentFOV", $ea["apparentFOV"]);
                        $objEyepiece->setEyepieceProperty($eyepId, "maxFocalLength", $ea["maxFocalLength"]);
                    } else {
                        // Add the new eyepiece!
                        $eyepId = $objEyepiece->addEyepiece($ea["name"], $ea["focalLength"], $ea["apparentFOV"]);
                        $objDatabase->execSQL("update eyepieces set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $eyepId . "\";");
                        $objEyepiece->setEyepieceProperty($eyepId, "maxFocalLength", $ea["maxFocalLength"]);
                    }
                }
                // Lens is not mandatory
                if ($observation->getElementsByTagName("lens")->item(0)) {
                    // Check if the eyepiece already exists in DeepskyLog
                    $lens = $lensArray[$observation->getElementsByTagName("lens")->item(0)->nodeValue]["name"];
                    $la = $lensArray[$observation->getElementsByTagName("lens")->item(0)->nodeValue];
                    if (count($objDatabase->selectRecordArray("SELECT * from lenses where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $lens . "\";")) > 0) {
                        // Update the lens
                        $lensId = $objLens->getLensId($la["name"], $_SESSION['deepskylog_id']);
                        $objLens->setLensProperty($lensId, "name", $la["name"]);
                        $objLens->setLensProperty($lensId, "factor", $la["factor"]);
                    } else {
                        // Add the new lens!
                        $lensId = $objLens->addLens($la["name"], $la["factor"]);
                        $objDatabase->execSQL("update lenses set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $lensId . "\";");
                    }
                }
                // Object!!!
                $target = $targetArray[$observation->getElementsByTagName("target")->item(0)->nodeValue]["name"];
                $ta = $targetArray[$observation->getElementsByTagName("target")->item(0)->nodeValue];
                if ($ta["valid"] && $siteValid) {
                    if ($ta["known"] == 1) {
                        $pattern = '/([A-Za-z]+)([\\d\\D\\w]*)/';
                        $targetName = preg_replace($pattern, '${1} ${2}', $target);
                        $targetName = str_replace("  ", " ", $targetName);
                        $objeId = -1;
                        // Check if the object with the given name exists. If this is the case, set the objeId, else check the alternative names
                        $targetName = $objCatalog->checkObject($targetName);
                        if (count($objDatabase->selectRecordArray("SELECT objectnames.objectname FROM objectnames WHERE (objectnames.altname = \"" . $targetName . "\");")) > 0) {
                            $objeId = $objObject->getDsObjectName($targetName);
                        } else {
                            // Object with the given name does not exist... Check if the name is an alternative name
                            for ($i = 0; $i < sizeof($ta["aliases"]); $i++) {
                                $targetName = preg_replace($pattern, '${1} ${2}', $ta["aliases"]["alias" . $i]);
                                $targetName = str_replace("  ", " ", $targetName);
                                $targetName = $objCatalog->checkObject($targetName);
                                if (count($objDatabase->selectRecordArray("SELECT objectnames.objectname FROM objectnames WHERE (objectnames.altname = \"" . $targetName . "\")")) > 0) {
                                    $objeId = $objObject->getDsObjectName($targetName);
                                }
                            }
                            if ($objeId == -1) {
                                // Object does not exist (name or alternative name)
                                // Check for the type and coordinates. If there is already an object at the same coordinates with the same type, add the alternative name
                                if (count($objDatabase->selectRecordArray("SELECT name FROM objects WHERE ra > " . ($ta["ra"] - 0.0001) . " and ra < " . ($ta["ra"] + 0.0001) . " and decl > " . ($ta["dec"] - 0.0001) . " and decl < " . ($ta["dec"] + 0.0001) . " and type = \"" . $ta["type"] . "\"")) > 0) {
                                    $run = $objDatabase->selectRecordset("SELECT name FROM objects WHERE ra > " . ($ta["ra"] - 0.0001) . " and ra < " . ($ta["ra"] + 0.0001) . " and decl > " . ($ta["dec"] - 0.0001) . " and decl < " . ($ta["dec"] + 0.0001) . " and type = \"" . $ta["type"] . "\"");
                                    $get = $run->fetch(PDO::FETCH_OBJ);
                                    $objeId = $get->name;
                                    // Also add alternative name to the existing object.
                                    $names = explode(" ", $objeId);
                                    $aliasNames = explode(" ", $targetName);
                                    $objObject->newAltName($names[0] . " " . $names[1], $aliasNames[0], $aliasNames[1]);
                                } else {
                                    // else, add new object
                                    $targetName = preg_replace($pattern, '${1} ${2}', $target);
                                    $targetName = str_replace("  ", " ", $targetName);
                                    $targetName = $objCatalog->checkObject($targetName);
                                    $names = explode(" ", $targetName);
                                    $objObject->addDSObject($names[0] . " " . $names[1], $names[0], $names[1], $ta["type"], $ta["constellation"], $ta["ra"], $ta["dec"], $ta["mag"], $ta["subr"], $ta["diam1"], $ta["diam2"], $ta["pa"], $ta["datasource"]);
                                    for ($i = 0; $i < sizeof($ta["aliases"]); $i++) {
                                        $aliasName = preg_replace($pattern, '${1} ${2}', $ta["aliases"]["alias" . $i]);
                                        $aliasNames = explode(" ", $aliasName);
                                        $objObject->newAltName($names[0] . " " . $names[1], $aliasNames[0], $aliasNames[1]);
                                    }
                                    $objeId = $objObject->getDsObjectName($targetName);
                                    $body = LangValidateAccountEmailTitleObject . " <a href=\"http://www.deepskylog.org/index.php?indexAction=detail_object&object=" . urlencode($targetName) . "\">" . $targetName . "</a> " . LangValidateAccountEmailTitleObject2 . " " . LangValidateAccountEmailTitleObjectObserver . " <a href=\"http://www.deepskylog.org/index.php?indexAction=detail_observer&user="******"\">" . $objObserver->getObserverProperty($loggedUser, 'firstname') . " " . $objObserver->getObserverProperty($loggedUser, 'name') . "</a>.<br /><br />";
                                    if (isset($developversion) && $developversion == 1) {
                                        $entryMessage .= "On the live server, a mail would be sent with the subject: " . $subject . ".<br />";
                                    } else {
                                        $objMessage->sendEmail(LangValidateAccountEmailTitleObject . " " . $targetName . LangValidateAccountEmailTitleObject2, $body, "developers");
                                    }
                                }
                            }
                        }
                        // Check if the observation already exists!
                        $dateArray = sscanf($observation->getElementsByTagName("begin")->item(0)->nodeValue, "%4d-%2d-%2dT%2d:%2d:%2d%c%02d:%02d");
                        $date = mktime($dateArray[3], $dateArray[4], 0, $dateArray[1], $dateArray[2], $dateArray[0]);
                        if ($dateArray[6] == "-") {
                            $timeDiff = -($dateArray[7] * 60 + $dateArray[8]) * 60.0;
                        } else {
                            $timeDiff = ($dateArray[7] * 60 + $dateArray[8]) * 60.0;
                        }
                        // Get the time and date in UT.
                        $date = $date - $timeDiff;
                        $dateStr = date("Ymd", $date);
                        $timeStr = date("Hi", $date);
                        if ($instId > 1) {
                            // Check if the observation does already exist
                            $obsId = $objDatabase->selectRecordArray("SELECT id from observations WHERE objectname = \"" . $objeId . "\" and date = \"" . $dateStr . "\" and instrumentid = \"" . $instId . "\" and locationId = \"" . $locId . "\" and observerid = \"" . $_SESSION['deepskylog_id'] . "\";");
                            if (count($obsId) > 0) {
                                // TODO : Adapt observation
                            } else {
                                // New observation
                                $resultNode = $observation->getElementsByTagName("result")->item(0);
                                if ($resultNode->getElementsByTagName("description")->item(0)) {
                                    $description = $resultNode->getElementsByTagName("description")->item(0)->nodeValue;
                                } else {
                                    $description = "";
                                }
                                // Seeing is not mandatory
                                if ($observation->getElementsByTagName("seeing")->item(0)) {
                                    $seeing = $observation->getElementsByTagName("seeing")->item(0)->nodeValue;
                                } else {
                                    $seeing = "-1";
                                }
                                // Limiting magnitude is not mandatory
                                if ($observation->getElementsByTagName("faintestStar")->item(0)) {
                                    $limmag = $observation->getElementsByTagName("faintestStar")->item(0)->nodeValue;
                                } else {
                                    $limmag = "";
                                }
                                if ($resultNode->hasAttribute("lang")) {
                                    $language = $resultNode->getAttribute("lang");
                                } else {
                                    $language = "en";
                                }
                                // Rating is not mandatory
                                if ($resultNode->getElementsByTagName("rating")->item(0)) {
                                    $visibility = $resultNode->getElementsByTagName("rating")->item(0)->nodeValue;
                                } else {
                                    $visibility = 0;
                                }
                                if ($visibility == 99) {
                                    $visibility = 0;
                                }
                                if ($observation->getElementsByTagName("eyepiece")->item(0)) {
                                    $ei = $eyepId;
                                } else {
                                    $ei = 0;
                                }
                                if ($observation->getElementsByTagName("filter")->item(0)) {
                                    $fi = $filtId;
                                } else {
                                    $fi = 0;
                                }
                                if ($observation->getElementsByTagName("lens")->item(0)) {
                                    $li = $lensId;
                                } else {
                                    $li = 0;
                                }
                                $obsId = $objObservation->addDSObservation2($objeId, $_SESSION['deepskylog_id'], $instId, $locId, $dateStr, $timeStr, $description, $seeing, $limmag, $visibility, $language, $ei, $fi, $li);
                                $obsId = $objDatabase->selectSingleValue("SELECT id FROM observations ORDER BY id DESC LIMIT 1", 'id');
                                // Add the observation to the session
                                $objSession->addObservationToSessions($obsId);
                                // Magnification is not mandatory
                                if ($observation->getElementsByTagName("magnification")->item(0)) {
                                    $objObservation->setDsObservationProperty($obsId, "magnification", $observation->getElementsByTagName("magnification")->item(0)->nodeValue);
                                }
                                // Sqm is not mandatory
                                if ($observation->getElementsByTagName("sky-quality")->item(0)) {
                                    // Get sqm value and convert it
                                    $unit = $observation->getElementsByTagName("sky-quality")->item(0)->getAttribute("unit");
                                    if ($unit == "mags-per-squarearcmin") {
                                        $sqm = $observation->getElementsByTagName("sky-quality")->item(0)->nodeValue + 8.890000000000001;
                                    } else {
                                        $sqm = $observation->getElementsByTagName("sky-quality")->item(0)->nodeValue;
                                    }
                                    $objObservation->setDsObservationProperty($obsId, "SQM", $sqm);
                                }
                                // The result of the observation!
                                $resultNode = $observation->getElementsByTagName("result")->item(0);
                                // colorContrasts is not mandatory
                                if ($resultNode->hasAttribute("colorContrasts")) {
                                    if ($resultNode->getAttribute("colorContrasts") == "true") {
                                        $colorContrast = 1;
                                    } else {
                                        $colorContrast = 0;
                                    }
                                } else {
                                    $colorContrast = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "colorContrasts", $colorContrast);
                                // extended is not mandatory
                                if ($resultNode->hasAttribute("extended")) {
                                    if ($resultNode->getAttribute("extended") == "true") {
                                        $extended = 1;
                                    } else {
                                        $extended = 0;
                                    }
                                } else {
                                    $extended = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "extended", $extended);
                                // mottled is not mandatory
                                if ($resultNode->hasAttribute("mottled")) {
                                    if ($resultNode->getAttribute("mottled") == "true") {
                                        $mottled = 1;
                                    } else {
                                        $mottled = 0;
                                    }
                                } else {
                                    $mottled = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "mottled", $mottled);
                                // resolved is not mandatory
                                if ($resultNode->hasAttribute("resolved")) {
                                    if ($resultNode->getAttribute("resolved") == "true") {
                                        $resolved = 1;
                                    } else {
                                        $resolved = 0;
                                    }
                                } else {
                                    $resolved = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "resolved", $resolved);
                                // stellar is not mandatory
                                if ($resultNode->hasAttribute("stellar")) {
                                    if ($resultNode->getAttribute("stellar") == "true") {
                                        $stellar = 1;
                                    } else {
                                        $stellar = 0;
                                    }
                                } else {
                                    $stellar = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "stellar", $stellar);
                                // unusualShape is not mandatory
                                if ($resultNode->hasAttribute("unusualShape")) {
                                    if ($resultNode->getAttribute("unusualShape") == "true") {
                                        $unusualShape = 1;
                                    } else {
                                        $unusualShape = 0;
                                    }
                                } else {
                                    $unusualShape = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "unusualShape", $unusualShape);
                                // partlyUnresolved is not mandatory
                                if ($resultNode->hasAttribute("partlyUnresolved")) {
                                    if ($resultNode->getAttribute("partlyUnresolved") == "true") {
                                        $partlyUnresolved = 1;
                                    } else {
                                        $partlyUnresolved = 0;
                                    }
                                } else {
                                    $partlyUnresolved = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "partlyUnresolved", $partlyUnresolved);
                                // equalBrightness is not mandatory
                                if ($resultNode->hasAttribute("equalBrightness")) {
                                    if ($resultNode->getAttribute("equalBrightness") == "true") {
                                        $equalBrightness = 1;
                                    } else {
                                        $equalBrightness = 0;
                                    }
                                } else {
                                    $equalBrightness = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "equalBrightness", $equalBrightness);
                                // niceSurrounding is not mandatory
                                if ($resultNode->hasAttribute("niceSurrounding")) {
                                    if ($resultNode->getAttribute("niceSurrounding") == "true") {
                                        $niceSurrounding = 1;
                                    } else {
                                        $niceSurrounding = 0;
                                    }
                                } else {
                                    $niceSurrounding = -1;
                                }
                                $objObservation->setDsObservationProperty($obsId, "nicefield", $niceSurrounding);
                                // colorMain is not mandatory
                                if ($resultNode->getElementsByTagName("colorMain")->item(0)) {
                                    $color1 = $resultNode->getElementsByTagName("colorMain")->item(0)->nodeValue;
                                    if ($color1 == "White" || $color1 == "white") {
                                        $col1 = 1;
                                    }
                                    if ($color1 == "Red" || $color1 == "red") {
                                        $col1 = 2;
                                    }
                                    if ($color1 == "Orange" || $color1 == "orange") {
                                        $col1 = 3;
                                    }
                                    if ($color1 == "Yellow" || $color1 == "yellow") {
                                        $col1 = 4;
                                    }
                                    if ($color1 == "Green" || $color1 == "green") {
                                        $col1 = 5;
                                    }
                                    if ($color1 == "Blue" || $color1 == "blue") {
                                        $col1 = 6;
                                    }
                                    $objObservation->setDsObservationProperty($obsId, "component1", $col1);
                                }
                                // colorCompanion is not mandatory
                                if ($resultNode->getElementsByTagName("colorCompanion")->item(0)) {
                                    $color2 = $resultNode->getElementsByTagName("colorCompanion")->item(0)->nodeValue;
                                    if ($color2 == "White" || $color2 == "white") {
                                        $col2 = 1;
                                    }
                                    if ($color2 == "Red" || $color2 == "red") {
                                        $col2 = 2;
                                    }
                                    if ($color2 == "Orange" || $color2 == "orange") {
                                        $col2 = 3;
                                    }
                                    if ($color2 == "Yellow" || $color2 == "yellow") {
                                        $col2 = 4;
                                    }
                                    if ($color2 == "Green" || $color2 == "green") {
                                        $col2 = 5;
                                    }
                                    if ($color2 == "Blue" || $color2 == "blue") {
                                        $col2 = 6;
                                    }
                                    $objObservation->setDsObservationProperty($obsId, "component2", $col2);
                                }
                                // Character is not mandatory
                                if ($resultNode->getElementsByTagName("character")->item(0)) {
                                    $objObservation->setDsObservationProperty($obsId, "clusterType", $resultNode->getElementsByTagName("character")->item(0)->nodeValue);
                                }
                                // smallDiameter is not mandatory
                                if ($resultNode->getElementsByTagName("smallDiameter")->item(0)) {
                                    $unit = $resultNode->getElementsByTagName("smallDiameter")->item(0)->getAttribute("unit");
                                    if ($unit == "deg") {
                                        $smallDiameter = $resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 3600.0;
                                    } else {
                                        if ($unit == "rad") {
                                            $smallDiameter = Rad2Deg($resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue) * 3600.0;
                                        } else {
                                            if ($unit == "arcmin") {
                                                $smallDiameter = $resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 60.0;
                                            } else {
                                                if ($unit == "arcsec") {
                                                    $smallDiameter = $resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue;
                                                }
                                            }
                                        }
                                    }
                                    $objObservation->setDsObservationProperty($obsId, "smallDiameter", $smallDiameter);
                                }
                                // largeDiameter is not mandatory
                                if ($resultNode->getElementsByTagName("largeDiameter")->item(0)) {
                                    $unit = $resultNode->getElementsByTagName("largeDiameter")->item(0)->getAttribute("unit");
                                    if ($unit == "deg") {
                                        $largeDiameter = $resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 3600.0;
                                    } else {
                                        if ($unit == "rad") {
                                            $largeDiameter = Rad2Deg($resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue) * 3600.0;
                                        } else {
                                            if ($unit == "arcmin") {
                                                $largeDiameter = $resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 60.0;
                                            } else {
                                                if ($unit == "arcsec") {
                                                    $largeDiameter = $resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue;
                                                }
                                            }
                                        }
                                    }
                                    $objObservation->setDsObservationProperty($obsId, "largeDiameter", $largeDiameter);
                                }
                                if ($observation->getElementsByTagName("magnification")->item(0)) {
                                    $objObservation->setDsObservationProperty($obsId, "magnification", $observation->getElementsByTagName("magnification")->item(0)->nodeValue);
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        $entryMessage .= LangXMLError3;
        $_GET['indexAction'] = "add_xml";
        return;
    }
}
Example #10
0
 /**
  * @param $record
  * @param $debug
  */
 public static function set_hcvrna_outcome($record, $debug)
 {
     global $Proj, $project_id, $ie_criteria_labels;
     $enable_kint = $debug && (isset($record) && $record != '') ? true : false;
     Kint::enabled($enable_kint);
     $baseline_event_id = $Proj->firstEventId;
     $fieldsets = array('abstracted' => array(array('date_field' => 'hcv_lbdtc'), array('value_field' => 'hcv_lbstresn'), array('detect_field' => 'hcv_supplb_hcvdtct')), 'imported' => array(array('date_field' => 'hcv_im_lbdtc'), array('value_field' => 'hcv_im_lbstresn'), array('detect_field' => 'hcv_im_supplb_hcvdtct'), array('trust' => 'hcv_im_nxtrust')));
     $data = array();
     $field_translate = array();
     $reverse_translate = array();
     foreach ($fieldsets as $formtype => $fieldset) {
         $filter_logic = $formtype == 'abstracted' ? "[hcv_lbdtc] != ''" : "[hcv_im_lbdtc] != '' AND [hcv_im_nxtrust] != 'N'";
         $fields = array();
         foreach ($fieldset as $field) {
             foreach ($field as $key => $value) {
                 $fields[] = $value;
                 $field_translate[$formtype][$key] = $value;
                 $reverse_translate[$formtype][$value] = $key;
             }
         }
         $data[$formtype] = REDCap::getData('array', $record, $fields, null, null, false, false, false, $filter_logic);
     }
     /**
      * Main
      */
     $ie_fields = array('ie_ietestcd');
     $ie_data = REDCap::getData('array', $record, $ie_fields);
     $date_fields = array('dm_usubjid', 'dm_rfstdtc', 'dis_suppfa_txendt', 'eot_dsterm', 'dis_dsstdy', 'hcv_suppfa_fuelgbl', 'hcv_suppfa_nlgblrsn', 'hcv_suppfa_hcvout', 'hcv_suppfa_wk10rna', 'hcv_suppfa_lastbloq', 'dis_suppds_funcmprsn', 'hcv_suppfa_fudue', 'dm_suppdm_hcvt2id', 'dm_actarmcd', 'dm_suppdm_rtrtsdtc');
     $date_data = REDCap::getData('array', $record, $date_fields, $baseline_event_id);
     foreach ($date_data as $subject_id => $subject) {
         $all_events = array();
         $post_tx_dates = array();
         $post_tx_bloq_dates = array();
         $re_treat_candidate = false;
         $re_treat_dates = array();
         foreach ($subject as $date_event_id => $date_event) {
             /**
              * HCV RNA Outcome
              */
             $hcvrna_improved = false;
             $on_tx_scores = array();
             $hcvrna_previous_score = '';
             $post_tx_scores = array();
             $post_tx_plus10w_scores = array();
             $post_tx_plus10d_scores = array();
             $last_hcvrna_bloq = false;
             $stop_date_plus_10w = null;
             $stop_date_plus_10d = null;
             $tx_stopped_10_wks_ago = false;
             $started_tx = false;
             $stopped_tx = false;
             $hcv_fu_eligible = true;
             $hcv_fu_ineligible_reason = array();
             $lost_to_followup = false;
             $hcv_data_due = false;
             $tx_start_date = isset($date_event['dm_rfstdtc']) && $date_event['dm_rfstdtc'] != '' ? $date_event['dm_rfstdtc'] : null;
             $stop_date = isset($date_event['dis_suppfa_txendt']) && $date_event['dis_suppfa_txendt'] != '' ? $date_event['dis_suppfa_txendt'] : null;
             $dis_dsstdy = isset($date_event['dis_dsstdy']) && $date_event['dis_dsstdy'] != '' ? $date_event['dis_dsstdy'] : null;
             $eot_dsterm = isset($date_event['eot_dsterm']) && $date_event['eot_dsterm'] != '' ? $date_event['eot_dsterm'] : null;
             /**
              * look for this dm_usubjid in dm_suppdm_hcvt2id. This is a foreign key between TARGET 2 and TARGET 3 patients.
              * Get the start date of the TARGET 3 patient if dm_suppdm_hcvt2id is not empty.
              */
             $t3_fk_result = db_query("SELECT record FROM redcap_data WHERE project_id = '{$project_id}' AND field_name = 'dm_suppdm_hcvt2id' AND value = '{$date_event['dm_usubjid']}'");
             if ($t3_fk_result) {
                 $t3_fk = db_fetch_assoc($t3_fk_result);
                 $t3_start_date_value = get_single_field($t3_fk['record'], $project_id, $baseline_event_id, 'dm_rfstdtc', '');
             }
             $t3_start_date = isset($t3_start_date_value) ? $t3_start_date_value : '';
             /**
              * where are we in treatment?
              */
             if (isset($tx_start_date)) {
                 // started treatment
                 $started_tx = true;
                 /**
                  * treatment must have started to stop
                  */
                 if (isset($stop_date)) {
                     // completed treatment
                     $stopped_tx = true;
                     $stop_date_plus_10d = add_date($stop_date, 10, 0, 0);
                     $stop_date_plus_10w = add_date($stop_date, 64, 0, 0);
                     if (date("Y-m-d") >= $stop_date_plus_10w && isset($stop_date_plus_10w)) {
                         $tx_stopped_10_wks_ago = true;
                     }
                 } else {
                     // not completed treatment
                     $stopped_tx = false;
                     $hcv_fu_eligible = false;
                     $hcv_fu_ineligible_reason[] = 'TX Not Completed';
                 }
             } else {
                 // not started treatment
                 $started_tx = false;
                 $hcv_fu_eligible = false;
                 $hcv_fu_ineligible_reason[] = 'TX Not Started';
             }
             /**
              * get fields for both abstracted (standardized) and imported HCV RNA forms
              */
             foreach ($fieldsets as $formtype => $fieldset) {
                 foreach ($data[$formtype][$subject_id] as $event_id => $event) {
                     /**
                      * standardize array keys
                      */
                     foreach ($event as $event_key => $event_value) {
                         unset($event[$event_key]);
                         $event[array_search($event_key, $field_translate[$formtype])] = $event_value;
                     }
                     /**
                      * merge into all_events array
                      */
                     if ($event['date_field'] != '') {
                         $all_events[$event['date_field']][] = $event;
                     }
                 }
             }
             ksort($all_events);
             /**
              * get outcomes
              */
             foreach ($all_events as $event_date => $event_set) {
                 foreach ($event_set as $event) {
                     /**
                      * if we have a date, and the HCV RNA isn't an 'untrusted blip'...
                      * (blips are sudden, small increases in viral load following EOT)
                      */
                     if (($event['value_field'] != '' || $event['detect_field'] != '') && ($event['date_field'] != '' && $t3_start_date == '' || $event['date_field'] != '' && $t3_start_date != '' && $event['date_field'] <= $t3_start_date)) {
                         $is_bloq = in_array($event['detect_field'], array('BLOQ', 'NOT_SPECIFIED', 'DETECTED')) || $event['value_field'] == '0' ? true : false;
                         $score = $is_bloq ? '0' : '1';
                         /**
                          * if treatment has started, and $event['date_field'] is after start date (is baseline or later)
                          */
                         if ($started_tx && $tx_start_date <= $event['date_field']) {
                             /**
                              * and is...
                              */
                             if (!$stopped_tx || $stopped_tx && $event['date_field'] <= $stop_date) {
                                 // on treatment
                                 $on_tx_scores[] = $score;
                                 if ($score >= $hcvrna_previous_score) {
                                     $hcvrna_improved = false;
                                 } elseif ($score < $hcvrna_previous_score) {
                                     $hcvrna_improved = true;
                                 }
                                 $hcvrna_previous_score = $score;
                                 if ($eot_dsterm == 'LACK_OF_EFFICACY' && get_end_of_array($on_tx_scores) == '1') {
                                     $re_treat_candidate = true;
                                 }
                             } else {
                                 // post-treatment
                                 /**
                                  * RE-TREAT handling
                                  * If this HCVRNA is quantifiable, add the date to an array
                                  * if this HCVRNA is bloq and we have quantified post-TX HCVRNA, it's a re-treat and we don't want it in $post_tx_scores
                                  */
                                 if ($is_bloq && !in_array('1', $post_tx_scores) && !$re_treat_candidate) {
                                     $post_tx_bloq_dates[] = $event['date_field'];
                                     $post_tx_scores[] = $score;
                                     /**
                                      * capture scores that are after EOT plus 10 weeks
                                      */
                                     if (isset($stop_date_plus_10w) && $event['date_field'] >= $stop_date_plus_10w) {
                                         $post_tx_plus10w_scores[] = $score;
                                     }
                                     /**
                                      * capture scores that are between EOT and EOT plus 10 days
                                      */
                                     if (isset($stop_date_plus_10d) && $event['date_field'] <= $stop_date_plus_10d) {
                                         $post_tx_plus10d_scores[] = $score;
                                     }
                                 }
                                 if (!$is_bloq && !in_array('1', $post_tx_scores) && !$re_treat_candidate) {
                                     $post_tx_dates[] = $event['date_field'];
                                     $post_tx_scores[] = $score;
                                     /**
                                      * capture scores that are after EOT plus 10 weeks
                                      */
                                     if (isset($stop_date_plus_10w) && $event['date_field'] >= $stop_date_plus_10w) {
                                         $post_tx_plus10w_scores[] = $score;
                                     }
                                     /**
                                      * capture scores that are between EOT and EOT plus 10 days
                                      */
                                     if (isset($stop_date_plus_10d) && $event['date_field'] <= $stop_date_plus_10d) {
                                         $post_tx_plus10d_scores[] = $score;
                                     }
                                 }
                                 if ($is_bloq && in_array('1', $post_tx_scores)) {
                                     $re_treat_candidate = true;
                                 }
                             }
                         }
                     }
                 }
             }
             /**
              * we have all our score candidates
              */
             $all_scores = array_merge($on_tx_scores, $post_tx_scores);
             $last_hcvrna_bloq = count($all_scores) > 0 && get_end_of_array($all_scores) == '0' ? true : false;
             /**
              * get candidates for re-treat cutoff date
              */
             $re_treat_dates = array_diff(array_unique($post_tx_dates), array_unique($post_tx_bloq_dates));
             /**
              * HCVRNA Followup Eligibility
              * subjects are ineligible for followup if:
              */
             foreach ($ie_data[$subject_id] as $ie_event) {
                 if ($ie_event['ie_ietestcd'] != '') {
                     // failed i/e criteria
                     $hcv_fu_eligible = false;
                     $hcv_fu_ineligible_reason[] = $ie_criteria_labels[$ie_event['ie_ietestcd']];
                 }
             }
             /**
              * disposition-related ineligibility
              */
             if (in_array($date_event['eot_dsterm'], array('LOST_TO_FOLLOWUP', 'LACK_OF_EFFICACY'))) {
                 // disposition is lost to followup
                 $lost_to_followup = true;
                 $hcv_fu_eligible = false;
                 $hcv_fu_ineligible_reason[] = fix_case($date_event['eot_dsterm']);
             }
             /**
              * Quantified HCVRNA after EOT
              */
             if (count($post_tx_scores) > 1 && !$hcvrna_improved) {
                 if (in_array('1', $post_tx_scores)) {
                     // had quantified HCV RNA after EOT
                     $hcv_fu_eligible = false;
                     $hcv_fu_ineligible_reason[] = 'Quantified post-TX HCVRNA';
                 }
             } else {
                 if (in_array('1', $post_tx_scores)) {
                     // had quantified HCV RNA after EOT
                     $hcv_fu_eligible = false;
                     $hcv_fu_ineligible_reason[] = 'Quantified post-TX HCVRNA';
                 }
             }
             /**
              * lost to post-treatment follow up if not already LTFU
              */
             $post_tx_followup_eligible = $date_event['dis_suppds_funcmprsn'] == 'LOST_TO_FOLLOWUP' ? false : true;
             if (!$lost_to_followup) {
                 if (!$post_tx_followup_eligible) {
                     $lost_to_followup = true;
                     $hcv_fu_eligible = false;
                     $hcv_fu_ineligible_reason[] = 'Lost to post-TX followup';
                 }
             }
             /**
              * derive outcome now as it's needed below
              */
             $GLOBALS['started_tx'] = $started_tx;
             $GLOBALS['stopped_tx'] = $stopped_tx;
             $GLOBALS['post_tx_plus10w_scores'] = $post_tx_plus10w_scores;
             $GLOBALS['last_hcvrna_bloq'] = $last_hcvrna_bloq;
             $GLOBALS['lost_to_followup'] = $lost_to_followup;
             $GLOBALS['tx_stopped_10_wks_ago'] = $tx_stopped_10_wks_ago;
             $GLOBALS['hcv_fu_eligible'] = $hcv_fu_eligible;
             $GLOBALS['on_tx_scores'] = $on_tx_scores;
             $GLOBALS['post_tx_plus10d_scores'] = $post_tx_plus10d_scores;
             $GLOBALS['post_tx_scores'] = $post_tx_scores;
             $GLOBALS['eot_dsterm'] = $eot_dsterm;
             $outcome = self::get_outcome();
             /**
              * IS FOLLOWUP DATA FOR THIS SUBJECT DUE?
              * if followup eligible and treatment duration greater than 4 weeks...
              */
             if ($hcv_fu_eligible && $post_tx_followup_eligible && isset($dis_dsstdy) && $dis_dsstdy >= 29) {
                 /**
                  * AND today is TX stop date + 14 weeks ago, and no final outcome, data is due
                  */
                 if (date("Y-m-d") >= add_date($stop_date, 98, 0, 0) && !in_array($outcome, array('SVR', 'VIRAL BREAKTHROUGH', 'RELAPSE', 'NON-RESPONDER', 'LOST TO FOLLOWUP'))) {
                     $hcv_data_due = true;
                 }
             }
             /**
              * if not followup eligible (and no TX stop - implied by ineligible)...
              */
             if ((!$hcv_fu_eligible || !$post_tx_followup_eligible) && $started_tx && !$stopped_tx) {
                 /**
                  * is regimen SOF + RBV?
                  */
                 $regimen = get_single_field($subject_id, $project_id, $baseline_event_id, 'dm_actarmcd', null);
                 //					$due_fields = array('sof_cmstdtc', 'rib_cmstdtc');
                 //					$due_data = REDCap::getData('array', $subject_id, $due_fields);
                 //					$sof_rbv_regimen = false;
                 //					$sof = array();
                 //					$rbv = array();
                 //					foreach ($due_data[$subject_id] AS $event_id => $event) {
                 //						if ($event['sof_cmstdtc'] != '') {
                 //							$sof[] = true;
                 //						}
                 //						if ($event['rib_cmstdtc'] != '') {
                 //							$rbv[] = true;
                 //						}
                 //					}
                 $sof_rbv_regimen = $regimen == 'SOF/RBV' ? true : false;
                 /**
                  * get genotype
                  */
                 $genotype = get_single_field($subject_id, $project_id, $baseline_event_id, 'hcvgt_lborres', '');
                 /**
                  * if regimen is SOF + RBV and Genotype 1 or 3
                  */
                 if ($sof_rbv_regimen && ($genotype == '1' || $genotype == '3')) {
                     /**
                      * AND if TX start is 168 days ago, data is due
                      */
                     if (date("Y-m-d") >= add_date($tx_start_date, 168, 0, 0)) {
                         $hcv_data_due = true;
                     }
                     /**
                      * if regimen is SOF + RBV and Genotype 2
                      */
                 } elseif ($sof_rbv_regimen && $genotype == '2') {
                     /**
                      * if TX start is 84 days ago, data is due
                      */
                     if (date("Y-m-d") >= add_date($tx_start_date, 84, 0, 0)) {
                         $hcv_data_due = true;
                     }
                     /**
                      * if any other regimen or genotype
                      */
                 } else {
                     /**
                      * if TX start is 84 days ago, data is due
                      */
                     if (date("Y-m-d") >= add_date($tx_start_date, 84, 0, 0)) {
                         $hcv_data_due = true;
                     }
                 }
             }
             /**
              * get values
              */
             $last_bloq = $last_hcvrna_bloq ? 'Y' : 'N';
             $eligible = !$hcv_fu_eligible ? 'N' : 'Y';
             $reason = implode('; ', array_unique($hcv_fu_ineligible_reason));
             $data_due = $hcv_data_due ? 'Y' : 'N';
             $wk10_rna = count($post_tx_plus10w_scores) > 0 ? 'Y' : 'N';
             rsort($re_treat_dates);
             $re_treat_date = $re_treat_candidate ? get_end_of_array($re_treat_dates) : null;
             /**
              * debug
              */
             d($all_scores);
             if ($started_tx) {
                 d($tx_start_date);
                 d($on_tx_scores);
                 if ($stopped_tx) {
                     d($stop_date);
                     d($post_tx_scores);
                     d($post_tx_plus10d_scores);
                     d($post_tx_plus10w_scores);
                     d($last_hcvrna_bloq);
                     d($lost_to_followup);
                     d($post_tx_followup_eligible);
                     d($hcv_fu_eligible);
                     d($post_tx_bloq_dates);
                     d($post_tx_dates);
                     d($t3_start_date);
                     d($re_treat_candidate);
                     d($re_treat_date);
                     d($tx_stopped_10_wks_ago);
                     d($hcv_data_due);
                     d($outcome);
                 } else {
                     d('NO TX STOP');
                 }
             } else {
                 d('NO TX START');
             }
             /**
              * set overall hcvrna followup eligibility and reason if ineligible
              */
             update_field_compare($subject_id, $project_id, $baseline_event_id, $eligible, $date_event['hcv_suppfa_fuelgbl'], 'hcv_suppfa_fuelgbl', $debug);
             update_field_compare($subject_id, $project_id, $baseline_event_id, $reason, $date_event['hcv_suppfa_nlgblrsn'], 'hcv_suppfa_nlgblrsn', $debug);
             /**
              * set follow up timing - is it due?
              */
             update_field_compare($subject_id, $project_id, $baseline_event_id, $data_due, $date_event['hcv_suppfa_fudue'], 'hcv_suppfa_fudue', $debug);
             /**
              * set outcome
              */
             update_field_compare($subject_id, $project_id, $baseline_event_id, $outcome, $date_event['hcv_suppfa_hcvout'], 'hcv_suppfa_hcvout', $debug);
             /**
              * set 10 HCV RNA?
              */
             update_field_compare($subject_id, $project_id, $baseline_event_id, $wk10_rna, $date_event['hcv_suppfa_wk10rna'], 'hcv_suppfa_wk10rna', $debug);
             /**
              * set HCV RNA BLOQ?
              */
             update_field_compare($subject_id, $project_id, $baseline_event_id, $last_bloq, $date_event['hcv_suppfa_lastbloq'], 'hcv_suppfa_lastbloq', $debug);
             /**
              * set re-treat window start date
              */
             update_field_compare($subject_id, $project_id, $baseline_event_id, $re_treat_date, $date_event['dm_suppdm_rtrtsdtc'], 'dm_suppdm_rtrtsdtc', $debug);
         }
     }
 }
Example #11
0
function print_rolling_week($start, $where_clause, $query, $f, $g, $empty)
{
    /***************************************************
     * Create calendar array (start time, day of week) *
     ***************************************************/
    global $resolution;
    $days_result = @mysql_query("SELECT DISTINCT day_of_week FROM Weekly_Shift {$where_clause} ORDER BY day_of_week");
    while ($day = @mysql_fetch_array($days_result)) {
        $days[] = $day['day_of_week'];
    }
    $times_result = @mysql_query("SELECT DISTINCT start_time FROM Weekly_Shift {$where_clause} ORDER BY start_time");
    while ($time = @mysql_fetch_array($times_result)) {
        $times[] = $time['start_time'];
    }
    $query_result = @mysql_query($query);
    while ($row = @mysql_fetch_array($query_result)) {
        $calendar[$row['start_time']][$row['day_of_week']][] = $f($row);
    }
    /********************
     * Fill in closures *
     ********************/
    $closures_result = @mysql_query("SELECT * FROM Closure WHERE (start_datetime BETWEEN '{$start}' AND '{$start}' + INTERVAL 7 DAY) OR (end_datetime BETWEEN '{$start}' AND '{$start}' + INTERVAL 7 DAY)");
    $is_new_day = true;
    $cur_day = "";
    while ($row = @mysql_fetch_array($closures_result)) {
        $datetime = $row['start_datetime'];
        while ($datetime != $row['end_datetime'] && date_diff($datetime, date("Y-m-d 00:00:00", strtotime(add_date($start, 0, 0, 0, 0, 7, 0)))) < 0) {
            while (date_diff($datetime, date("Y-m-d 00:00:00", strtotime($start))) < 0) {
                $datetime = add_date($datetime, 0, $resolution * 60, 0, 0, 0, 0);
            }
            $day_of_week = date("l", strtotime($datetime));
            $datetime_array = explode(" ", $datetime);
            $date = $datetime_array[0];
            $time = $datetime_array[1];
            if ($day_of_week != $cur_day) {
                if (isset($newcol_start_time) && isset($newcol_start_day)) {
                    $calendar[$newcol_start_time][$newcol_start_day][1] = $count;
                }
                $newcol_start_time = $time;
                $newcol_start_day = $day_of_week;
                $is_new_day = true;
            }
            if ($is_new_day && in_array($time, $times)) {
                $calendar[$time][$day_of_week][0] = "Closed: {$row['reason']}";
                $is_new_day = false;
                $cur_day = $day_of_week;
                $count = 1;
            } elseif (in_array($time, $times)) {
                $calendar[$time][$day_of_week][0] = "empty";
                $count++;
            }
            $datetime = add_date($datetime, 0, $resolution * 60, 0, 0, 0, 0);
        }
        if (isset($newcol_start_time) && isset($newcol_start_day)) {
            $calendar[$newcol_start_time][$newcol_start_day][1] = $count;
        }
    }
    /****************
     * Render table *
     ****************/
    echo "<table class=\"calendar\">";
    echo "<tr>";
    echo "<th class=\"time\"><span>Time</span></th>";
    $date = date("Y-m-d H:i:00", strtotime($start));
    for ($offset = 0; $offset < 7; $offset++) {
        $day_of_week = date("l", strtotime($date));
        if (in_array($day_of_week, $days)) {
            $ordered_dates[] = $date;
            $formatted_date = date("D, M j", strtotime($date));
            echo "<th>{$formatted_date}</th>";
        }
        $date = add_date($date, 0, 0, 0, 0, 1, 0);
    }
    echo "</tr>";
    $alt = "alt";
    foreach ($times as $time) {
        $alt = empty($alt) ? "alt" : "";
        $time_array = explode(":", $time);
        $is_hour = $time_array[1] == "00" ? "hour" : "not_hour";
        $formatted_time = format_time($time);
        echo "<tr>";
        echo "<td class=\"time\"><span class=\"{$is_hour}\">{$formatted_time}</span></td>";
        foreach ($ordered_dates as $datetime) {
            $day = date("l", strtotime($datetime));
            if (strpos($calendar[$time][$day][0], "Closed") !== false) {
                echo "<td class=\"closed{$alt} {$is_hour}\" rowspan=\"{$calendar[$time][$day][1]}\">";
                echo $calendar[$time][$day][0];
                echo "</td>";
            } else {
                if (strpos($calendar[$time][$day][0], "empty") !== false) {
                    continue;
                    // multicolumn closure, make this one blank
                } else {
                    $q_result = @mysql_query("SELECT capacity FROM Weekly_Shift WHERE day_of_week='{$day}' AND start_time='{$time}'");
                    $q = @mysql_fetch_array($q_result);
                    $capacity = $q[0] ? $q[0] : 0;
                    echo "<td class=\"cap{$capacity}{$alt} {$is_hour}\">";
                    if ($cell = $calendar[$time][$day]) {
                        $datetime_array = explode(" ", $datetime);
                        echo $g($cell, "{$datetime_array[0]} {$time}");
                    } else {
                        echo $empty;
                    }
                    echo "</td>";
                }
            }
        }
        echo "</tr>";
    }
    echo "</tr>";
    echo "</table>";
}
Example #12
0
function PintarColecciones($colecciones)
{
    $ahora = date("Y-m-d");
    $hace_un_ano = add_date($ahora, -9);
    // seis meses de antiguedad
    $contador = 0;
    foreach ($colecciones as $row) {
        if ($contador < 500) {
            echo "<li>";
            if ($row["f_alta"] > $hace_un_ano && $row["coleccionistas"] > 9) {
                echo "<strong>";
            }
            echo anchor('coleccion/ficha/' . $row["esc_nombre"] . '/' . $row["id"], $row["nombre"], array("title" => $row["ano_publica"] . " " . $row["editorial_nombre"] . $row["f_alta"]));
            if ($row["f_alta"] > $hace_un_ano) {
                echo "</strong>";
            }
            echo "</li>";
            $contador++;
        }
    }
}
Example #13
0
<?php

$title = 'Важни дати';
include '/php/phplogin.php';
include '/includes/headerin.php';
imp_dates($con);
if (isset($_GET['add_date'])) {
    add_date($con);
}
?>
<div class='maincontent'>
    <form method='POST' action="/php/phplogin.php">
    <div class="fffbackg">
        <div class="inheading">
            <h2><?php 
echo $title;
?>
</h2><img class="imglogoin" src="/test/<?php 
echo $uni['pic_logo'];
?>
" title="" alt=""/>
            <h1><?php 
echo $uni['uniname'];
?>
</h1>
        </div>

        <div class="menuonpage">
            <div class="datenote">
                <a href="/imp_dates.php" ><img style='background:#ddd;' alt='ImpDates' title='Важни дати' src='/img/datesimp.png'/></a>
                <a href="/imp_notes.php"><img  alt='ImpNotes' title='Важни бележки' src='/img/notesimp.png'/></a>
			$midpoint = $midpoint_obj->format('Y-m-d');
			/**
			 * format dates so we can use them on timeline
			 */
			$start_date = get_gregorian_date($event['dm_rfstdtc']);
			$end_date = get_gregorian_date($end_obj->format('Y-m-d'));
			$tx_4_weeks_start = get_gregorian_date(add_date($event['dm_rfstdtc'], 21));
			$tx_4_weeks_end = get_gregorian_date(add_date($event['dm_rfstdtc'], 28));
			$tx_12_weeks_start = get_gregorian_date(add_date($event['dm_rfstdtc'], 77));
			$tx_12_weeks_end = get_gregorian_date(add_date($event['dm_rfstdtc'], 84));
			$tx_24_weeks_start = get_gregorian_date(add_date($event['dm_rfstdtc'], 161));
			$tx_24_weeks_end = get_gregorian_date(add_date($event['dm_rfstdtc'], 168));
			$svr12_weeks_start = get_gregorian_date(add_date($event['eot_dsstdtc'], 63));
			$svr12_weeks_end = get_gregorian_date(add_date($event['eot_dsstdtc'], 84));
			$svr24_weeks_start = get_gregorian_date(add_date($event['eot_dsstdtc'], 147));
			$svr24_weeks_end = get_gregorian_date(add_date($event['eot_dsstdtc'], 168));
		}
	}
}
/**
 * enqueue javascript
 */
$script = "<script type='text/javascript'>
var tl;
function onLoad() {
	var theme = Timeline.ClassicTheme.create();
	theme.event.bubble.width = 300;
	theme.event.bubble.height = 300;
	theme.event.track.height = 0;
	theme.event.tape.height = 4;
Example #15
0
 public function save_invoice($id)
 {
     $this->db->trans_begin();
     try {
         $this->invoice->order_id = $id;
         $this->invoice->no = $this->input->post('no');
         $this->invoice->due_date = add_date(date('Y-m-d'), 1, 0, 0);
         $this->invoice->total = $this->input->post('total');
         $save = $this->invoice->insert($this->invoice);
         if (!$save) {
             throw new ErrorException('Menyimpan invoice gagal.');
         }
         //Update orders after invoice created
         $this->order->isInvoiceCreated = '1';
         $this->order->update($id, $this->order);
         $this->db->trans_commit();
         return json_view('success');
     } catch (ErrorException $e) {
         $this->db->trans_rollback();
         return json_view($e->getMessage());
     }
 }
Example #16
0
 function get_by_id($id)
 {
     $this->db->where($this->primary_key, $id);
     if ($row = $this->db->get($this->table_name)->row()) {
         $r_item = $this->db->query("select warehouse_code from invoice_lineitems \n\t\t\twhere invoice_number='{$id}' limit 1")->row();
         if ($r_item) {
             $this->warehouse_code = $r_item->warehouse_code;
         }
         $terms = $row->payment_terms;
         $due_date = $row->due_date;
         if ($t = $this->db->query("select days from type_of_payment where type_of_payment='{$terms}'")) {
             if ($t = $t->row()) {
                 $due_date = add_date($row->invoice_date, $t->days);
             }
         }
         $data['warehouse_code'] = $this->warehouse_code;
         $data['due_date'] = $due_date;
         $this->update($id, $data);
     }
     $this->db->where($this->primary_key, $id);
     return $this->db->get($this->table_name);
 }
Example #17
0
 function proses_kredit_save($data)
 {
     //param $data['old_loan_id'], $data['new_loan_id'], $data['loan_date']
     $this->load->model("leasing/invoice_header_model");
     $ok = false;
     $old = $data['old_loan_id'];
     $data['loan_date'] = date('Y-m-d H:i:s', strtotime($data['loan_date']));
     if ($data['new_loan_id'] == "") {
         $data['new_loan_id'] = "01630" . substr($old, -6);
     }
     $rs_loan['loan_id'] = $data['new_loan_id'];
     $rs_loan['loan_date'] = $data['loan_date'];
     $rs_loan['loan_date'] = $data['loan_date'];
     $rs_loan['status'] = 1;
     if ($query = $this->db->where("loan_id", $data['old_loan_id'])->update("ls_loan_master", $rs_loan)) {
         $this->db->query("update ls_loan_obj_items \n\t\t\t\tset loan_id='" . $data['new_loan_id'] . "' \n\t\t\t\twhere loan_id='" . $data['old_loan_id'] . "'");
         if ($query = $this->db->query("select * from ls_loan_master lm\n\t\t\t\twhere lm.loan_id='" . $data['new_loan_id'] . "'")) {
             if ($row_loan = $query->row()) {
                 $qspk = $this->db->query("select * from ls_app_master  \n\t\t\t\t\twhere app_id='" . $row_loan->app_id . "'");
                 $spk = $qspk->row();
                 $rs_invoice = null;
                 // hapus dulu data invoice yg ada
                 $this->db->where("loan_id", $data['new_loan_id'])->delete("ls_invoice_header");
                 $tgl_tagih = date('Y-m-d H:i:s', strtotime($data['loan_date']));
                 for ($tenor = 0; $tenor < $row_loan->max_month; $tenor++) {
                     $faktur = $row_loan->loan_id . "-" . strzero($tenor + 1, 2);
                     $rs_invoice['loan_id'] = $row_loan->loan_id;
                     $rs_invoice['app_id'] = $spk->app_id;
                     $rs_invoice['idx_month'] = strzero($tenor + 1, 2);
                     $rs_invoice['invoice_number'] = $faktur;
                     $rs_invoice['invoice_date'] = add_date($tgl_tagih, 0, $tenor + 1);
                     $rs_invoice['invoice_type'] = "I";
                     $rs_invoice['amount'] = $spk->inst_amount;
                     $rs_invoice['cust_deal_id'] = $row_loan->cust_id;
                     $rs_invoice['cust_deal_ship_id'] = $spk->counter_id;
                     $rs_invoice['gross_amount'] = $spk->inst_amount;
                     $rs_invoice['insr_amount'] = $spk->insr_amount;
                     $rs_invoice['pokok'] = $spk->inst_amount - $spk->rate_amount;
                     $rs_invoice['bunga'] = $spk->rate_amount;
                     $rs_invoice['disc_amount'] = 0;
                     $rs_invoice['paid'] = 0;
                     $rs_invoice['admin_amount'] = 0;
                     $ok = $this->invoice_header_model->save($rs_invoice);
                 }
                 $this->db->where("app_id", $spk->app_id)->update("ls_app_master", array("status" => "Finish", "contract_id" => $row_loan->loan_id));
             }
         } else {
             echo mysql_error();
         }
     }
     return $ok;
 }
Example #18
0
function calculate_expiry_date($start, $units, $um)
{
    switch ($um) {
        case 1:
            $mul = 1;
            break;
        case 2:
            $mul = 3;
            break;
        case 3:
            $mul = 6;
            break;
        case 4:
            $mul = 12;
            break;
        default:
            $mul = 0;
            break;
    }
    if ($mul != 0) {
        return add_date($start, $units * $mul);
    }
    return 0;
}
function Preapproval()
{
    $token = '';
    $currDate = getdate();
    $startDate = $currDate['year'] . '-' . $currDate['mon'] . '-' . $currDate['mday'];
    $startDate = strtotime($startDate);
    $startDate = date('Y-m-d', mktime(0, 0, 0, date('m', $startDate), date('d', $startDate), date('Y', $startDate)));
    $endDate = add_date($startDate, 1);
    $returnURL = 'http://www.paypal.com';
    $cancelURL = 'http://www.paypal.com';
    $preapprovalRequest = new PreapprovalRequest();
    $preapprovalRequest->cancelUrl = $cancelURL;
    $preapprovalRequest->returnUrl = $returnURL;
    $preapprovalRequest->clientDetails = new ClientDetailsType();
    $preapprovalRequest->clientDetails->applicationId = "APP-80W284485P519543T";
    $preapprovalRequest->clientDetails->deviceId = "PayPal_PHP_SDK";
    $preapprovalRequest->clientDetails->ipAddress = "127.0.0.1";
    $preapprovalRequest->currencyCode = "USD";
    $preapprovalRequest->startingDate = $startDate;
    $preapprovalRequest->endingDate = $endDate;
    $preapprovalRequest->maxNumberOfPayments = "10";
    $preapprovalRequest->maxTotalAmountOfAllPayments = "50.00";
    $preapprovalRequest->requestEnvelope = new RequestEnvelope();
    $preapprovalRequest->requestEnvelope->errorLanguage = "en_US";
    $preapprovalRequest->senderEmail = "*****@*****.**";
    $ap = new AdaptivePayments();
    $response = $ap->Preapproval($preapprovalRequest);
    if (strtoupper($ap->isSuccess) == 'FAILURE') {
        $FaultMsg = $ap->getLastError();
        echo "Transaction Preapproval Failed: error Id: ";
        if (is_array($FaultMsg->error)) {
            echo $FaultMsg->error[0]->errorId . ", error message: " . $FaultMsg->error[0]->message;
        } else {
            echo $FaultMsg->error->errorId . ", error message: " . $FaultMsg->error->message;
        }
    } else {
        $token = $response->preapprovalKey;
        echo "Preapproval Transaction Successful! Key is {$token} \n";
    }
    return $token;
}
				 */
			} elseif ($sof_rbv_regimen && ($genotype == '2')) {
				/**
				 * if TX start is 84 days ago, data is due
				 */
				if (date("Y-m-d") >= (add_date($tx_start_date, 84, 0, 0))) {
					$hcv_data_due = true;
				}
				/**
				 * if any other regimen or genotype
				 */
			} else {
				/**
				 * if TX start is 84 days ago, data is due
				 */
				if (date("Y-m-d") >= (add_date($tx_start_date, 84, 0, 0))) {
					$hcv_data_due = true;
				}
			}
		}
		/**
		 * get values
		 */
		$eligible = !$hcv_fu_eligible ? 'N' : 'Y';
		$reason = implode('; ', array_unique($hcv_fu_ineligible_reason));
		$data_due = $hcv_data_due ? 'Y' : 'N';
		$wk10_rna = $has_10week_results ? 'Y' : 'N';
		$last_bloq = $last_hcvrna_bloq ? 'Y' : 'N';
		/**
		 * debug
		 */
 function get_edition_data($edition_num, $is_package)
 {
     $title_parts = array();
     $title_owner_prefix = empty($_SERVER['PHP_AUTH_USER']) ? '' : $_SERVER['PHP_AUTH_USER'] . '\'s ';
     if (!empty($title_owner_prefix)) {
         $title_parts[] = $title_owner_prefix;
     }
     $num_editions = get_number_of_editions();
     $edition_key = get_edition_id($edition_num);
     $edition_date = add_date(time(), $edition_num);
     $modified = add_date_timestamp(time(), $edition_num);
     $cycle = $edition_num % 10 + 1;
     // http response
     $http_responses = array(200, 404, 401, 403, 500);
     $http_reponses_index = $num_editions - 10 - $edition_num;
     $http_status = 0;
     if ($http_reponses_index >= 0 && $http_reponses_index < count($http_responses)) {
         $http_status = $http_responses[$http_reponses_index];
     }
     $is_timeout = $http_reponses_index == count($http_responses);
     $is_broken = $is_timeout || $http_status > 0;
     if ($is_broken) {
         $title_parts[] = 'Broken Test';
     }
     // edition flags
     $is_published = $edition_num % 3;
     $is_paid = !$is_broken && $edition_num % 7;
     $is_vampire = $edition_num == $num_editions - 20;
     if ($is_broken) {
         $title_parts[] = 'Vampire';
     }
     $is_deleted = $is_vampire && rand(0, 1) == 1;
     // strings
     $price = $is_paid ? 'PAID' : 'FREE';
     $status = $is_published ? 'published' : 'draft';
     // url
     if ($http_status == 0) {
         if ($is_timeout) {
             $url = '../auth_test/responses/timeout.php';
         } else {
             $query = empty($_SERVER['QUERY_STRING']) ? '' : '?' . $_SERVER['QUERY_STRING'];
             $url = "edition/{$edition_key}/" . ($is_package ? 'package.xml' : 'content.xml') . $query;
         }
     } else {
         $url = "../auth_test/responses/{$http_status}.php";
         // todo: fix relative path, so we can find authtest from custom content
     }
     $http_status_summary = array(200 => 'All lies. I return a fake 200 code.', 404 => 'Not Found. I return a 404 code.', 401 => 'Unauthorized. I return a 401 code.', 403 => 'Forbidden. I return a 403 code.', 500 => 'Broken. I return a 500 code.');
     // summary
     $always_updates = $edition_num % 9 == 0;
     $long_ttl = $edition_num % 27 == 0;
     $summary = "You really should read edition {$edition_num}. It's the best {$status} ever. ";
     if ($is_published) {
         $summary .= "It is {$price}. ";
     } else {
         $summary .= "All draft editions are treated as free. ";
     }
     if ($always_updates) {
         $summary .= "And it ALWAYS updates. ";
     }
     if ($long_ttl) {
         $summary .= "I have a long 5 minute TTL on the Atom and Package feeds. ";
     }
     if ($is_vampire) {
         $summary .= "I get deleted and then raise from the dead. ";
     }
     if ($http_status > 0) {
         $summary = $http_status_summary[$http_status] . ' ' . $summary;
     }
     if ($is_timeout) {
         $summary = 'Timeout. I take 60 seconds.' . ' ' . $summary;
     }
     // categories
     $custom_categories = array();
     if ($is_package) {
         $size = 0;
         $parts = get_package_parts($edition_num);
         foreach ($parts as $part_name => $part_info) {
             $size += filesize($part_info['path']);
         }
         $custom_categories['download_size'] = pugpig_bytestosize($size, 0);
     }
     // pages
     $pages = array();
     $num_pages = get_number_of_pages($edition_num);
     for ($page_num = 1; $page_num <= $num_pages; $page_num++) {
         $pages[] = get_page_id($edition_num, $page_num);
     }
     $subtitles = array(null, ' ', null, ' ', "Edition {$edition_num} Sub Title", null, ' ', null, ' ', "This is the stupidly long subtitle for Edition {$edition_num} which isn't going to fit even on an iPad in portrait, especially since all this extra text was added to make this an even longer stupidly long subtitle.");
     $subtitle = $subtitles[$edition_num % count($subtitles)];
     if ($subtitle != null) {
         $custom_categories['subtitle'] = $subtitle;
     }
     // pane model
     $pane_models = array(null, 'scrolling', 'horizontal', 'vertical');
     $pane_model_granularity = 4;
     $pane_model = $pane_models[$edition_num / $pane_model_granularity % count($pane_models)];
     if ($pane_model === null) {
         $summary .= 'With no pane model.';
     } else {
         $custom_categories['pane_model'] = $pane_model;
         $summary .= 'With ' . ucwords($pane_model) . ' pane model.';
     }
     $title_parts[] = "Edition Number {$edition_num}";
     $title_parts = array_filter($title_parts);
     $title = join(' ', $title_parts);
     return array('key' => $edition_key, 'date' => $edition_date, 'title' => $title, 'modified' => !$always_updates ? $modified : time(), 'packaged' => !$always_updates ? $modified : time(), 'ttl' => $long_ttl ? 300 : 0, 'status' => $status, 'price' => $price, 'thumbnail' => "http://lorempixel.com/600/800/abstract/{$cycle}/Issue-{$edition_num}-{$edition_date}/", 'newsstand_cover_art_icon_source' => "http://dummyimage.com/768x1024/000000/ffffff.png?text=Newstand+Cover+768x1024+Issue+{$edition_num}/", 'summary' => $summary, 'tombstone' => $is_deleted, 'url_type' => $is_package ? 'application/pugpigpkg+xml' : 'application/atom+xml', 'url' => $url, 'newsstand_summary' => 'This is a longer summary that can appear in Newsstand. ' . $summary, 'page_ids' => $pages, 'custom_categories' => $custom_categories);
 }
 function get_edition_data($edition_num, $is_package)
 {
     $num_editions = get_number_of_editions();
     $edition_key = get_edition_id($edition_num);
     $edition_date = add_date(time(), $edition_num);
     $modified = add_date_timestamp(time(), $edition_num);
     $cycle = $edition_num % 10 + 1;
     // http response
     $http_responses = array(200, 404, 401, 403, 500);
     $http_reponses_index = $num_editions - 10 - $edition_num;
     $http_status = 0;
     if ($http_reponses_index >= 0 && $http_reponses_index < count($http_responses)) {
         $http_status = $http_responses[$http_reponses_index];
     }
     $is_timeout = $http_reponses_index == count($http_responses);
     $is_broken = $is_timeout || $http_status > 0;
     // edition flags
     $is_published = $edition_num % 3;
     $is_paid = !$is_broken && $edition_num % 7;
     $is_vampire = $edition_num == $num_editions - 20;
     $is_deleted = $is_vampire && rand(0, 1) == 1;
     // strings
     $price = $is_paid ? 'PAID' : 'FREE';
     $status = $is_published ? 'published' : 'draft';
     // url
     if ($http_status == 0) {
         if ($is_timeout) {
             $url = '../auth_test/responses/timeout.php';
         } else {
             $query = empty($_SERVER['QUERY_STRING']) ? '' : '?' . $_SERVER['QUERY_STRING'];
             $url = "edition/{$edition_num}/" . ($is_package ? 'package.xml' : 'content.xml') . $query;
         }
     } else {
         $url = "../auth_test/responses/{$http_status}.php";
         // todo: fix relative path, so we can find authtest from custom content
     }
     $http_status_summary = array(200 => 'All lies. I return a fake 200 code.', 404 => 'Not Found. I return a 404 code.', 401 => 'Unauthorized. I return a 401 code.', 403 => 'Forbidden. I return a 403 code.', 500 => 'Broken. I return a 500 code.');
     // summary
     $always_updates = $edition_num % 9 == 0;
     $long_ttl = $edition_num % 27 == 0;
     $summary = "You really should read edition {$edition_num}. It's the best {$status} ever. ";
     if ($is_published) {
         $summary .= "It is {$price}. ";
     } else {
         $summary .= "All draft editions are treated as free. ";
     }
     if ($always_updates) {
         $summary .= "And it ALWAYS updates. ";
     }
     if ($long_ttl) {
         $summary .= "I have a long 5 minute TTL on the Atom and Package feeds. ";
     }
     if ($is_vampire) {
         $summary .= "I get deleted and then raise from the dead. ";
     }
     if ($http_status > 0) {
         $summary = $http_status_summary[$http_status] . ' ' . $summary;
     }
     if ($is_timeout) {
         $summary = 'Timeout. I take 60 seconds.' . ' ' . $summary;
     }
     // pages
     $pages = array();
     $num_pages = get_number_of_pages($edition_num);
     for ($page_num = 1; $page_num <= $num_pages; $page_num++) {
         $pages[] = get_page_id($edition_num, $page_num);
     }
     return array('key' => $edition_key, 'date' => $edition_date, 'title' => ($is_broken ? 'Broken Test ' : '') . ($is_vampire ? "Vampire " : "") . "Edition Number {$edition_num}", 'modified' => !$always_updates ? $modified : time(), 'packaged' => !$always_updates ? $modified : time(), 'ttl' => $long_ttl ? 300 : 0, 'status' => $status, 'price' => $price, 'thumbnail' => "http://lorempixel.com/600/800/abstract/{$cycle}/Issue-{$edition_num}-{$edition_date}/", 'newsstand_cover_art_icon_source' => "http://dummyimage.com/768x1024/000000/ffffff.png?text=Newstand+Cover+768x1024+Issue+{$edition_num}/", 'summary' => $summary, 'tombstone' => $is_deleted, 'url_type' => $is_package ? 'application/pugpigpkg+xml' : 'application/atom+xml', 'url' => $url, 'newsstand_summary' => 'This is a longer summary that can appear in Newsstand. ' . $summary, 'page_ids' => $pages);
 }
/**
 * @param $subject_id
 * @param $debug
 * determine completeness of all survey-containing events
 */
function events_completion($subject_id, $debug) {
	if (isset($subject_id)) {
		global $Proj, $project_id;
		$today = date("Y-m-d");
		$fields = array();
		$arms = get_arms(array_keys($Proj->eventsForms));
		$baseline_event_id = $Proj->firstEventId;
		$enrollment_event_id = getNextEventId($baseline_event_id);
		$tx_duration = get_single_field($subject_id, $project_id, $enrollment_event_id, 'dm_suppdm_actarmdur', null);
		$tx_first_event = array_search_recursive($tx_duration . ' Weeks', $arms) !== false ? array_search_recursive($tx_duration . ' Weeks', $arms) : null;
		$survey_event_ids = isset($tx_first_event) ? array_merge(array($baseline_event_id), $Proj->getEventsByArmNum($arms[$tx_first_event]['arm_num'])) : array($baseline_event_id);
		foreach ($survey_event_ids AS $survey_event_id) {
			$survey_event_name = $Proj->getUniqueEventNames($survey_event_id);
			$survey_prefix = substr($survey_event_name, 0, strpos($survey_event_name, '_'));
			$fields[] = $survey_prefix . '_completed';
			$fields[] = $survey_prefix . '_date';
			$fields[] = $survey_prefix . '_startdate';
			$fields[] = $survey_prefix . '_deadline';
		}
		$data = REDCap::getData('array', $subject_id, $fields, $baseline_event_id);
		foreach ($survey_event_ids AS $survey_event_id) {
			$data_event_name = $Proj->getUniqueEventNames($survey_event_id);
			$prefix = substr($data_event_name, 0, strpos($data_event_name, '_'));
			$is_t_complete = is_t_complete($subject_id, $survey_event_id);
			$t_complete = $is_t_complete ? '1' : '0';
			foreach ($data[$subject_id] AS $data_event_id => $data_event) {
				foreach ($data_event AS $key => $value) {
					/**
					 * derive intra-event timing variables
					 */
					switch ($key) {
						case $prefix . '_completed':
							update_field_compare($subject_id, $project_id, $data_event_id, $t_complete, $value, $key, $debug);
							break;
						case $prefix . '_date':
							if ($value == '' && $is_t_complete) {
								update_field_compare($subject_id, $project_id, $data_event_id, $today, $value, $key, $debug);
							}
							break;
						default:
							break;
					}
				}
			}
			/**
			 * derive inter-event timing variables
			 */
			$complete_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_completed', null);
			$start_date_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_startdate', null);
			$deadline_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_deadline', null);
			$missed_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_missed', null);
			$t_missed = $complete_value == '0' && $today > $deadline_value && isset($deadline_value) && $deadline_value != '' ? '1' : '0';
			switch ($prefix) {
				case 't1':
					$t_base_date = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_date', null);
					$t_start_date = $t_base_date;
					$t_deadline_date = add_date($t_base_date, 89);
					break;
				default:
					$t_base_date = get_single_field($subject_id, $project_id, $enrollment_event_id, 'dm_rfstdtc', null);
					$t_start_date = add_date($t_base_date, ($arms[$data_event_name]['day_offset'] - $arms[$data_event_name]['offset_min']));
					$t_deadline_date = add_date($t_base_date, ($arms[$data_event_name]['day_offset'] + $arms[$data_event_name]['offset_max']) - 1);
					break;
			}
			update_field_compare($subject_id, $project_id, $baseline_event_id, $t_complete, $complete_value, $prefix . '_completed', $debug);
			update_field_compare($subject_id, $project_id, $baseline_event_id, $t_missed, $missed_value, $prefix . '_missed', $debug);
			if (isset($t_base_date) && $t_base_date != '') {
				update_field_compare($subject_id, $project_id, $baseline_event_id, $t_start_date, $start_date_value, $prefix . '_startdate', $debug);
				update_field_compare($subject_id, $project_id, $baseline_event_id, $t_deadline_date, $deadline_value, $prefix . '_deadline', $debug);
			}
		}
	}
}
Example #24
0
 public function confirm($payment_id, $invoice_id)
 {
     $this->db->trans_begin();
     try {
         // Update payment status konfirmasi pembayaran di set 1 jika nasabah sudah melakukan pembayaran
         $this->payment->isConfirmed = '1';
         $update = $this->payment->update($payment_id, $this->payment);
         if (!$update) {
             throw new ErrorException('konfirmasi pembayaran gagal.');
         }
         // Updata status invoice juga bahwa invoice sudah dibayar
         $this->invoice->isPaid = '1';
         $this->invoice->update($invoice_id, $this->invoice);
         // Update order dengan mengambil order id dari invoice yang sudah dibayar
         $this->db->where('id', $invoice_id);
         $this->db->select('order_id, total');
         $this->db->from('invoices');
         $result = $this->db->get()->result();
         $order_id = $result[0]->order_id;
         $total = $result[0]->total;
         $this->order->status = 'active';
         $this->order->due_date = add_date(date('Y-m-d'), 0, 12, 0);
         $this->order->update($order_id, $this->order);
         // Create income generate otomatis jika sudah melakukan pembayaran pada order ini
         $profit_per_month = 2 / 100 * $total;
         for ($i = 1; $i < 13; $i++) {
             $this->income->order_id = $order_id;
             $this->income->total = $profit_per_month;
             $this->income->due_date = add_date(date('Y-m-d'), 0, $i, 0);
             $this->income->status = $i % 3 == 0 ? 'active' : 'inactive';
             $this->income->insert($this->income);
         }
         $this->db->trans_commit();
         return json_view('success');
     } catch (ErrorException $e) {
         $this->db->trans_rollback();
         return json_view('failed');
     }
 }
Example #25
0
/***********************************************************
SetPreapproval.php

Begining of the Preapproval web flow

Called by index.html.

***********************************************************/
// clearing the session before starting new API Call
require_once 'web_constants.php';
session_unset();
$currDate = getdate();
$startDate = $currDate['year'] . '-' . $currDate['mon'] . '-' . $currDate['mday'];
$startDate = strtotime($startDate);
$startDate = date('Y-m-d', mktime(0, 0, 0, date('m', $startDate), date('d', $startDate), date('Y', $startDate)));
$endDate = add_date($startDate, 1);
function add_date($orgDate, $yr)
{
    $cd = strtotime($orgDate);
    $retDAY = date('Y-m-d', mktime(0, 0, 0, date('m', $cd), date('d', $cd), date('Y', $cd) + $yr));
    return $retDAY;
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Windows (vers 14 February 2006), see www.w3.org">
Example #26
0
	/**
	 * @param $record
	 * @param $event_id
	 * @param $group_id
	 * @param $debug
	 */
	public static function schedule_surveys($record, $event_id, $group_id, $debug)
	{
		global $Proj, $project_id, $user_rights, $table_pk;
		/**
		 * if the user is in a DAG
		 */
		if ($user_rights['group_id'] != "") {
			/**
			 * does this record exist?
			 */
			$q = db_query("SELECT 1 from redcap_data WHERE project_id = $project_id AND record = '$record' LIMIT 1");
			if (db_num_rows($q) > 0) {
				/**
				 * is the record in this users DAG?
				 */
				$q = db_query("SELECT 1 from redcap_data WHERE project_id = $project_id AND record = '$record' AND field_name = '__GROUPID__' AND value = '{$user_rights['group_id']}' LIMIT 1");
				if (db_num_rows($q) < 1) {
					/**
					 * record is not in Users DAG!
					 */
					REDCap::logEvent('Scheduled record is not in users DAG', '', '', $record, $event_id, $project_id);
					exit;
				}
			}
		}
		/**
		 * check to see if the subject has an existing schedule on an existing arm
		 */
		$sub = "SELECT DISTINCT e.arm_id from redcap_events_calendar c, redcap_events_metadata e WHERE c.project_id = $project_id AND c.record = '$record' AND c.event_id = e.event_id";
		$sched_arm_result = db_query("SELECT arm_num FROM redcap_events_arms WHERE project_id = $project_id AND arm_id IN (" . pre_query($sub) . ")");
		if ($sched_arm_result) {
			$trt = Prioritize::getTrtInfo($record);
			if ($debug) {
				error_log(print_r($trt, true));
			}
			$tx_start_date = $trt['rfxstdtc'];
			$rand_date = $trt['rand_date'];
			$dates = array();
			$arm_num = db_result($sched_arm_result, 0, 'arm_num');
			if (isset($arm_num) && $arm_num != '') { // subject has an existing schedule. keep existing event_id > arm structure
				if ($arm_num != '1') { // make sure we don't put anything in the first arm
					$q = db_query("SELECT * from redcap_events_metadata m, redcap_events_arms a WHERE a.project_id = $project_id AND a.arm_id = m.arm_id AND a.arm_num = $arm_num order by m.day_offset, m.descrip");
					if ($q) {
						while ($row = db_fetch_assoc($q)) { // if we have no $arm_num, this will be empty
							/**
							 * get the event date ($rand_date for baseline and $tx_start_date + day_offset)
							 */
							$row['day_offset'] = $arm_num != $trt['timing_arm_num'] ? $trt['timing_offsets'][$row['descrip']] : $row['day_offset'];
							if (in_array($row['descrip'], array('Baseline', 'EOT+1Year', 'EOT+3Year'))) {
								$this_event_date = isset($rand_date) && $rand_date != '' ? add_date($rand_date, $row['day_offset']) : null;
							} else {
								$this_event_date = isset($tx_start_date) && $tx_start_date != '' ? add_date($tx_start_date, $row['day_offset']) : null;
							}
							$dates[$row['event_id']] = $this_event_date;
						}
						db_free_result($q);
					}
				} else {
					REDCap::logEvent('Scheduling attempted in invalid arm', '', '', $record, $event_id, $project_id);
				}
			} else { // subject's schedule is new. put dates into event_ids for this arm
				$arm_result = db_query("SELECT arm_num FROM redcap_events_arms WHERE project_id = '$project_id' AND arm_name = '{$trt['arm']}'");
				if ($arm_result) {
					$arm_num = db_result($arm_result, 0, 'arm_num');
					if ($arm_num != '1') {
						$q = db_query("SELECT * from redcap_events_metadata m, redcap_events_arms a WHERE a.project_id = $project_id AND a.arm_id = m.arm_id AND a.arm_num = $arm_num order by m.day_offset, m.descrip");
						if ($q) {
							while ($row = db_fetch_assoc($q)) { // if we have no $arm_num, this will be empty
								/**
								 * get the event date ($rand_date for baseline and $tx_start_date + day_offset)
								 */
								if (in_array($row['descrip'], array('Baseline', 'EOT+1Year', 'EOT+3Year'))) {
									$this_event_date = isset($rand_date) && $rand_date != '' ? add_date($rand_date, $row['day_offset']) : null;
								} else {
									$this_event_date = isset($tx_start_date) && $tx_start_date != '' ? add_date($tx_start_date, $row['day_offset']) : null;
								}
								$dates[$row['event_id']] = $this_event_date;
							}
							db_free_result($q);
						}
					} else {
						REDCap::logEvent('Scheduling attempted in invalid arm', '', '', $record, $event_id, $project_id);
					}
					db_free_result($arm_result);
				}
			}
			if ($debug) {
				error_log(print_r($dates, true));
			}
			if (!empty($dates)) {
				/**
				 * do we have an existing schedule?
				 */
				$sql = "SELECT c.event_date, c.baseline_date, e.* FROM redcap_events_calendar c, redcap_events_metadata e WHERE c.project_id = $project_id AND c.record = '$record' AND c.event_id = e.event_id AND e.arm_id IN (" . pre_query($sub) . ")";
				$sched_result = db_query($sql);
				if ($sched_result) {
					$sql_all = array();
					$sql_errors = array();
					if (db_num_rows($sched_result) > 0) {
						while ($sched_row = db_fetch_assoc($sched_result)) {
							$base_date = in_array($sched_row['descrip'], array('Baseline', 'EOT+1Year', 'EOT+3Year')) ? $trt['rand_date'] : $trt['rfxstdtc'];
							/**
							 * if the scheduled date is in the $dates array, we don't care about it, so ignore it and remove from $dates
							 * if we have an existing schedule and the dates have changed, update the schedule and remove from $dates
							 * if the base date has changed, update it and the schedule
							 * whatever is left will be new dates, insert into schedule
							 */
							if ($dates[$sched_row['event_id']] == $sched_row['event_date']) {
								unset($dates[$sched_row['event_id']]);
							}
							if (isset($dates[$sched_row['event_id']]) && $dates[$sched_row['event_id']] != '' && $sched_row['event_date'] != $dates[$sched_row['event_id']]) { // the date has changed. update the date.
								$sql = "UPDATE redcap_events_calendar SET event_date = '{$dates[$sched_row['event_id']]}' WHERE record = '$record' AND project_id = '$project_id' AND group_id = '$group_id' AND event_id = '{$sched_row['event_id']}' AND event_date = '{$sched_row['event_date']}'";
								if (!$debug) {
									if (db_query($sql)) {
										$sql_all[] = $sql;
										log_event($sql, "redcap_events_calendar", "MANAGE", $record, $sched_row['event_id'], "Update calendar event");
									} else {
										$sql_errors[] = $sql;
									}
								} else {
									error_log($sql);
								}
								unset($dates[$sched_row['event_id']]);
							}
							if ($base_date != $sched_row['baseline_date']) { // the base_date has changed. this will only occur if the treatment start date or randomization date are changed in the study.
								$sql = "UPDATE redcap_events_calendar SET baseline_date = '" . prep($base_date) . "' WHERE record = '$record' AND project_id = '$project_id' AND group_id = '$group_id' AND event_id = '{$sched_row['event_id']}' AND baseline_date = '{$sched_row['baseline_date']}'";
								if (!$debug) {
									if (db_query($sql)) {
										$sql_all[] = $sql;
										log_event($sql, "redcap_events_calendar", "MANAGE", $record, $sched_row['event_id'], "Update calendar event");
									} else {
										$sql_errors[] = $sql;
									}
								} else {
									error_log($sql);
								}
								unset($dates[$sched_row['event_id']]);
							}
						}
						foreach ($dates AS $date_event_id => $date) { //Loop through dates and add them to the schedule
							$base_date = in_array($Proj->eventInfo[$date_event_id]['name'], array('Baseline', 'EOT+1Year', 'EOT+3Year')) ? $trt['rand_date'] : $trt['rfxstdtc'];
							if (isset($date) && $date != "") { //Add to table
								$sql = "INSERT INTO redcap_events_calendar (record, project_id, group_id, event_id, event_date, event_time, event_status, baseline_date) VALUES ('$record', $project_id, " . checkNull($group_id) . ", '" . prep($date_event_id) . "', '" . prep($date) . "', '" . null . "', 0, '$base_date')";
								if (!$debug) {
									if (db_query($sql)) {
										$sql_all[] = $sql;
									} else {
										$sql_errors[] = $sql;
									}
								} else {
									error_log($sql);
								}
							}
						}
						log_event(implode(";\n", $sql_all), "redcap_events_calendar", "MANAGE", $_GET['idnumber'], "$table_pk = '$record'", "Perform scheduling");
					} else {
						foreach ($dates AS $date_event_id => $date) { //Loop through dates and add them to the schedule
							$base_date = in_array($Proj->eventInfo[$date_event_id]['name'], array('Baseline', 'EOT+1Year', 'EOT+3Year')) ? $trt['rand_date'] : $trt['rfxstdtc'];
							if (isset($date) && $date != "") { //Add to table
								$sql = "INSERT INTO redcap_events_calendar (record, project_id, group_id, event_id, event_date, event_time, event_status, baseline_date) VALUES ('$record', $project_id, " . checkNull($group_id) . ", '" . prep($date_event_id) . "', '" . prep($date) . "', '" . null . "', 0, '$base_date')";
								if (!$debug) {
									if (db_query($sql)) {
										$sql_all[] = $sql;
									} else {
										$sql_errors[] = $sql;
									}
								} else {
									error_log($sql);
								}
							}
						}
						log_event(implode(";\n", $sql_all), "redcap_events_calendar", "MANAGE", $_GET['idnumber'], "$table_pk = '$record'", "Perform scheduling");
					}
				}
				db_free_result($sched_result);
			}
			db_free_result($sched_arm_result);
		}
	}
	if ($subject_result) {
		while ($subject_row = db_fetch_assoc($subject_result)) {
			$subject_array[$subject_row['subjid']] = array();
			foreach ($subject_row AS $key => $value) {
				if ($key != 'subjid') {
					$subject_array[$subject_row['subjid']][$key] = $value;
				}
			}
		}
	}
	foreach ($hist_data AS $subject_id => $subject) {
		if ($debug) {
			show_var($subject_id, 'dm_usubjid', 'blue');
		}
		foreach ($subject AS $event_id => $event) {
			if (($event['dm_rfstdtc'] != '' && $event['dm_rfstdtc'] < add_date(date("Y-m-d"), -168)) && $event['dm_rfendtc'] != '' && $event['livr_mhoccur'] == 'Y') {
				if ($debug) {
					show_var($event, 'EVENT');
				}
				if ($debug) {
					//show_var($subject_sql);
				}
				/**
				 * initialize the working arrays
				 */
				$data_row = array();
				$data_row['Subject ID'] = $subject_id;
				$data_row['Demographics Monitored?'] = '--';
				$data_row['EOT Monitored?'] = '--';
				$data_row['EOT Status'] = '--';
				$data_row['SIM-SOF Containing Regimen?'] = '--';
Example #28
0
$fake_register_globals = false;
require_once "../globals.php";
require_once "{$srcdir}/patient.inc";
require_once "{$srcdir}/options.inc.php";
require_once "../drugs/drugs.inc.php";
require_once "{$srcdir}/formatting.inc.php";
function add_date($givendate, $day = 0, $mth = 0, $yr = 0)
{
    $cd = strtotime($givendate);
    $newdate = date('Y-m-d', mktime(date('h', $cd), date('i', $cd), date('s', $cd), date('m', $cd) + $mth, date('d', $cd) + $day, date('Y', $cd) + $yr));
    return $newdate;
}
$type = $_POST["type"];
$facility = isset($_POST['facility']) ? $_POST['facility'] : '';
$sql_date_from = fixDate($_POST['date_from'], date('Y-01-01'));
$sql_date_to = fixDate($_POST['date_to'], add_date(date('Y-m-d')));
$patient_id = trim($_POST["patient_id"]);
$age_from = $_POST["age_from"];
$age_to = $_POST["age_to"];
$sql_gender = $_POST["gender"];
$sql_ethnicity = $_POST["ethnicity"];
$sql_race = $_POST["race"];
$form_drug_name = trim($_POST["form_drug_name"]);
$form_diagnosis = trim($_POST["form_diagnosis"]);
$form_lab_results = trim($_POST["form_lab_results"]);
$form_service_codes = trim($_POST["form_service_codes"]);
?>
<html>
<head>
<?php 
html_header_show();
Example #29
0
                                                                <td class="text-right"><h4>Totals</h4></td>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <!-- foreach ($order->lineItems as $line) or some such thing here -->
                                                            <tr>
                                                                <td><?php 
echo $order->type;
?>
</td>
                                                                <td class="text-center"><?php 
echo number_format($order->amount, 2);
?>
</td>
                                                                <td class="text-center"><?php 
echo add_date(date('Y-m-d'), 1, 0, 0);
?>
</td>
                                                                <td class="text-right"><?php 
echo number_format($order->amount, 2);
?>
</td>
                                                            </tr>
                                                            
                                                            <tr>
                                                                <td class="thick-line"></td>
                                                                <td class="thick-line"></td>
                                                                <td class="thick-line text-center"><h4>Subtotal</h4></td>
                                                                <td class="thick-line text-right"><h4><?php 
echo number_format($order->amount, 2);
?>