Example #1
0
function execONVIF($cmd)
{
    exec(escapeshellcmd(ZM_PATH_BIN . "/zmonvif-probe.pl {$cmd}"), $output, $status);
    if ($status) {
        Fatal("Unable to probe network cameras, status is '{$status}'");
    }
    return $output;
}
/**
 * \brief get all the licenses for a single file or uploadtree
 * 
 * \param $agent_pk - agent id
 * \param $pfile_pk - pfile id, (if empty, $uploadtree_pk must be given)
 * \param $uploadtree_pk - (used only if $pfile_pk is empty)
 * \param $uploadtree_tablename
 * \param $duplicate - get duplicated licenses or not, if NULL: No, or Yes
 *
 * \return Array of file licenses   LicArray[fl_pk] = rf_shortname if $duplicate is Not NULL
 * LicArray[rf_pk] = rf_shortname if $duplicate is NULL
 * FATAL if neither pfile_pk or uploadtree_pk were passed in
 */
function GetFileLicenses($agent, $pfile_pk, $uploadtree_pk, $uploadtree_tablename = 'uploadtree', $duplicate = "")
{
    global $PG_CONN;
    if (empty($agent)) {
        Fatal("Missing parameter: agent", __FILE__, __LINE__);
    }
    if ($uploadtree_pk) {
        /* Find lft and rgt bounds for this $uploadtree_pk  */
        $sql = "SELECT lft, rgt, upload_fk FROM {$uploadtree_tablename}\n                   WHERE uploadtree_pk = {$uploadtree_pk}";
        $result = pg_query($PG_CONN, $sql);
        DBCheckResult($result, $sql, __FILE__, __LINE__);
        $row = pg_fetch_assoc($result);
        $lft = $row["lft"];
        $rgt = $row["rgt"];
        $upload_pk = $row["upload_fk"];
        pg_free_result($result);
        $agentIdCondition = $agent != "any" ? "and agent_fk={$agent}" : "";
        /* Strip out added upload_pk condition if it isn't needed */
        if ($uploadtree_tablename == "uploadtree_a" or $uploadtree_tablename == "uploadtree") {
            $UploadClause = "upload_fk={$upload_pk} and ";
        } else {
            $UploadClause = "";
        }
        /*  Get the licenses under this $uploadtree_pk*/
        $sql = "SELECT distinct(rf_shortname) as rf_shortname, rf_pk as rf_fk, fl_pk\n              from license_file_ref,\n                  (SELECT distinct(pfile_fk) as PF from {$uploadtree_tablename} \n                     where {$UploadClause} lft BETWEEN {$lft} and {$rgt}) as SS\n              where PF=pfile_fk {$agentIdCondition}\n              order by rf_shortname asc";
        $result = pg_query($PG_CONN, $sql);
        DBCheckResult($result, $sql, __FILE__, __LINE__);
    } else {
        Fatal("Missing function inputs", __FILE__, __LINE__);
    }
    $LicArray = array();
    if ($duplicate) {
        while ($row = pg_fetch_assoc($result)) {
            $LicArray[$row['fl_pk']] = $row['rf_shortname'];
        }
    } else {
        // do not return duplicated licenses
        while ($row = pg_fetch_assoc($result)) {
            $LicArray[$row['rf_fk']] = $row['rf_shortname'];
        }
    }
    pg_free_result($result);
    return $LicArray;
}
/**
 * \brief get all the copyright for a single file or uploadtree
 * 
 * \param $agent_pk - agent id
 * \param $pfile_pk - pfile id, (if empty, $uploadtree_pk must be given)
 * \param $uploadtree_pk - (used only if $pfile_pk is empty)
 * \param $type - copyright statement/url/email
 * 
 * \return Array of file copyright CopyrightArray[ct_pk] = copyright.content
 * FATAL if neither pfile_pk or uploadtree_pk were passed in
 */
