Esempio n. 1
0
 /**
  * overwrite __construct() function
  * @return void
  */
 function __construct()
 {
     # these variables are assumed to be globally available
     global $logging;
     # set global references for this object
     $this->_log =& $logging;
     $this->reset();
     $this->_log->debug("constructed new ListState object");
 }
Esempio n. 2
0
 static function initialize($settings, $version = "-")
 {
     self::$version = $version;
     self::$debug = (isset($settings) and isset($settings["debug"]) and $settings['debug'] === TRUE);
     self::$firebug = (isset($settings) and isset($settings["firebug_logging"]) and $settings['firebug_logging'] === TRUE);
     if (self::$firebug) {
         require_once 'FirePHPCore/fb.php';
         FB::setEnabled(true);
     }
 }
Esempio n. 3
0
 public function getTimelineDatatableAction()
 {
     $start = microtime(true);
     $data = Application_Model_Preference::getTimelineDatatableSetting();
     if (!is_null($data)) {
         $this->view->settings = $data;
     }
     $end = microtime(true);
     Logging::debug("getting timeline datatables info took:");
     Logging::debug(floatval($end) - floatval($start));
 }
Esempio n. 4
0
 /**
  * check if given table exists in database
  * @param string $table name of table
  * @return bool indicates if given table exists in database
  */
 function table_exists($table)
 {
     $query = "SHOW TABLES";
     $this->_log->debug("check if table exists (table=" . $table . ")");
     $result = $this->query($query);
     while ($row = $this->fetch($result)) {
         if ($row[0] == $table) {
             return TRUE;
         }
     }
     return FALSE;
 }
Esempio n. 5
0
 private function generateToken($action, $user_id)
 {
     $salt = md5("pro");
     $token = self::generateRandomString();
     $info = new CcSubjsToken();
     $info->setDbUserId($user_id);
     $info->setDbAction($action);
     $info->setDbToken(sha1($token . $salt));
     $info->setDbCreated(gmdate('Y-m-d H:i:s'));
     $info->save();
     Logging::debug("generated token {$token}");
     return $token;
 }
 public function dispatchLoopShutdown()
 {
     if (Application_Model_RabbitMq::$doPush) {
         $md = array('schedule' => Application_Model_Schedule::getSchedule());
         Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
         if (!isset($_SERVER['AIRTIME_SRV'])) {
             Application_Model_RabbitMq::SendMessageToShowRecorder("update_recorder_schedule");
         }
     }
     if (memory_get_peak_usage() > 30 * pow(2, 20)) {
         Logging::debug("Peak memory usage: " . memory_get_peak_usage() / 1000000 . " MB while accessing URI " . $_SERVER['REQUEST_URI']);
         Logging::debug("Should try to keep memory footprint under 25 MB");
     }
 }
Esempio n. 7
0
 public function hasBeenUpdatedSince($timestamp, $instances)
 {
     $outdated = false;
     $shows = Application_Model_Show::getShows($this->startDT, $this->endDT);
     $include = array();
     if ($this->opts["showFilter"] !== 0) {
         $include[] = $this->opts["showFilter"];
     } elseif ($this->opts["myShows"] === 1) {
         $include = $this->getUsersShows();
     }
     $currentInstances = array();
     foreach ($shows as $show) {
         if (empty($include) || in_array($show["show_id"], $include)) {
             $currentInstances[] = $show["instance_id"];
             if (isset($show["last_scheduled"])) {
                 $dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC"));
             } else {
                 $dt = new DateTime($show["created"], new DateTimeZone("UTC"));
             }
             //check if any of the shows have a more recent timestamp.
             $showTimeStamp = intval($dt->format("U"));
             if ($timestamp < $showTimeStamp) {
                 $outdated = true;
                 break;
             }
         }
     }
     //see if the displayed show instances have changed. (deleted,
     //empty schedule etc)
     if ($outdated === false && count($instances) !== count($currentInstances)) {
         Logging::debug("show instances have changed.");
         $outdated = true;
     }
     return $outdated;
 }