function GetFileCopyrights($agent_pk, $pfile_pk, $uploadtree_pk, $type)
{
    global $PG_CONN;
    if (empty($agent_pk)) {
        Fatal("Missing parameter: agent_pk", __FILE__, __LINE__);
    }
    // if $pfile_pk, then return the copyright for that one file
    if ($pfile_pk) {
        $sql = "SELECT ct_pk, content \n              from copyright\n              where pfile_fk='{$pfile_pk}' and agent_fk={$agent_pk};";
        $result = pg_query($PG_CONN, $sql);
        DBCheckResult($result, $sql, __FILE__, __LINE__);
    } else {
        if ($uploadtree_pk) {
            // Find lft and rgt bounds for this $uploadtree_pk
            $sql = "SELECT lft, rgt, upload_fk FROM uploadtree\n                   WHERE uploadtree_pk = {$uploadtree_pk}";
            $result = pg_query($PG_CONN, $sql);
            DBCheckResult($result, $sql, __FILE__, __LINE__);
            $row = pg_fetch_assoc($result);
            $lft = $row["lft"];
            $rgt = $row["rgt"];
            $upload_pk = $row["upload_fk"];
            pg_free_result($result);
            $typesql = '';
            if ($type && "all" != $type) {
                $typesql = "and type = '{$type}'";
            }
            //  Get the copyright under this $uploadtree_pk
            $sql = "SELECT ct_pk, content from copyright ,\n                  (SELECT distinct(pfile_fk) as PF from uploadtree\n                     where upload_fk={$upload_pk}\n                       and uploadtree.lft BETWEEN {$lft} and {$rgt}) as SS\n              where PF=pfile_fk and agent_fk={$agent_pk} {$typesql};";
            $result = pg_query($PG_CONN, $sql);
            DBCheckResult($result, $sql, __FILE__, __LINE__);
        } else {
            Fatal("Missing function inputs", __FILE__, __LINE__);
        }
    }
    $CopyrightArray = array();
    while ($row = pg_fetch_assoc($result)) {
        $CopyrightArray[$row['ct_pk']] = $row["content"];
    }
    pg_free_result($result);
    return $CopyrightArray;
}
Example #4
0
function dbError($sql)
{
    Fatal("SQL-ERR '" . mysql_error() . "', statement was '" . $sql . "'");
}
Example #5
0
function Main($argv)
{
    if (count($argv) == 1) {
        BenchPrintHelp($argv[0]);
        return 0;
    }
    $mode = null;
    $files = array();
    $locals = array();
    // parse arguments
    $force_reindex = false;
    $view_results = false;
    $unlink_run = false;
    for ($i = 1; $i < count($argv); $i++) {
        $opt = $argv[$i];
        if (substr($opt, 0, 2) == '--') {
            $values = explode('=', substr($opt, 2), 2);
            if (count($values) == 2) {
                $locals[$values[0]] = $values[1];
            }
        } else {
            if ($opt[0] == '-' && $i < count($argv) - 1) {
                $locals[substr($opt, 1)] = $argv[++$i];
            } else {
                if ($mode) {
                    $files[] = $opt;
                } else {
                    switch ($opt) {
                        case 'b':
                        case 'benchmark':
                            $mode = 'benchmark';
                            break;
                        case 'bb':
                            $mode = 'benchmark';
                            $force_reindex = true;
                            break;
                        case 'bv':
                            $mode = 'benchmark';
                            $view_results = true;
                            break;
                        case 'bbv':
                            $mode = 'benchmark';
                            $force_reindex = true;
                            $view_results = true;
                            break;
                        case 'c':
                        case 'compare':
                            $mode = 'compare';
                            break;
                        case 't':
                        case 'try':
                            $mode = 'benchmark';
                            $view_results = true;
                            $unlink_run = true;
                            break;
                        case 'v':
                        case 'view':
                            $mode = 'view';
                            break;
                        default:
                            Fatal("unknown mode '{$opt}' (run bench.php without arguments for help)");
                    }
                }
            }
        }
    }
    global $g_locals;
    PublishLocals($locals, true);
    require_once "helpers.inc";
    // run the command
    if ($mode == 'benchmark') {
        if (count($files) == 0) {
            $avail = AvailableBenchmarks();
            if ($avail) {
                $avail = " ({$avail})";
            }
            Fatal("benchmark command requires a benchmark name{$avail}");
        }
        if (count($files) != 1) {
            Fatal("benchmark command requires exactly one name");
        }
        $path = "bench/{$files['0']}.xml";
        if (!is_readable($path)) {
            Fatal("benchmark scenario '{$path}' is not readable");
        }
        $res = sphBenchmark($files[0], $g_locals, $force_reindex);
        if (!$res) {
            return 1;
        }
        if ($view_results) {
            sphTextReport(sphCompare(array("{$res}.bin", "{$res}.bin")));
        }
        if ($unlink_run) {
            printf("\nunlinked %s\n", $res);
            unlink("{$res}.bin");
            unlink("{$res}.searchd.txt");
        }
    } else {
        if ($mode == 'compare') {
            switch (count($files)) {
                case 1:
                    // pick two freshest by name
                    $runs = PickFreshest($files[0], 2);
                    if (count($runs) != 2) {
                        Fatal("not enough run files for '{$files['0']}' (needed 2, got " . count($runs) . ")");
                    }
                    break;
                case 2:
                    // explicit run names given
                    $runs = array(LookupRun($files[0]), LookupRun($files[1]));
                    break;
                case 3:
                    // explicit run names, shortcut syntax
                    $runs = array(LookupRun("{$files['0']}.{$files['1']}"), LookupRun("{$files['0']}.{$files['2']}"));
                    break;
                default:
                    Fatal("invalid compare syntax (expected 1 to 3 args, got " . count($files) . ")");
            }
            sphTextReport(sphCompare($runs));
        } else {
            if ($mode == 'view') {
                if (count($files) != 1) {
                    Fatal("view command requires exactly one argument");
                }
                $run = LookupRun($files[0]);
                sphTextReport(sphCompare(array($run, $run)));
            } else {
                BenchPrintHelp($argv[0]);
            }
        }
    }
}
Example #6
0
# Only one request can open the session file at a time, so let's close the session here to improve concurrency.
# Any file/page that uses the session must re-open it.
session_write_close();
if (isset($_REQUEST['request'])) {
    foreach (getSkinIncludes('ajax/' . $request . '.php', true, true) as $includeFile) {
        if (!file_exists($includeFile)) {
            Fatal("Request '{$request}' does not exist");
        }
        require_once $includeFile;
    }
    return;
} else {
    if ($includeFiles = getSkinIncludes('views/' . $view . '.php', true, true)) {
        foreach ($includeFiles as $includeFile) {
            if (!file_exists($includeFile)) {
                Fatal("View '{$view}' does not exist");
            }
            require_once $includeFile;
        }
        // If the view overrides $view to 'error', and the user is not logged in, then the
        // issue is probably resolvable by logging in, so provide the opportunity to do so.
        // The login view should handle redirecting to the correct location afterward.
        if ($view == 'error' && !isset($user)) {
            $view = 'login';
            foreach (getSkinIncludes('views/login.php', true, true) as $includeFile) {
                require_once $includeFile;
            }
        }
    }
    // If the view is missing or the view still returned error with the user logged in,
    // then it is not recoverable.
Example #7
0
 $format = $_REQUEST['format'];
 switch ($format) {
     case 'text':
         $exportExt = "txt";
         break;
     case 'tsv':
         $exportExt = "tsv";
         break;
     case 'html':
         $exportExt = "html";
         break;
     case 'xml':
         $exportExt = "xml";
         break;
     default:
         Fatal("Unrecognised log export format '{$format}'");
 }
 $exportFile = "zm-log.{$exportExt}";
 $exportPath = "temp/zm-log-{$exportKey}.{$exportExt}";
 header("Pragma: public");
 header("Expires: 0");
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 header("Cache-Control: private", false);
 // required by certain browsers
 header("Content-Description: File Transfer");
 header('Content-Disposition: attachment; filename="' . $exportFile . '"');
 header("Content-Transfer-Encoding: binary");
 header("Content-Type: application/force-download");
 header("Content-Length: " . filesize($exportPath));
 readfile($exportPath);
 exit(0);
Example #8
0
# Only one request can open the session file at a time, so let's close the session here to improve concurrency.
# Any file/page that uses the session must re-open it.
session_write_close();
if (isset($_REQUEST['request'])) {
    foreach (getSkinIncludes('ajax/' . $request . '.php', true, true) as $includeFile) {
        if (!file_exists($includeFile)) {
            Fatal("Request '{$request}' does not exist");
        }
        require_once $includeFile;
    }
    return;
} else {
    if ($includeFiles = getSkinIncludes('views/' . $view . '.php', true, true)) {
        foreach ($includeFiles as $includeFile) {
            if (!file_exists($includeFile)) {
                Fatal("View '{$view}' does not exist: " . $includeFile);
            }
            require_once $includeFile;
        }
        // If the view overrides $view to 'error', and the user is not logged in, then the
        // issue is probably resolvable by logging in, so provide the opportunity to do so.
        // The login view should handle redirecting to the correct location afterward.
        if ($view == 'error' && !isset($user)) {
            $view = 'login';
            foreach (getSkinIncludes('views/login.php', true, true) as $includeFile) {
                require_once $includeFile;
            }
        }
    }
    // If the view is missing or the view still returned error with the user logged in,
    // then it is not recoverable.
Example #9
0
    }
} else {
    // Not so simple version
    if (!function_exists("imagecreatefromjpeg")) {
        Warning("The imagecreatefromjpeg function is not present, php-gd not installed?");
    }
    if (!$errorText) {
        if (!($image = imagecreatefromjpeg(ZM_DIR_EVENTS . '/' . $path))) {
            $errorText = "Can't load image";
            $error = error_get_last();
            Error($error['message']);
        }
    }
    if ($errorText) {
        if (!($image = imagecreatetruecolor(160, 120))) {
            $error = error_get_last();
            Error($error['message']);
        }
        if (!($textColor = imagecolorallocate($image, 255, 0, 0))) {
            $error = error_get_last();
            Error($error['message']);
        }
        if (!imagestring($image, 1, 20, 60, $errorText, $textColor)) {
            $error = error_get_last();
            Error($error['message']);
        }
        Fatal($errorText . " - " . $path);
    }
    imagejpeg($image);
    imagedestroy($image);
}
function _extractDatetimeRange(&$node, &$minTime, &$maxTime, &$expandable, $subOr)
{
    $pruned = $leftPruned = $rightPruned = false;
    if ($node) {
        if (isset($node['left']) && isset($node['right'])) {
            if ($node['data']['type'] == 'cnj' && $node['data']['value'] == 'or') {
                $subOr = true;
            } elseif (!empty($node['left']['data']['dtAttr'])) {
                if ($subOr) {
                    $expandable = false;
                } elseif ($node['data']['type'] == 'op') {
                    if ($node['data']['value'] == '>' || $node['data']['value'] == '>=') {
                        if (!$minTime || $minTime > $node['right']['data']['sqlValue']) {
                            $minTime = $node['right']['data']['value'];
                            return true;
                        }
                    }
                    if ($node['data']['value'] == '<' || $node['data']['value'] == '<=') {
                        if (!$maxTime || $maxTime < $node['right']['data']['sqlValue']) {
                            $maxTime = $node['right']['data']['value'];
                            return true;
                        }
                    }
                } else {
                    Fatal("Unexpected node type '" . $node['data']['type'] . "'");
                }
                return false;
            }
            $leftPruned = _extractDatetimeRange($node['left'], $minTime, $maxTime, $expandable, $subOr);
            $rightPruned = _extractDatetimeRange($node['right'], $minTime, $maxTime, $expandable, $subOr);
            if ($leftPruned && $rightPruned) {
                $pruned = true;
            } elseif ($leftPruned) {
                $node = $node['right'];
            } elseif ($rightPruned) {
                $node = $node['left'];
            }
        }
    }
    return $pruned;
}
Example #11
0
     if ($ctrlCommand) {
         $socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
         if ($socket < 0) {
             Fatal("socket_create() failed: " . socket_strerror($socket));
         }
         $sockFile = ZM_PATH_SOCKS . '/zmcontrol-' . $monitor['Id'] . '.sock';
         if (@socket_connect($socket, $sockFile)) {
             $options = array();
             foreach (explode(" ", $ctrlCommand) as $option) {
                 if (preg_match('/--([^=]+)(?:=(.+))?/', $option, $matches)) {
                     $options[$matches[1]] = $matches[2] ? $matches[2] : 1;
                 }
             }
             $optionString = jsonEncode($options);
             if (!socket_write($socket, $optionString)) {
                 Fatal("Can't write to control socket: " . socket_strerror(socket_last_error($socket)));
             }
             socket_close($socket);
         } else {
             $ctrlCommand .= " --id=" . $monitor['Id'];
             // Can't connect so use script
             $ctrlOutput = exec(escapeshellcmd($ctrlCommand));
         }
     }
 } elseif ($action == "settings") {
     $args = " -m " . escapeshellarg($mid);
     $args .= " -B" . escapeshellarg($_REQUEST['newBrightness']);
     $args .= " -C" . escapeshellarg($_REQUEST['newContrast']);
     $args .= " -H" . escapeshellarg($_REQUEST['newHue']);
     $args .= " -O" . escapeshellarg($_REQUEST['newColour']);
     $zmuCommand = getZmuCommand($args);
Example #12
0
 /**
  * \brief This function returns the output html
  */
 function Output()
 {
     global $PG_CONN;
     global $Plugins;
     if ($this->State != PLUGIN_STATE_READY) {
         return 0;
     }
     $V = "";
     $folder_pk = GetParm("folder", PARM_INTEGER);
     $Upload = GetParm("upload", PARM_INTEGER);
     // upload_pk to browse
     $Item = GetParm("item", PARM_INTEGER);
     // uploadtree_pk to browse
     /* check permission if $Upload is given */
     if (!empty($Upload)) {
         $UploadPerm = GetUploadPerm($Upload);
         if ($UploadPerm < PERM_READ) {
             $text = _("Permission Denied");
             echo "<h2>{$text}<h2>";
             return;
         }
     }
     /* kludge for plugins not supplying a folder parameter.
      * Find what folder this upload is in.  Error if in multiple folders.
      */
     if (empty($folder_pk)) {
         if (empty($Upload)) {
             $folder_pk = GetUserRootFolder();
         } else {
             /* Make sure the upload record exists */
             $sql = "select upload_pk from upload where upload_pk={$Upload}";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             if (pg_num_rows($result) < 1) {
                 echo "This upload no longer exists on this system.";
                 return;
             }
             $sql = "select parent_fk from foldercontents where child_id={$Upload} and foldercontents_mode=2";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             if (pg_num_rows($result) > 1) {
                 Fatal("Upload {$Upload} found in multiple folders.", __FILE__, __LINE__);
             }
             if (pg_num_rows($result) < 1) {
                 Fatal("Upload {$Upload} missing from foldercontents.", __FILE__, __LINE__);
             }
             $row = pg_fetch_assoc($result);
             $folder_pk = $row['parent_fk'];
             pg_free_result($result);
         }
     }
     $Folder = $folder_pk;
     $Show = 'detail';
     // always use detail
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             /************************/
             /* Show the folder path */
             /************************/
             $uploadtree_tablename = "";
             if (!empty($Item)) {
                 /* Make sure the item is not a file */
                 $sql = "SELECT ufile_mode, upload_fk FROM uploadtree WHERE uploadtree_pk = '{$Item}';";
                 $result = pg_query($PG_CONN, $sql);
                 DBCheckResult($result, $sql, __FILE__, __LINE__);
                 $row = pg_fetch_assoc($result);
                 pg_free_result($result);
                 $Upload = $row['upload_fk'];
                 $UploadPerm = GetUploadPerm($Upload);
                 if ($UploadPerm < PERM_READ) {
                     $text = _("Permission Denied");
                     echo "<h2>{$text}<h2>";
                     return;
                 }
                 if (!Iscontainer($row['ufile_mode'])) {
                     /* Not a container! */
                     $View =& $Plugins[plugin_find_id("view")];
                     if (!empty($View)) {
                         return $View->ShowView(NULL, "browse");
                     }
                 }
                 $V .= "<font class='text'>\n";
                 $uploadtree_tablename = GetUploadtreeTableName($row['upload_fk']);
                 $V .= Dir2Browse($this->Name, $Item, NULL, 1, "Browse", -1, '', '', $uploadtree_tablename) . "\n";
             } else {
                 if (!empty($Upload)) {
                     $V .= "<font class='text'>\n";
                     $uploadtree_tablename = GetUploadtreeTableName($Upload);
                     $V .= Dir2BrowseUpload($this->Name, $Upload, NULL, 1, "Browse", $uploadtree_tablename) . "\n";
                 } else {
                     $V .= "<font class='text'>\n";
                 }
             }
             /******************************/
             /* Get the folder description */
             /******************************/
             if (!empty($Upload)) {
                 if (empty($Item)) {
                     $sql = "select uploadtree_pk from uploadtree\n                where parent is NULL and upload_fk={$Upload} ";
                     $result = pg_query($PG_CONN, $sql);
                     DBCheckResult($result, $sql, __FILE__, __LINE__);
                     if (pg_num_rows($result)) {
                         $row = pg_fetch_assoc($result);
                         $Item = $row['uploadtree_pk'];
                     } else {
                         $text = _("Missing upload tree parent for upload");
                         $V .= "<hr><h2>{$text} {$Upload}</h2><hr>";
                         break;
                     }
                     pg_free_result($result);
                 }
                 $V .= $this->ShowItem($Upload, $Item, $Show, $Folder, $uploadtree_tablename);
             } else {
                 $V .= $this->ShowFolder($Folder, $Show);
             }
             $V .= "</font>\n";
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print "{$V}";
     return;
 }
Example #13
0
function sendControlCommand($mid, $command)
{
    // Either connects to running zmcontrol.pl or runs zmcontrol.pl to send the command.
    $socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
    if ($socket < 0) {
        Fatal("socket_create() failed: " . socket_strerror($socket));
    }
    $sockFile = ZM_PATH_SOCKS . '/zmcontrol-' . $mid . '.sock';
    if (@socket_connect($socket, $sockFile)) {
        $options = array();
        foreach (explode(" ", $command) as $option) {
            if (preg_match('/--([^=]+)(?:=(.+))?/', $option, $matches)) {
                $options[$matches[1]] = $matches[2] ? $matches[2] : 1;
            }
        }
        $optionString = jsonEncode($options);
        if (!socket_write($socket, $optionString)) {
            Fatal("Can't write to control socket: " . socket_strerror(socket_last_error($socket)));
        }
        socket_close($socket);
    } else {
        if ($command != 'quit') {
            $command .= ' --id=' . $mid;
            // Can't connect so use script
            $ctrlOutput = exec(escapeshellcmd($command));
        }
    }
}
function exportEvents($eids, $exportDetail, $exportFrames, $exportImages, $exportVideo, $exportMisc, $exportFormat)
{
    if (canView('Events') && !empty($eids)) {
        $export_root = "zmExport";
        $export_listFile = "zmFileList.txt";
        $exportFileList = array();
        $html_eventMaster = '';
        if (is_array($eids)) {
            foreach ($eids as $eid) {
                $exportFileList = array_merge($exportFileList, exportFileList($eid, $exportDetail, $exportFrames, $exportImages, $exportVideo, $exportMisc));
            }
        } else {
            $eid = $eids;
            $exportFileList = exportFileList($eid, $exportDetail, $exportFrames, $exportImages, $exportVideo, $exportMisc);
        }
        // create an master image slider
        if ($exportImages) {
            if (!is_array($eids)) {
                $eids = array($eids);
            }
            $monitorPath = 'events/';
            $html_eventMaster = 'zmEventImagesMaster_' . date('Ymd_His') . '.html';
            if (!($fp = fopen($monitorPath . "/" . $html_eventMaster, "w"))) {
                Fatal("Can't open event images export file '{$html_eventMaster}'");
            }
            fwrite($fp, exportEventImagesMaster($eids));
            fclose($fp);
            $exportFileList[] = $monitorPath . "/" . $html_eventMaster;
        }
        $listFile = "temp/" . $export_listFile;
        if (!($fp = fopen($listFile, "w"))) {
            Fatal("Can't open event export list file '{$listFile}'");
        }
        foreach ($exportFileList as $exportFile) {
            fwrite($fp, "{$exportFile}\n");
        }
        fclose($fp);
        $archive = "";
        if ($exportFormat == "tar") {
            $archive = "temp/" . $export_root . ".tar.gz";
            @unlink($archive);
            $command = "tar --create --gzip --file={$archive} --files-from={$listFile}";
            exec(escapeshellcmd($command), $output, $status);
            if ($status) {
                Error("Command '{$command}' returned with status {$status}");
                if ($output[0]) {
                    Error("First line of output is '" . $output[0] . "'");
                }
                return false;
            }
        } elseif ($exportFormat == "zip") {
            $archive = "temp/zm_export.zip";
            $archive = "temp/" . $export_root . ".zip";
            @unlink($archive);
            $command = "cat " . escapeshellarg($listFile) . " | zip -q " . escapeshellarg($archive) . " -@";
            //cat zmFileList.txt | zip -q zm_export.zip -@
            //-bash: zip: command not found
            exec($command, $output, $status);
            if ($status) {
                Error("Command '{$command}' returned with status {$status}");
                if ($output[0]) {
                    Error("First line of output is '" . $output[0] . "'");
                }
                return false;
            }
        }
        //clean up temporary files
        if (!empty($html_eventMaster)) {
            unlink($monitorPath . '/' . $html_eventMaster);
        }
    }
    return $archive;
}
/**
 * \brief Check if a bucket_pk is found in a tree 
 * for a given nomos and bucket agent.
 * 
 * \param  $bucket_pk
 * \param  $uploadtree_pk  
 * 
 * \return True if bucket_pk is found in the tree
 *   False if not
 */
function BucketInTree($bucket_pk, $uploadtree_pk)
{
    global $PG_CONN;
    $BuckArray = array();
    if (empty($bucket_pk) || empty($uploadtree_pk)) {
        Fatal("Missing parameter: bucket_pk: {$bucket_pk}, uploadtree_pk: {$uploadtree_pk}<br>", __FILE__, __LINE__);
    }
    /* Find lft and rgt bounds for this $uploadtree_pk  */
    $sql = "SELECT lft,rgt, upload_fk FROM uploadtree WHERE uploadtree_pk = {$uploadtree_pk}";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    if (pg_num_rows($result) < 1) {
        pg_free_result($result);
        return False;
    }
    $row = pg_fetch_assoc($result);
    $lft = $row["lft"];
    $rgt = $row["rgt"];
    $upload_fk = $row["upload_fk"];
    pg_free_result($result);
    /* search for bucket in tree */
    $sql = "SELECT bucket_fk from bucket_file, \n            (SELECT distinct(pfile_fk) as PF from uploadtree \n               where uploadtree.lft BETWEEN {$lft} and {$rgt} and upload_fk='{$upload_fk}') as SS\n          where PF=pfile_fk and bucket_fk='{$bucket_pk}' limit 1";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    if (pg_num_rows($result) == 0) {
        $rv = False;
    } else {
        $rv = True;
    }
    pg_free_result($result);
    return $rv;
}
    /**
    * @brief Output(): 
    * Requires:\n
           filter: optional filter to apply\n
           item1:  uploadtree_pk of the column 1 tree\n
           item2:  uploadtree_pk of the column 2 tree\n
           freeze: column number (1 or 2) to freeze
    */
    function Output()
    {
        if ($this->State != PLUGIN_STATE_READY) {
            return 0;
        }
        $uTime = microtime(true);
        $V = "";
        /**/
        $UpdCache = GetParm("updcache", PARM_INTEGER);
        /* Remove "updcache" from the GET args and set $this->UpdCache
         * This way all the url's based on the input args won't be
         * polluted with updcache
         * Use Traceback_parm_keep to ensure that all parameters are in order
         */
        $CacheKey = "?mod=" . $this->Name . Traceback_parm_keep(array("item1", "item2", "filter", "col", "freeze", "itemf"));
        if ($UpdCache) {
            $UpdCache = $_GET['updcache'];
            $_SERVER['REQUEST_URI'] = preg_replace("/&updcache=[0-9]*/", "", $_SERVER['REQUEST_URI']);
            unset($_GET['updcache']);
            $V = ReportCachePurgeByKey($CacheKey);
        } else {
            $V = ReportCacheGet($CacheKey);
        }
        /**/
        if (empty($V)) {
            $filter = GetParm("filter", PARM_STRING);
            if (empty($filter)) {
                $filter = "none";
            }
            $FreezeCol = GetParm("freeze", PARM_INTEGER);
            // which column to freeze?  1 or 2 or null
            $ClickedCol = GetParm("col", PARM_INTEGER);
            // which column was clicked on?  1 or 2 or null
            $ItemFrozen = GetParm("itemf", PARM_INTEGER);
            // frozen item or null
            $in_uploadtree_pk1 = GetParm("item1", PARM_INTEGER);
            $in_uploadtree_pk2 = GetParm("item2", PARM_INTEGER);
            if (empty($in_uploadtree_pk1) || empty($in_uploadtree_pk2)) {
                Fatal("Bad input parameters.  Both item1 and item2 must be specified.", __FILE__, __LINE__);
            }
            /* If you click on a item in a frozen column, then you are a dope so ignore $ItemFrozen */
            if ($FreezeCol == $ClickedCol) {
                $ItemFrozen = 0;
                $FreezeCol = 0;
            }
            /* Check item1 upload permission */
            $Item1Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$in_uploadtree_pk1}");
            $UploadPerm = GetUploadPerm($Item1Row['upload_fk']);
            if ($UploadPerm < PERM_READ) {
                $text = _("Permission Denied");
                echo "<h2>{$text} item 1<h2>";
                return;
            }
            /* Check item2 upload permission */
            $Item2Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$in_uploadtree_pk2}");
            $UploadPerm = GetUploadPerm($Item2Row['upload_fk']);
            if ($UploadPerm < PERM_READ) {
                $text = _("Permission Denied");
                echo "<h2>{$text} item 2<h2>";
                return;
            }
            $uploadtree_pk1 = $in_uploadtree_pk1;
            $uploadtree_pk2 = $in_uploadtree_pk2;
            if ($FreezeCol == 1) {
                $uploadtree_pk1 = $ItemFrozen;
            } else {
                if ($FreezeCol == 2) {
                    $uploadtree_pk2 = $ItemFrozen;
                }
            }
            $newURL = Traceback_dir() . "?mod=" . $this->Name . "&item1={$uploadtree_pk1}&item2={$uploadtree_pk2}";
            if (!empty($filter)) {
                $newURL .= "&filter={$filter}";
            }
            // rewrite page with new uploadtree_pks */
            if ($uploadtree_pk1 != $in_uploadtree_pk1 || $uploadtree_pk2 != $in_uploadtree_pk2) {
                print <<<JSOUT
<script type="text/javascript">
  window.location.assign('{$newURL}');
</script>
JSOUT;
            }
            $TreeInfo1 = $this->GetTreeInfo($uploadtree_pk1);
            $TreeInfo2 = $this->GetTreeInfo($uploadtree_pk2);
            $ErrText = _("No license data for tree %d.  Use Jobs > Agents to schedule a license scan.");
            $ErrMsg = '';
            if ($TreeInfo1['agent_pk'] == 0) {
                $ErrMsg = sprintf($ErrText, 1);
            } else {
                if ($TreeInfo2['agent_pk'] == 0) {
                    $ErrMsg = sprintf($ErrText, 2);
                } else {
                    $BucketDefArray = initBucketDefArray($TreeInfo1['bucketpool_pk']);
                    /* Get list of children */
                    $Children1 = GetNonArtifactChildren($uploadtree_pk1);
                    $Children2 = GetNonArtifactChildren($uploadtree_pk2);
                    /* Add fuzzyname to children */
                    FuzzyName($Children1);
                    // add fuzzyname to children
                    FuzzyName($Children2);
                    // add fuzzyname to children
                    /* add element licstr to children */
                    $this->AddBucketStr($TreeInfo1, $Children1, $BucketDefArray);
                    $this->AddBucketStr($TreeInfo2, $Children2, $BucketDefArray);
                    /* Master array of children, aligned.   */
                    $Master = MakeMaster($Children1, $Children2);
                    /* add linkurl to children */
                    FileList($Master, $TreeInfo1['agent_pk'], $TreeInfo2['agent_pk'], $filter, $this, $uploadtree_pk1, $uploadtree_pk2);
                    /* Apply filter */
                    $this->FilterChildren($filter, $Master, $BucketDefArray);
                }
            }
            switch ($this->OutputType) {
                case "XML":
                    break;
                case "HTML":
                    if ($ErrMsg) {
                        $V .= $ErrMsg;
                    } else {
                        $V .= $this->HTMLout($Master, $uploadtree_pk1, $uploadtree_pk2, $in_uploadtree_pk1, $in_uploadtree_pk2, $filter, $TreeInfo1, $TreeInfo2, $BucketDefArray);
                    }
                    break;
                case "Text":
                    break;
                default:
            }
            $Cached = false;
        } else {
            $Cached = true;
        }
        if (!$this->OutputToStdout) {
            return $V;
        }
        print "{$V}";
        $Time = microtime(true) - $uTime;
        // convert usecs to secs
        $text = _("Elapsed time: %.2f seconds");
        printf("<small>{$text}</small>", $Time);
        /**/
        if ($Cached) {
            $text = _("cached");
            $text1 = _("Update");
            echo " <i>{$text}</i>   <a href=\"{$_SERVER['REQUEST_URI']}&updcache=1\"> {$text1} </a>";
        } else {
            //  Cache Report if this took longer than 1/2 second
            if ($Time > 0.5) {
                ReportCachePut($CacheKey, $V);
            }
        }
        /**/
        return;
    }