Esempio n. 8
0
 public static function findEntries($con, $displayColumns, $fromTable, $data, $dataProp = "aaData")
 {
     $librarySetting = Application_Model_Preference::getCurrentLibraryTableColumnMap();
     //$displayColumns[] = 'owner';
     // map that maps original column position to db name
     $current2dbname = array();
     // array of search terms
     $orig2searchTerm = array();
     foreach ($data as $key => $d) {
         if (strstr($key, "mDataProp_")) {
             list($dump, $index) = explode("_", $key);
             $current2dbname[$index] = $d;
         } elseif (strstr($key, "sSearch_")) {
             list($dump, $index) = explode("_", $key);
             $orig2searchTerm[$index] = $d;
         }
     }
     // map that maps dbname to searchTerm
     $dbname2searchTerm = array();
     foreach ($current2dbname as $currentPos => $dbname) {
         $new_index = $librarySetting($currentPos);
         // TODO : Fix this retarded hack later. Just a band aid for
         // now at least we print some warnings so that we don't
         // forget about this -- cc-4462
         if (array_key_exists($new_index, $orig2searchTerm)) {
             $dbname2searchTerm[$dbname] = $orig2searchTerm[$new_index];
         } else {
             Logging::warn("Trying to reorder to unknown index\n                    printing as much debugging as possible...");
             $debug = array('$new_index' => $new_index, '$currentPos' => $currentPos, '$orig2searchTerm' => $orig2searchTerm);
             Logging::warn($debug);
         }
     }
     $where = array();
     /* Holds the parameters for binding after the statement has been
        prepared */
     $params = array();
     if (isset($data['advSearch']) && $data['advSearch'] === 'true') {
         $advancedWhere = self::buildWhereClauseForAdvancedSearch($dbname2searchTerm);
         if (!empty($advancedWhere['clause'])) {
             $where[] = join(" AND ", $advancedWhere['clause']);
             $params = $advancedWhere['params'];
         }
     }
     if ($data["sSearch"] !== "") {
         $searchTerms = explode(" ", $data["sSearch"]);
     }
     $selectorCount = "SELECT COUNT(*) ";
     $selectorRows = "SELECT " . join(",", $displayColumns) . " ";
     $sql = $selectorCount . " FROM " . $fromTable;
     $sqlTotalRows = $sql;
     if (isset($searchTerms)) {
         $searchCols = array();
         for ($i = 0; $i < $data["iColumns"]; $i++) {
             if ($data["bSearchable_" . $i] == "true") {
                 $searchCols[] = $data["mDataProp_{$i}"];
             }
         }
         $outerCond = array();
         $simpleWhere = array();
         foreach ($searchTerms as $term) {
             foreach ($searchCols as $col) {
                 $simpleWhere['clause']["simple_" . $col] = "{$col}::text ILIKE :simple_" . $col;
                 $simpleWhere['params']["simple_" . $col] = "%" . $term . "%";
             }
             $outerCond[] = "(" . implode(" OR ", $simpleWhere['clause']) . ")";
         }
         $where[] = "(" . implode(" AND ", $outerCond) . ")";
         $params = array_merge($params, $simpleWhere['params']);
     }
     // End Where clause
     // Order By clause
     $orderby = array();
     for ($i = 0; $i < $data["iSortingCols"]; $i++) {
         $num = $data["iSortCol_" . $i];
         $orderby[] = $data["mDataProp_{$num}"] . " " . $data["sSortDir_" . $i];
     }
     $orderby[] = "id";
     $orderby = join(",", $orderby);
     // End Order By clause
     $displayLength = intval($data["iDisplayLength"]);
     $needToBind = false;
     if (count($where) > 0) {
         $needToBind = true;
         $where = join(" OR ", $where);
         $sql = $selectorCount . " FROM " . $fromTable . " WHERE " . $where;
         $sqlTotalDisplayRows = $sql;
         $sql = $selectorRows . " FROM " . $fromTable . " WHERE " . $where . " ORDER BY " . $orderby;
         //limit the results returned.
         if ($displayLength !== -1) {
             $sql .= " OFFSET " . $data["iDisplayStart"] . " LIMIT " . $displayLength;
         }
     } else {
         $sql = $selectorRows . " FROM " . $fromTable . " ORDER BY " . $orderby;
         //limit the results returned.
         if ($displayLength !== -1) {
             $sql .= " OFFSET " . $data["iDisplayStart"] . " LIMIT " . $displayLength;
         }
     }
     try {
         $r = $con->query($sqlTotalRows);
         $totalRows = $r->fetchColumn(0);
         if (isset($sqlTotalDisplayRows)) {
             $totalDisplayRows = Application_Common_Database::prepareAndExecute($sqlTotalDisplayRows, $params, 'column');
         } else {
             $totalDisplayRows = $totalRows;
         }
         //TODO
         if ($needToBind) {
             $results = Application_Common_Database::prepareAndExecute($sql, $params);
         } else {
             $stmt = $con->query($sql);
             $stmt->setFetchMode(PDO::FETCH_ASSOC);
             $results = $stmt->fetchAll();
         }
         // we need to go over all items and fix length for playlist
         // in case the playlist contains dynamic block
         foreach ($results as &$r) {
             //this function is also called for Manage Users so in
             //this case there will be no 'ftype'
             if (isset($r['ftype'])) {
                 if ($r['ftype'] == 'playlist') {
                     $pl = new Application_Model_Playlist($r['id']);
                     $r['length'] = $pl->getLength();
                 } elseif ($r['ftype'] == "block") {
                     $bl = new Application_Model_Block($r['id']);
                     $r['bl_type'] = $bl->isStatic() ? 'static' : 'dynamic';
                     $r['length'] = $bl->getLength();
                 }
             }
         }
     } catch (Exception $e) {
         Logging::debug($e->getMessage());
     }
     return array("sEcho" => intval($data["sEcho"]), "iTotalDisplayRecords" => intval($totalDisplayRows), "iTotalRecords" => intval($totalRows), $dataProp => $results);
 }
Esempio n. 9
0
 public function notifyWebstreamDataAction()
 {
     $request = $this->getRequest();
     $data = $request->getParam("data");
     $media_id = $request->getParam("media_id");
     $data_arr = json_decode($data);
     if (!is_null($media_id) && isset($data_arr->title) && strlen($data_arr->title) < 1024) {
         $previous_metadata = CcWebstreamMetadataQuery::create()->orderByDbStartTime('desc')->filterByDbInstanceId($media_id)->findOne();
         $do_insert = true;
         if ($previous_metadata) {
             if ($previous_metadata->getDbLiquidsoapData() == $data_arr->title) {
                 Logging::debug("Duplicate found: " . $data_arr->title);
                 $do_insert = false;
             }
         }
         if ($do_insert) {
             $webstream_metadata = new CcWebstreamMetadata();
             $webstream_metadata->setDbInstanceId($media_id);
             $webstream_metadata->setDbStartTime(new DateTime("now", new DateTimeZone("UTC")));
             $webstream_metadata->setDbLiquidsoapData($data_arr->title);
             $webstream_metadata->save();
         }
     } else {
         throw new Error("Unexpected error. media_id {$media_id} has a null stream value in cc_schedule!");
     }
     $this->view->response = $data;
     $this->view->media_id = $media_id;
 }
Esempio n. 10
0
 public function passwordChangeAction()
 {
     //uses separate layout without a navigation.
     $this->_helper->layout->setLayout('login');
     $request = $this->getRequest();
     $token = $request->getParam("token", false);
     $user_id = $request->getParam("user_id", 0);
     $form = new Application_Form_PasswordChange();
     $auth = new Application_Model_Auth();
     $user = CcSubjsQuery::create()->findPK($user_id);
     //check validity of token
     if (!$auth->checkToken($user_id, $token, 'password.restore')) {
         Logging::debug("token not valid");
         $this->_helper->redirector('index', 'login');
     }
     if ($request->isPost() && $form->isValid($request->getPost())) {
         $user->setDbPass(md5($form->password->getValue()));
         $user->save();
         $auth->invalidateTokens($user, 'password.restore');
         $zend_auth = Zend_Auth::getInstance();
         $zend_auth->clearIdentity();
         $authAdapter = Application_Model_Auth::getAuthAdapter();
         $authAdapter->setIdentity($user->getDbLogin())->setCredential($form->password->getValue());
         $zend_auth->authenticate($authAdapter);
         //all info about this user from the login table omit only the password
         $userInfo = $authAdapter->getResultRowObject(null, 'password');
         //the default storage is a session with namespace Zend_Auth
         $authStorage = $zend_auth->getStorage();
         $authStorage->write($userInfo);
         $this->_helper->redirector('index', 'showbuilder');
     }
     $this->view->form = $form;
 }
$loglevel = Logging::$LOG_INFO;
$dryrun = $args['--dry-run'];
if ($args['--quiet']) {
    $loglevel = Logging::$LOG_QUIET;
} else {
    if ($args['--debug']) {
        $loglevel = Logging::$LOG_DEBUG;
    } else {
        $loglevel = Logging::$LOG_INFO;
    }
}
$logger = new Logging($loglevel);
/**
 * Just do some debug with arguments scanned by docopt
 */
$logger->debug("Script " . $_SERVER['argv'][0] . "called with following arguments:");
foreach ($args as $k => $v) {
    $logger->debug($k . ': ' . json_encode($v));
}
/**
 * Get every manifests in use in packages
 */
$manifests_used = getManifestsUsed($logger);
$logger->info(count($manifests_used) . " manifest(s) used in packages.");
$logger->debug($manifests_used);
/**
 * Get every manifests registered in database
 */
$manifests_registered = getManifestsRegistered($logger);
$logger->info(count($manifests_registered) . " manifest(s) registered in database.");
$logger->debug($manifests_registered);
Esempio n. 12
0
$logging = new Logging($firstthingsfirst_loglevel, "../logs/" . $firstthingsfirst_logfile);
# the tmp file name has to be given by means of a parameter
if (isset($_GET['tmp_file'])) {
    $tmp_file = $_GET['tmp_file'];
} else {
    $tmp_file = 'tmp.txt';
    $logging->warn("parameter tmp_file not given, assuming tmp.txt");
}
# the original file name has to be given by means of a parameter
if (isset($_GET['file_name'])) {
    $file_name = $_GET['file_name'];
} else {
    $file_name = 'list_export.csv';
    $logging->warn("parameter file_name not given, assuming list_export.csv");
}
$logging->debug("exporting file (tmp_file={$tmp_file}, file_name={$file_name})");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private, false");
#header("Content-Type: text/plain" );
header("Content-Disposition: attachment; filename=\"{$file_name}\";");
header("Content-Transfer-Encoding:­ binary");
ob_clean();
flush();
# read the file to standard out
$full_tmp_file_name = "../uploads/" . $tmp_file;
if (readfile($full_tmp_file_name) == FALSE) {
    print "ERROR could not read temporary file";
}
# delete the tmp file
 /**
  * add a new record to database
  * @param $name_values_array array array containing name-values of the record
  * @param $user_name string name of current user
  * @return int number indicates the id of the new record or 0 when no record was added
  */
 function insert($name_values_array, $user_name)
 {
     $values = array();
     $db_field_names = array_keys($name_values_array);
     $this->_log->trace("inserting into DatabaseTable (user_name=" . $user_name . ")");
     # check if database connection is working
     if ($this->_check_database_connection() == FALSE) {
         return 0;
     }
     # check if database table exists
     if (!$this->_database->table_exists($this->table_name)) {
         if ($this->create() == FALSE) {
             return 0;
         }
     }
     foreach ($db_field_names as $db_field_name) {
         $value = $name_values_array[$db_field_name];
         $field_type = $this->fields[$db_field_name][1];
         # check if db_field_name is known
         if ($field_type == "") {
             $this->_handle_error("unknown field type (db_field_name=" . $db_field_name . ")", "ERROR_DATABASE_PROBLEM");
             return 0;
         }
         $this->_log->debug("building insert query (db_field_name=" . $db_field_name . ", value=" . $value . ")");
         # encode text field
         if (stristr($field_type, "TEXT")) {
             $value = htmlentities($value, ENT_QUOTES);
         }
         if (stristr($field_type, "DATE")) {
             if (!$this->_check_datetime($value)) {
                 $this->_handle_error("given date string is incorrect (date_str=" . $value . ")", "ERROR_DATE_WRONG_FORMAT");
                 return 0;
             } else {
                 array_push($values, "'" . $value . "'");
             }
         } else {
             if ($field_type == FIELD_TYPE_DEFINITION_AUTO_CREATED || $field_type == FIELD_TYPE_DEFINITION_AUTO_MODIFIED) {
                 array_push($values, "'0'");
             } else {
                 array_push($values, "'" . $value . "'");
             }
         }
     }
     $query = "INSERT INTO " . $this->table_name . " VALUES (0, " . implode($values, ", ");
     # add archiver name and datetime
     if ($this->metadata_str[DATABASETABLE_METADATA_ENABLE_ARCHIVE] != DATABASETABLE_METADATA_FALSE) {
         $query .= ", \"\"";
         $query .= ", \"" . DB_NULL_DATETIME . "\"";
     }
     # add creator name and datetime
     if ($this->metadata_str[DATABASETABLE_METADATA_ENABLE_CREATE] != DATABASETABLE_METADATA_FALSE) {
         $query .= ", \"" . $user_name . "\"";
         $query .= ", \"" . strftime(DB_DATETIME_FORMAT) . "\"";
     }
     # add modifier name and datetime
     if ($this->metadata_str[DATABASETABLE_METADATA_ENABLE_MODIFY] != DATABASETABLE_METADATA_FALSE) {
         $query .= ", \"" . $user_name . "\"";
         $query .= ", \"" . strftime(DB_DATETIME_FORMAT) . "\"";
     }
     $query .= ")";
     $result = $this->_database->insertion_query($query);
     if ($result == 0) {
         $this->_handle_error("could not insert record to DatabaseTable", "ERROR_DATABASE_PROBLEM");
         return 0;
     }
     $this->_log->trace("inserted record into DatabaseTable (result=" . $result . ")");
     return $result;
 }