Example #17
0
function checkJsonError($value)
{
    if (function_exists('json_last_error')) {
        $value = var_export($value, true);
        switch (json_last_error()) {
            case JSON_ERROR_DEPTH:
                Fatal("Unable to decode JSON string '{$value}', maximum stack depth exceeded");
            case JSON_ERROR_CTRL_CHAR:
                Fatal("Unable to decode JSON string '{$value}', unexpected control character found");
            case JSON_ERROR_STATE_MISMATCH:
                Fatal("Unable to decode JSON string '{$value}', invalid or malformed JSON");
            case JSON_ERROR_SYNTAX:
                Fatal("Unable to decode JSON string '{$value}', syntax error");
            default:
                Fatal("Unable to decode JSON string '{$value}', unexpected error " . json_last_error());
            case JSON_ERROR_NONE:
                break;
        }
    }
}
Example #18
0
function dbFetchAll($sql, $col = false, $params = NULL)
{
    $result = dbQuery($sql, $params);
    if (!$result) {
        Fatal("SQL-ERR dbFetchAll no result, statement was '" . $sql . "'" . ($params ? 'params: ' . join(',', $params) : ''));
        return false;
    }
    $dbRows = array();
    while ($dbRow = $result->fetch(PDO::FETCH_ASSOC)) {
        $dbRows[] = $col ? $dbRow[$col] : $dbRow;
    }
    return $dbRows;
}
Example #19
0
 public function logPrint($level, $string, $file = NULL, $line = NULL)
 {
     if ($level <= $this->effectiveLevel) {
         $string = preg_replace('/[\\r\\n]+$/', '', $string);
         $code = self::$codes[$level];
         $time = gettimeofday();
         $message = sprintf("%s.%06d %s[%d].%s [%s]", strftime("%x %H:%M:%S", $time['sec']), $time['usec'], $this->id, getmypid(), $code, $string);
         if (is_null($file)) {
             if ($this->useErrorLog || $this->databaseLevel > self::NOLOG) {
                 $backTrace = debug_backtrace();
                 $file = $backTrace[1]['file'];
                 $line = $backTrace[1]['line'];
                 if ($this->hasTerm) {
                     $rootPath = getcwd();
                 } else {
                     $rootPath = $_SERVER['DOCUMENT_ROOT'];
                 }
                 $file = preg_replace('/^' . addcslashes($rootPath, '/') . '\\/?/', '', $file);
             }
         }
         if ($this->useErrorLog) {
             $message .= " at " . $file . " line " . $line;
         } else {
             $message = $message;
         }
         if ($level <= $this->termLevel) {
             if ($this->hasTerm) {
                 print $message . "\n";
             } else {
                 print preg_replace("/\n/", '<br/>', htmlspecialchars($message)) . "<br/>";
             }
         }
         if ($level <= $this->fileLevel) {
             if ($this->useErrorLog) {
                 if (!error_log($message . "\n", 3, $this->logFile)) {
                     if (strnatcmp(phpversion(), '5.2.0') >= 0) {
                         $error = error_get_last();
                         trigger_error("Can't write to log file '" . $this->logFile . "': " . $error['message'] . " @ " . $error['file'] . "/" . $error['line'], E_USER_ERROR);
                     }
                 }
             } elseif ($this->logFd) {
                 fprintf($this->logFd, $message . "\n");
             }
         }
         $message = $code . " [" . $string . "]";
         if ($level <= $this->syslogLevel) {
             syslog(self::$syslogPriorities[$level], $message);
         }
         if ($level <= $this->databaseLevel) {
             try {
                 global $dbConn;
                 $sql = "INSERT INTO Logs ( TimeKey, Component, Pid, Level, Code, Message, File, Line ) values ( ?, ?, ?, ?, ?, ?, ?, ? )";
                 $stmt = $dbConn->prepare($sql);
                 $result = $stmt->execute(array(sprintf("%d.%06d", $time['sec'], $time['usec']), $this->id, getmypid(), $level, $code, $string, $file, $line));
             } catch (PDOException $ex) {
                 $this->databaseLevel = self::NOLOG;
                 Fatal("Can't write log entry '{$sql}': " . $ex->getMessage());
             }
         }
         // This has to be last as trigger_error can be fatal
         if ($level <= $this->weblogLevel) {
             if ($this->useErrorLog) {
                 error_log($message, 0);
             } else {
                 trigger_error($message, self::$phpErrorLevels[$level]);
             }
         }
     }
 }