Esempio n. 14
0
 public static function debug_sparse(array $p_msg)
 {
     Logging::debug("Sparse output:");
     Logging::debug(array_filter($p_msg));
 }
<?php 
$doc = <<<DOC
get_job_logs.php

Usage:
   get_job_logs.php [-h | -q | -d ] [-m methods] [-t task_ids]

-h, --help     Show this help
-q, --quiet    Run quietly
-d, --debug    Show informations.

-m, --methods=methods   Show only tasks defined with a list of methods (separated by commas).
-t, --tasks=task_ids    Filter logs by tasks (separated by commas)
DOC;
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
include "../../../inc/includes.php";
include "./docopt.php";
require "./logging.php";
/**
 * Process arguments passed to the script
 */
$docopt = new \Docopt\Handler();
$args = $docopt->handle($doc);
$logger = new Logging();
$logger->setLevelFromArgs($args['--quiet'], $args['--debug']);
$logger->debug($args);
/*
 * Get Running Tasks
 */
$logs = PluginFusioninventoryTask::getJobLogs();
$logger->info($logs);
 public function saveAction()
 {
     $request = $this->getRequest();
     $id = $request->getParam("id");
     $parameters = array();
     foreach (array('id', 'length', 'name', 'description', 'url') as $p) {
         $parameters[$p] = trim($request->getParam($p));
     }
     if (!$this->isAuthorized($id)) {
         header("Status: 401 Not Authorized");
         return;
     }
     list($analysis, $mime, $mediaUrl, $di) = Application_Model_Webstream::analyzeFormData($parameters);
     try {
         if (Application_Model_Webstream::isValid($analysis)) {
             $streamId = Application_Model_Webstream::save($parameters, $mime, $mediaUrl, $di);
             Application_Model_Library::changePlaylist($streamId, "stream");
             $this->view->statusMessage = "<div class='success'>" . _("Webstream saved.") . "</div>";
             $this->view->streamId = $streamId;
             $this->view->length = $di->format("%Hh %Im");
         } else {
             throw new Exception("isValid returned false");
         }
     } catch (Exception $e) {
         Logging::debug($e->getMessage());
         $this->view->statusMessage = "<div class='errors'>" . _("Invalid form values.") . "</div>";
         $this->view->streamId = -1;
         $this->view->analysis = $analysis;
     }
 }
Esempio n. 17
0
 public function notifyWebstreamDataAction()
 {
     $request = $this->getRequest();
     $data = $request->getParam("data");
     $media_id = intval($request->getParam("media_id"));
     $data_arr = json_decode($data);
     //$media_id is -1 sometimes when a stream has stopped playing
     if (!is_null($media_id) && $media_id > 0) {
         if (isset($data_arr->title)) {
             $data_title = substr($data_arr->title, 0, 1024);
             $previous_metadata = CcWebstreamMetadataQuery::create()->orderByDbStartTime('desc')->filterByDbInstanceId($media_id)->findOne();
             $do_insert = true;
             if ($previous_metadata) {
                 if ($previous_metadata->getDbLiquidsoapData() == $data_title) {
                     Logging::debug("Duplicate found: " . $data_title);
                     $do_insert = false;
                 }
             }
             if ($do_insert) {
                 $startDT = new DateTime("now", new DateTimeZone("UTC"));
                 $webstream_metadata = new CcWebstreamMetadata();
                 $webstream_metadata->setDbInstanceId($media_id);
                 $webstream_metadata->setDbStartTime($startDT);
                 $webstream_metadata->setDbLiquidsoapData($data_title);
                 $webstream_metadata->save();
                 $historyService = new Application_Service_HistoryService();
                 $historyService->insertWebstreamMetadata($media_id, $startDT, $data_arr);
             }
         }
     }
     $this->view->response = $data;
     $this->view->media_id = $media_id;
 }
Esempio n. 18
0
 public function moveItem($selectedItems, $afterItems, $adjustSched = true)
 {
     $startProfile = microtime(true);
     $this->con->beginTransaction();
     $this->con->useDebug(true);
     try {
         $this->validateRequest($selectedItems);
         $this->validateRequest($afterItems);
         $endProfile = microtime(true);
         Logging::debug("validating move request took:");
         Logging::debug(floatval($endProfile) - floatval($startProfile));
         $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con);
         //map show instances to cc_schedule primary keys.
         $modifiedMap = array();
         $movedData = array();
         //prepare each of the selected items.
         for ($i = 0; $i < count($selectedItems); $i++) {
             $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con);
             $selectedInstance = $selected->getCcShowInstances($this->con);
             $data = $this->fileInfo;
             $data["id"] = $selected->getDbFileId();
             $data["cliplength"] = $selected->getDbClipLength();
             $data["cuein"] = $selected->getDbCueIn();
             $data["cueout"] = $selected->getDbCueOut();
             $data["fadein"] = $selected->getDbFadeIn();
             $data["fadeout"] = $selected->getDbFadeOut();
             $data["sched_id"] = $selected->getDbId();
             $movedData[] = $data;
             //figure out which items must be removed from calculated show times.
             $showInstanceId = $selectedInstance->getDbId();
             $schedId = $selected->getDbId();
             if (isset($modifiedMap[$showInstanceId])) {
                 array_push($modifiedMap[$showInstanceId], $schedId);
             } else {
                 $modifiedMap[$showInstanceId] = array($schedId);
             }
         }
         //calculate times excluding the to be moved items.
         foreach ($modifiedMap as $instance => $schedIds) {
             $startProfile = microtime(true);
             $this->removeGaps($instance, $schedIds);
             $endProfile = microtime(true);
             Logging::debug("removing gaps from instance {$instance}:");
             Logging::debug(floatval($endProfile) - floatval($startProfile));
         }
         $startProfile = microtime(true);
         $this->insertAfter($afterItems, $movedData, $adjustSched);
         $endProfile = microtime(true);
         Logging::debug("inserting after removing gaps.");
         Logging::debug(floatval($endProfile) - floatval($startProfile));
         $modified = array_keys($modifiedMap);
         //need to adjust shows we have moved items from.
         foreach ($modified as $instanceId) {
             $instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con);
             $instance->updateScheduleStatus($this->con);
         }
         $this->con->useDebug(false);
         $this->con->commit();
         Application_Model_RabbitMq::PushSchedule();
     } catch (Exception $e) {
         $this->con->rollback();
         throw $e;
     }
 }
Esempio n. 19
0
 public function addShowAction()
 {
     $js = $this->_getParam('data');
     $data = array();
     //need to convert from serialized jQuery array.
     foreach ($js as $j) {
         $data[$j["name"]] = $j["value"];
     }
     $data['add_show_hosts'] = $this->_getParam('hosts');
     $data['add_show_day_check'] = $this->_getParam('days');
     if ($data['add_show_day_check'] == "") {
         $data['add_show_day_check'] = null;
     }
     $validateStartDate = true;
     $success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate);
     if ($success) {
         $this->view->addNewShow = true;
         $this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
         Logging::debug("Show creation succeeded");
     } else {
         $this->view->addNewShow = true;
         $this->view->form = $this->view->render('schedule/add-show-form.phtml');
         Logging::debug("Show creation failed");
     }
 }
Esempio n. 20
0
 public function deleteAction()
 {
     //array containing id and type of media to delete.
     $mediaItems = $this->_getParam('media', null);
     $user = Application_Model_User::getCurrentUser();
     //$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
     $files = array();
     $playlists = array();
     $blocks = array();
     $streams = array();
     $message = null;
     foreach ($mediaItems as $media) {
         if ($media["type"] === "audioclip") {
             $files[] = intval($media["id"]);
         } elseif ($media["type"] === "playlist") {
             $playlists[] = intval($media["id"]);
         } elseif ($media["type"] === "block") {
             $blocks[] = intval($media["id"]);
         } elseif ($media["type"] === "stream") {
             $streams[] = intval($media["id"]);
         }
     }
     try {
         Application_Model_Playlist::deletePlaylists($playlists, $user->getId());
     } catch (PlaylistNoPermissionException $e) {
         $this->view->message = "You don't have permission to delete selected items.";
         return;
     }
     try {
         Application_Model_Block::deleteBlocks($blocks, $user->getId());
     } catch (Exception $e) {
         //TODO: warn user that not all blocks could be deleted.
     }
     try {
         Application_Model_Webstream::deleteStreams($streams, $user->getId());
     } catch (Exception $e) {
         //TODO: warn user that not all streams could be deleted.
         Logging::info($e);
     }
     foreach ($files as $id) {
         $file = Application_Model_StoredFile::Recall($id);
         if (isset($file)) {
             try {
                 $res = $file->delete(true);
             } catch (Exception $e) {
                 //could throw a scheduled in future exception.
                 $message = "Could not delete some scheduled files.";
                 Logging::debug($e->getMessage());
             }
         }
     }
     if (isset($message)) {
         $this->view->message = $message;
     }
 }