Example #20
0
                $arp_command = '/usr/sbin/arp -a';
            }
        } else {
            $arp_command = $output[0] . " -a";
        }
    } else {
        $arp_command = $output[0] . " -a";
    }
} else {
    $arp_command = ZM_PATH_ARP;
}
// Now that we know where arp is, call it using the full path
unset($output);
$result = exec(escapeshellcmd($arp_command), $output, $status);
if ($status) {
    Fatal("Unable to probe network cameras, status is '{$status}'");
}
foreach ($output as $line) {
    if (!preg_match('/^.*([\\d.]+).*([0-9a-f:]+).*/', $line, $matches)) {
        continue;
    }
    $ip = $matches[1];
    $host = $ip;
    $mac = $matches[2];
    //echo "I:$ip, H:$host, M:$mac<br/>";
    $macRoot = substr($mac, 0, 8);
    if (isset($macBases[$macRoot])) {
        $macBase = $macBases[$macRoot];
        $camera = call_user_func($macBase['probeFunc'], $ip);
        $sourceDesc = htmlspecialchars(serialize($camera['monitor']));
        $sourceString = $camera['model'] . ' @ ' . $host;
Example #21
0
    public function htmlContent()
    {
        $filter = GetParm("filter", PARM_STRING);
        if (empty($filter)) {
            $filter = "none";
        }
        $FreezeCol = GetParm("freeze", PARM_INTEGER);
        // which column to freeze?  1 or 2 or null
        $ClickedCol = GetParm("col", PARM_INTEGER);
        // which column was clicked on?  1 or 2 or null
        $ItemFrozen = GetParm("itemf", PARM_INTEGER);
        // frozen item or null
        $in_uploadtree_pk1 = GetParm("item1", PARM_INTEGER);
        $in_uploadtree_pk2 = GetParm("item2", PARM_INTEGER);
        if (empty($in_uploadtree_pk1) || empty($in_uploadtree_pk2)) {
            Fatal("Bad input parameters.  Both item1 and item2 must be specified.", __FILE__, __LINE__);
        }
        /* If you click on a item in a frozen column, then you are a dope so ignore $ItemFrozen */
        if ($FreezeCol == $ClickedCol) {
            $ItemFrozen = 0;
            $FreezeCol = 0;
        }
        /* @var $uploadDao UploadDao */
        $uploadDao = $GLOBALS['container']->get('dao.upload');
        /* Check item1 upload permission */
        $Item1Row = $uploadDao->getUploadEntry($in_uploadtree_pk1);
        if (!$uploadDao->isAccessible($Item1Row['upload_fk'], Auth::getGroupId())) {
            $text = _("Permission Denied");
            return "<h2>{$text} item 1</h2>";
        }
        /* Check item2 upload permission */
        $Item2Row = $uploadDao->getUploadEntry($in_uploadtree_pk2);
        if (!$uploadDao->isAccessible($Item2Row['upload_fk'], Auth::getGroupId())) {
            $text = _("Permission Denied");
            return "<h2>{$text} item 2</h2>";
        }
        $uploadtree_pk1 = $in_uploadtree_pk1;
        $uploadtree_pk2 = $in_uploadtree_pk2;
        if ($FreezeCol == 1) {
            $uploadtree_pk1 = $ItemFrozen;
        } else {
            if ($FreezeCol == 2) {
                $uploadtree_pk2 = $ItemFrozen;
            }
        }
        $newURL = Traceback_dir() . "?mod=" . $this->Name . "&item1={$uploadtree_pk1}&item2={$uploadtree_pk2}";
        if (!empty($filter)) {
            $newURL .= "&filter={$filter}";
        }
        // rewrite page with new uploadtree_pks */
        if ($uploadtree_pk1 != $in_uploadtree_pk1 || $uploadtree_pk2 != $in_uploadtree_pk2) {
            print <<<JSOUT
<script type="text/javascript">
  window.location.assign('{$newURL}');
</script>
JSOUT;
        }
        $TreeInfo1 = $this->GetTreeInfo($uploadtree_pk1);
        $TreeInfo2 = $this->GetTreeInfo($uploadtree_pk2);
        $ErrText = _("No license data for tree %d.  Use Jobs > Agents to schedule a license scan.");
        $ErrMsg = '';
        if ($TreeInfo1['agent_pk'] == 0) {
            $ErrMsg = sprintf($ErrText, 1);
        } else {
            if ($TreeInfo2['agent_pk'] == 0) {
                $ErrMsg = sprintf($ErrText, 2);
            } else {
                $BucketDefArray1 = initBucketDefArray($TreeInfo1['bucketpool_pk']);
                $BucketDefArray2 = initBucketDefArray($TreeInfo2['bucketpool_pk']);
                $BucketDefArray = $BucketDefArray1 + $BucketDefArray2;
                /* Get list of children */
                $Children1 = GetNonArtifactChildren($uploadtree_pk1);
                $Children2 = GetNonArtifactChildren($uploadtree_pk2);
                /* Add fuzzyname to children */
                FuzzyName($Children1);
                // add fuzzyname to children
                FuzzyName($Children2);
                // add fuzzyname to children
                /* add element licstr to children */
                $this->AddBucketStr($TreeInfo1, $Children1, $BucketDefArray);
                $this->AddBucketStr($TreeInfo2, $Children2, $BucketDefArray);
                /* Master array of children, aligned.   */
                $Master = MakeMaster($Children1, $Children2);
                /* add linkurl to children */
                FileList($Master, $TreeInfo1['agent_pk'], $TreeInfo2['agent_pk'], $filter, $this, $uploadtree_pk1, $uploadtree_pk2);
                /* Apply filter */
                $this->FilterChildren($filter, $Master, $BucketDefArray);
            }
        }
        if ($this->OutputType == 'HTML') {
            if ($ErrMsg) {
                $V .= $ErrMsg;
            } else {
                $V .= $this->HTMLout($Master, $uploadtree_pk1, $uploadtree_pk2, $in_uploadtree_pk1, $in_uploadtree_pk2, $filter, $TreeInfo1, $TreeInfo2, $BucketDefArray);
            }
        }
        return $V;
    }