Esempio n. 21
0
}
# get the error messages
require_once "../lang/" . $firstthingsfirst_lang_prefix_array[$lang] . ".Text.Errors.php";
# test if the uploaded file is actually present
if (isset($_FILES['upload_file'])) {
    # uploaded file is present
    $tmp_name = $_FILES['upload_file']['tmp_name'];
    $upload_file_name = $_FILES['upload_file']['name'];
    $upload_file_size = $_FILES['upload_file']['size'];
    $upload_file_type = $_FILES['upload_file']['type'];
    $error_str = $_FILES['upload_file']['error'];
    $path_parts = pathinfo($upload_file_name);
    $upload_file_name_extension = $path_parts['extension'];
    # we want to save the file in the uploads directory
    $save_path = "../uploads";
    $logging->debug("uploading file (name={$tmp_name}, size={$upload_file_size}, lang={$lang}, mode={$mode})");
    # only allow files smaller than 1Mb
    if ($upload_file_size > 1048576) {
        $loggin->warn("file size exceeds 1MB");
        die(translate("ERROR_IMPORT_FILE_SIZE_TOO_LARGE"));
    }
    # only allow uploading of .txt or .csv files in import mode csv
    if ($mode == UPLOAD_MODE_CSV) {
        if ($upload_file_name_extension != "txt" && $upload_file_name_extension != "csv") {
            $logging->warn("file extension incorrect (extension={$upload_file_name_extension})");
            die(translate("ERROR_IMPORT_FILE_WRONG_EXTENSION"));
        }
    }
    $full_file_name = $save_path . "/" . $file_name;
    if (move_uploaded_file($tmp_name, $full_file_name) == FALSE) {
        $logging->warn("could not move uploaded file (tmp_name={$tmp_name}, full_file_name={$full_file_name})");
Esempio n. 22
0
 public function getListOfFilesUnderLimit()
 {
     $info = $this->getListofFilesMeetCriteria();
     $files = $info['files'];
     $limit = $info['limit'];
     $repeat = $info['repeat_tracks'];
     $insertList = array();
     $totalTime = 0;
     $totalItems = 0;
     // this moves the pointer to the first element in the collection
     $files->getFirst();
     $iterator = $files->getIterator();
     $isBlockFull = false;
     while ($iterator->valid()) {
         $id = $iterator->current()->getDbId();
         $fileLength = $iterator->current()->getCueLength();
         $length = Application_Common_DateHelper::calculateLengthInSeconds($fileLength);
         $insertList[] = array('id' => $id, 'length' => $length);
         $totalTime += $length;
         $totalItems++;
         if (!is_null($limit['items']) && $limit['items'] == count($insertList) || $totalItems > 500 || $totalTime > $limit['time']) {
             $isBlockFull = true;
             break;
         }
         $iterator->next();
     }
     $sizeOfInsert = count($insertList);
     // if block is not full and repeat_track is check, fill up more
     while (!$isBlockFull && $repeat == 1 && $sizeOfInsert > 0) {
         Logging::debug("adding repeated tracks.");
         Logging::debug("total time = " . $totalTime);
         $randomEleKey = array_rand(array_slice($insertList, 0, $sizeOfInsert));
         $insertList[] = $insertList[$randomEleKey];
         $totalTime += $insertList[$randomEleKey]['length'];
         $totalItems++;
         if (!is_null($limit['items']) && $limit['items'] == count($insertList) || $totalItems > 500 || $totalTime > $limit['time']) {
             break;
         }
     }
     return $insertList;
 }
 public function addShowAction()
 {
     $service_showForm = new Application_Service_ShowFormService(null);
     //$service_show = new Application_Service_ShowService();
     $js = $this->_getParam('data');
     $data = array();
     //need to convert from serialized jQuery array.
     foreach ($js as $j) {
         $data[$j["name"]] = $j["value"];
     }
     $service_show = new Application_Service_ShowService(null, $data);
     // TODO: move this to js
     $data['add_show_hosts'] = $this->_getParam('hosts');
     $data['add_show_day_check'] = $this->_getParam('days');
     if ($data['add_show_day_check'] == "") {
         $data['add_show_day_check'] = null;
     }
     $forms = $this->createShowFormAction();
     $this->view->addNewShow = true;
     if ($service_showForm->validateShowForms($forms, $data)) {
         $service_show->addUpdateShow($data);
         //send new show forms to the user
         $this->createShowFormAction(true);
         $this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
         Logging::debug("Show creation succeeded");
     } else {
         $this->view->form = $this->view->render('schedule/add-show-form.phtml');
         Logging::debug("Show creation failed");
     }
 }
 /**
  * get html (use Result object) of one specified record
  * @param $database_table DatabaseTable database table object
  * @param $list_title string title of list
  * @param $encoded_key_string string comma separated name value pairs
  * @param $db_field_names array array containing db_field_names to select for record
  * @param $result Result result object
  * @return string name of input element that should get focus
  */
 function get_record($database_table, $list_title, $encoded_key_string, $db_field_names, $result)
 {
     global $firstthingsfirst_field_descriptions;
     $this->_log->trace("getting record (list_title=" . $list_title . ", encoded_key_string=" . $encoded_key_string . ")");
     # get list record when key string has been given
     if (strlen($encoded_key_string) > 0) {
         $this->_log->debug("key string has been set");
         $record = $database_table->select_record($encoded_key_string);
         if (strlen($database_table->get_error_message_str()) > 0) {
             $this->_log->debug("error has been set");
             $this->_handle_error($database_table, $result, MESSAGE_PANE_DIV);
             return;
         }
     }
     $html_str = "";
     $return_name_tag = "";
     if (count($db_field_names) == 0) {
         $db_field_names = $database_table->get_db_field_names();
     }
     $fields = $database_table->get_fields();
     $tab_index = 0;
     # start with the action bar
     if (strlen($encoded_key_string)) {
         $html_str .= $this->get_action_bar($list_title, "edit");
     } else {
         $html_str .= $this->get_action_bar($list_title, "insert");
     }
     # then the form and table definition
     $html_str .= "\n                <div id=\"" . $this->configuration[HTML_TABLE_CSS_NAME_PREFIX] . "record_contents_pane\">\n";
     $html_str .= "                    <form name=\"record_form_name\" id=\"record_form\" action=\"javascript:void(0);\" method=\"javascript:void(0);\">\n";
     $html_str .= "                        <table id=\"" . $this->configuration[HTML_TABLE_CSS_NAME_PREFIX] . "record_contents\" align=\"left\" border=\"0\" cellspacing=\"2\">\n";
     $html_str .= "                            <tbody>\n";
     # add table record for each field type
     foreach ($db_field_names as $db_field_name) {
         $field_name = $fields[$db_field_name][0];
         $field_type = $fields[$db_field_name][1];
         $field_options = $fields[$db_field_name][2];
         $this->_log->debug("record (name=" . $field_name . " db_name=" . $db_field_name . " type=" . $field_type . ")");
         # set empty string if field does not exist (encoded_key_string was not set)
         if (strlen($encoded_key_string) == 0) {
             $record[$db_field_name] = "";
         }
         # replace all " chars with &quot
         $record[$db_field_name] = str_replace('"', "&#34", $record[$db_field_name]);
         # replace all space chars with &nbsp
         $field_name_replaced = str_replace(' ', '&nbsp;', $field_name);
         # translate field_name when this is not a list table
         if ($this->configuration[HTML_TABLE_PAGE_TYPE] != PAGE_TYPE_LIST) {
             $field_name_replaced = str_replace(' ', '&nbsp;', translate($field_name));
         } else {
             if ($field_type == FIELD_TYPE_DEFINITION_ATTACHMENTS) {
                 $field_name_replaced = str_replace(' ', '&nbsp;', translate("LABEL_DEFINITION_ATTACHMENTS"));
             }
         }
         # only add non auto_increment field types (check database definition for this)
         if ($field_type != FIELD_TYPE_DEFINITION_AUTO_NUMBER && strlen($field_name) > 0) {
             $html_str .= "                                <tr>\n";
             # translate the attachments field
             $html_str .= "                                    <th>" . $field_name_replaced . "</th>\n";
             # the name tag
             $tag = $db_field_name . GENERAL_SEPARATOR . $field_type . GENERAL_SEPARATOR . "0";
             if ($field_type != FIELD_TYPE_DEFINITION_NOTES_FIELD && $field_type != FIELD_TYPE_DEFINITION_ATTACHMENTS) {
                 $html_str .= "                                    <td id=\"" . $db_field_name;
                 $html_str .= "\" tabindex=\"" . $tab_index . "\"><" . $firstthingsfirst_field_descriptions[$field_type][FIELD_DESCRIPTION_FIELD_HTML_DEFINITION];
                 # create a name tag
                 $html_str .= " name=" . $tag . " id=" . $tag;
             }
             # set element name for return value
             if (strlen($return_name_tag) == 0 && !stristr($field_type, "AUTO")) {
                 $return_name_tag = $tag;
             }
             # set values from database
             if (strlen($encoded_key_string)) {
                 if ($field_type == FIELD_TYPE_DEFINITION_BOOL) {
                     # set is_admin checkbox to readonly when this is user admin page and user has no admin permissions
                     if ($this->configuration[HTML_TABLE_PAGE_TYPE] == PAGE_TYPE_USER_ADMIN && $this->_user->get_is_admin() == FALSE && $db_field_name == USER_IS_ADMIN_FIELD_NAME) {
                         $html_str .= " disabled=\"disabled\"";
                     }
                     if ($record[$db_field_name] == "1") {
                         $html_str .= " checked";
                     }
                 } else {
                     if (stristr($field_type, "DATE")) {
                         $date_string = get_date_str(DATE_FORMAT_NORMAL, $record[$db_field_name], $this->_user->get_date_format());
                         $html_str .= " value=\"" . $date_string . "\"";
                     } else {
                         if ($field_type == FIELD_TYPE_DEFINITION_AUTO_CREATED) {
                             if ($field_options == NAME_DATE_OPTION_NAME) {
                                 $html_str .= " value=\"" . $record[DB_CREATOR_FIELD_NAME] . "\"";
                             } else {
                                 $ts_created = get_date_str(DATE_FORMAT_FANCY, $record[DB_TS_CREATED_FIELD_NAME], $this->_user->get_date_format());
                                 if ($field_options == NAME_DATE_OPTION_DATE) {
                                     $html_str .= " value=\"{$ts_created}\"";
                                 } else {
                                     if ($field_options == NAME_DATE_OPTION_DATE_NAME) {
                                         $html_str .= " value=\"{$ts_created}&nbsp;(" . $record[DB_CREATOR_FIELD_NAME] . ")\"";
                                     }
                                 }
                             }
                         } else {
                             if ($field_type == FIELD_TYPE_DEFINITION_AUTO_MODIFIED) {
                                 if ($field_options == NAME_DATE_OPTION_NAME) {
                                     $html_str .= " value=\"" . $record[DB_MODIFIER_FIELD_NAME] . "\"";
                                 } else {
                                     $ts_modified = get_date_str(DATE_FORMAT_FANCY, $record[DB_TS_MODIFIED_FIELD_NAME], $this->_user->get_date_format());
                                     if ($field_options == NAME_DATE_OPTION_DATE) {
                                         $html_str .= " value=\"{$ts_modified}\"";
                                     } else {
                                         if ($field_options == NAME_DATE_OPTION_DATE_NAME) {
                                             $html_str .= " value=\"{$ts_modified}&nbsp;(" . $record[DB_MODIFIER_FIELD_NAME] . ")\"";
                                         }
                                     }
                                 }
                             } else {
                                 if ($field_type == FIELD_TYPE_DEFINITION_TEXT_FIELD) {
                                     $html_str .= ">" . $record[$db_field_name] . "</textarea";
                                 } else {
                                     if ($field_type == FIELD_TYPE_DEFINITION_PASSWORD) {
                                         $html_str .= " value=\"\"";
                                     } else {
                                         if ($field_type == FIELD_TYPE_DEFINITION_ATTACHMENTS) {
                                             $html_str .= get_list_record_attachments($list_title, $record[$db_field_name]);
                                         } else {
                                             if ($field_type == FIELD_TYPE_DEFINITION_SELECTION) {
                                                 $html_str .= ">";
                                                 $option_list = explode("|", $field_options);
                                                 foreach ($option_list as $option) {
                                                     $html_str .= "\n                                        <option value=\"" . $option . "\"";
                                                     if ($option == $record[$db_field_name]) {
                                                         $html_str .= " selected";
                                                     }
                                                     # translate selections in non list page (user admin)
                                                     if ($this->configuration[HTML_TABLE_PAGE_TYPE] != PAGE_TYPE_LIST && $fields[$db_field_name][1] == FIELD_TYPE_DEFINITION_SELECTION) {
                                                         $html_str .= ">" . translate($option) . "&nbsp;&nbsp;" . "</option>";
                                                     } else {
                                                         $html_str .= ">" . $option . "&nbsp;&nbsp;" . "</option>";
                                                     }
                                                 }
                                                 $html_str .= "\n                                    </select";
                                             } else {
                                                 if ($field_type == FIELD_TYPE_DEFINITION_NOTES_FIELD) {
                                                     $html_str .= get_list_record_notes($db_field_name, $record[$db_field_name]);
                                                 } else {
                                                     $html_str .= " value=\"" . $record[$db_field_name] . "\"";
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 if ($field_type == FIELD_TYPE_DEFINITION_BOOL) {
                     # set to readonly when this is user admin page and user has no admin permissions
                     if ($this->configuration[HTML_TABLE_PAGE_TYPE] == PAGE_TYPE_USER_ADMIN && $this->_user->get_is_admin() == FALSE && $db_field_name == USER_IS_ADMIN_FIELD_NAME) {
                         $html_str .= " disabled=\"disabled\"";
                     }
                 }
                 if ($field_type == FIELD_TYPE_DEFINITION_NUMBER && ($field_options != "" && $field_options != NUMBER_COLUMN_NO_SUMMATION && $field_options != NUMBER_COLUMN_SUMMATION)) {
                     $html_str .= " value=\"" . $field_options . "\"";
                 }
                 if ($field_type == FIELD_TYPE_DEFINITION_NON_EDIT_NUMBER) {
                     $html_str .= " value=\"0\"";
                 } else {
                     if (stristr($field_type, "DATE")) {
                         $date_string = get_date_str(DATE_FORMAT_NORMAL, strftime(DB_DATETIME_FORMAT), $this->_user->get_date_format());
                         $html_str .= " value=\"" . $date_string . "\"";
                     } else {
                         if ($field_type == FIELD_TYPE_DEFINITION_AUTO_CREATED || $field_type == FIELD_TYPE_DEFINITION_AUTO_MODIFIED) {
                             if ($field_options == NAME_DATE_OPTION_NAME) {
                                 $html_str .= " value=\"" . $this->_user->get_name() . "\"";
                             } else {
                                 $ts = get_date_str(DATE_FORMAT_FANCY, strftime(DB_DATETIME_FORMAT), $this->_user->get_date_format());
                                 if ($field_options == NAME_DATE_OPTION_DATE) {
                                     $html_str .= " value=\"{$ts}\"";
                                 } else {
                                     if ($field_options == NAME_DATE_OPTION_DATE_NAME) {
                                         $html_str .= " value=\"{$ts}&nbsp;(" . $this->_user->get_name() . ")\"";
                                     }
                                 }
                             }
                         } else {
                             if ($field_type == FIELD_TYPE_DEFINITION_TEXT_FIELD) {
                                 $html_str .= "></textarea";
                             } else {
                                 if ($field_type == FIELD_TYPE_DEFINITION_ATTACHMENTS) {
                                     $html_str .= get_list_record_attachments($list_title, array());
                                 } else {
                                     if ($field_type == FIELD_TYPE_DEFINITION_NOTES_FIELD) {
                                         $html_str .= get_list_record_notes($db_field_name, array());
                                     } else {
                                         if ($field_type == FIELD_TYPE_DEFINITION_SELECTION) {
                                             $html_str .= ">";
                                             $option_list = explode("|", $field_options);
                                             foreach ($option_list as $option) {
                                                 # translate selections in user admin page
                                                 if ($this->configuration[HTML_TABLE_PAGE_TYPE] != PAGE_TYPE_LIST && $fields[$db_field_name][1] == FIELD_TYPE_DEFINITION_SELECTION) {
                                                     $html_str .= "\n                                        <option value=\"" . $option . "\">" . translate($option) . "&nbsp;&nbsp;" . "</option>\n";
                                                 } else {
                                                     $html_str .= "\n                                        <option value=\"" . $option . "\">" . $option . "&nbsp;&nbsp;" . "</option>\n";
                                                 }
                                             }
                                             $html_str .= "\n                                    </select";
                                         } else {
                                             $html_str .= " value=\"\"";
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             if ($field_type != FIELD_TYPE_DEFINITION_NOTES_FIELD && $field_type != FIELD_TYPE_DEFINITION_ATTACHMENTS) {
                 $html_str .= "></td>\n";
             }
             $html_str .= "                                    <td class=\"super_width\">&nbsp;</td>\n";
             $html_str .= "                                </tr>\n";
         }
         $tab_index += 1;
     }
     # end table definition
     $html_str .= "                            </tbody>\n";
     $html_str .= "                        </table> <!-- " . $this->configuration[HTML_TABLE_CSS_NAME_PREFIX] . "record_contents -->\n";
     # define insert, update and cancel buttons
     $js_button_insert = "action_insert_" . $this->configuration[HTML_TABLE_JS_NAME_PREFIX] . "record";
     $js_button_update = "action_update_" . $this->configuration[HTML_TABLE_JS_NAME_PREFIX] . "record";
     $js_button_cancel = "action_cancel_" . $this->configuration[HTML_TABLE_JS_NAME_PREFIX] . "action";
     # add link to confirm contents to database
     $html_str .= "                        <span id=\"record_contents_buttons\">\n";
     $html_str .= "                            ";
     if (!strlen($encoded_key_string)) {
         $html_str .= get_href(get_onclick($js_button_insert, $this->permissions_list_title, "record_contents_buttons", "above", "(%27" . $list_title . "%27, xajax.getFormValues(%27record_form%27))"), translate("BUTTON_ADD"), "icon_add");
     } else {
         $html_str .= get_href(get_onclick($js_button_update, $this->permissions_list_title, "record_contents_buttons", "above", "(%27" . $list_title . "%27, %27" . $encoded_key_string . "%27, xajax.getFormValues(%27record_form%27))"), translate("BUTTON_COMMIT_CHANGES"), "icon_accept");
     }
     $html_str .= "\n                            ";
     # only display the cancel button when this is not the user settings page
     if ($this->configuration[HTML_TABLE_PAGE_TYPE] != PAGE_TYPE_USER_SETTINGS) {
         $html_str .= "&nbsp;&nbsp;" . get_href(get_onclick($js_button_cancel, HTML_NO_PERMISSION_CHECK, "", "", "('" . $list_title . "')"), translate("BUTTON_CANCEL"), "icon_cancel");
     }
     $html_str .= "\n                        </span> <!-- record_contents_buttons -->\n";
     #end form
     $html_str .= "                    </form> <!-- record_form -->\n";
     $html_str .= "                </div> <!-- " . $this->configuration[HTML_TABLE_CSS_NAME_PREFIX] . "record_contents_pane -->\n";
     $html_str .= "                <div class=\"corner bottom_left_normal\"></div>\n";
     $html_str .= "                <div class=\"corner bottom_right_normal\"></div>\n\n            ";
     $result->set_result_str($html_str);
     $this->_log->trace("got record (return_name_tag=" . $return_name_tag . ")");
     # return the element name
     return $return_name_tag;
 }