/** * Singleton - I called it 'logger' in case we want to * plug in Zend_Log at any stage. * * @return DTLog */ public static function logger() { if (!isset(self::$logger)) { self::$logger = new DTLog(); } return self::$logger; }
public function token() { try { return new DTOAuthToken($this->db->where("token='{$this->access_token}'")); } catch (Exception $e) { DTLog::error("Could not find token: " . $e->getMessage()); } return null; }
protected function sendRequestToProvider($url, $params, $method = "GET", $multipart = false) { $mtd = strtolower($method) == "get" ? "GET" : "POST"; try { unset($params["tok"], $params["fmt"], $params["act"], $params["callback"]); $r = DTHTTPRequest::makeHTTPRequest($url, $params, $mtd); return $r->getResponseBody(); } catch (OAuthException $E) { DTLog::error("Failed to access ({$url})"); } }
public function verify($action) { try { if (parent::verify($action)) { //parent::verify has to happen first to set up userID! $user = new DTUser($this->db->filter(array("id" => $this->userID(), "is_admin" => 1))); return true; } } catch (Exception $e) { DTLog::warn("Failed attempt to access admin action '{$action}'."); return false; } return false; }
/** override the access token method to use add /oauth/ to the path */ function oauthAccessToken() { $token = $this->requestToken(); $secret = $this->requestTokenSecret(); $this->oauth->setToken($this->requestToken(), $this->requestTokenSecret()); $response = $this->oauth->getAccessToken("https://api.twitter.com/oauth/access_token"); if (!isset($response["oauth_token"])) { DTLog::error("bad response from access token request: " . json_encode($response)); } $this->setAccessToken($response["oauth_token"], $response["oauth_token_secret"]); $oauth = $this->session[$this->api["name"]]; unset($oauth["oauth_request_token"]); unset($oauth["oauth_request_secret"]); }
/** @param params the parameters to match against @param defaults the default values to be passed to upsert @return returns the primary key for a model using cached results */ public function identifier($params, $defaults = array()) { $key = $this->key($params); if (!isset($this->cache[$key])) { $model = $this->model; $changes = array("summary" => "none"); $obj = $this->readonly ? new $this->model($this->db->filter($params)) : $model::upsert($this->db->filter($params), $params, $defaults, $changes); $this->cache[$key] = $obj->primaryKey(); if ($changes["summary"] == "new") { DTLog::info(DTLog::colorize("New object '{$model}' ({$this->cache[$key]})", "warn")); DTLog::info($changes); } } return $this->cache[$key]; }
/** performs standard authentication, authorizing the relevant token if necessary */ public function actionAuthenticate() { $u = parent::actionAuthenticate(); if (isset($u)) { try { //update oauth token $tok_str = $this->params->stringParam("oauth_token"); if (empty($tok_str)) { DTLog::error("OAuth token parameter was empty."); } $token = new DTOAuthToken($this->db->where("token='{$tok_str}' AND type=0")); return $this->authorizeToken($token, $u); } catch (Exception $e) { DTLog::Debug("auth error: " . $e->getMessage()); } //the user failed to authenticate (maybe bad user/pass) } return $u; }
/** performs standard authentication, authorizing the relevant token if necessary */ public function actionAuthenticate() { $u = parent::actionAuthenticate(); if (isset($u)) { try { //create oauth token $token = DTOAuthToken::upsert($this->db->qb()->fail(), array("type" => 0, "status" => 1, "user_id" => $u["id"])); $redirect_uri = $this->params->stringParam("redirect_uri"); $state = $this->params->stringParam("state"); $url = $this->appendParams($redirect_uri, array("code" => $token["token"], "state" => $state)); DTLog::debug($url); header('HTTP/1.1 278 Client Redirect', true, 278); return array("location" => $url); } catch (Exception $e) { DTLog::Debug("auth error: " . $e->getMessage()); } //the user failed to authenticate (maybe bad user/pass) } return $u; }
/** * reset a password * @param alias - the user to reset password for */ public function actionResetPassword() { $rst = $this->params->stringParam("rst"); $user_id = $this->params->stringParam("user_id"); try { $t = new DTResetToken($this->db->filter(array("token" => $rst, "user_id" => $user_id, "is_valid" => 1, "expires_at" => array(">", $this->db->now())))); $t["is_valid"] = 0; //invalidate the token $t->clean(); $t->update($this->db); $params = $this->params->allParams(); $u = $this->castUser($this->db->filter(array("id" => $user_id, "is_active" => 1))); $u->clean(); $u->merge($params); $u->update($this->db); } catch (Exception $e) { DTLog::error("Failed to reset password:" . $e->getMessage()); return false; } return true; }
/** * Executes the necessary commands to deploy the website. */ public function execute() { try { // Make sure we're in the right directory //exec('cd '.$this->_directory, $output); chdir($this->_directory); DTLog::info("Changing working directory to {$this->_directory}..."); // Discard any changes to tracked files since our last deploy exec('git reset --hard HEAD', $output); DTLog::info('Reseting repository... ' . implode("\n", $output)); // Update the local repository exec('git pull ' . $this->_remote . ' ' . $this->_branch, $output2); DTLog::info('Pulling in changes... ' . implode("\n", $output2)); // Secure the .git directory //exec('chmod -R o-rx .git'); //DTLog::info('Securing .git directory... '); if (is_callable($this->post_deploy)) { call_user_func($this->post_deploy, $this->_data); } DTLog::info('Deployment successful.'); } catch (Exception $e) { DTLog::info($e, 'ERROR'); } }
public function processEach($proc_f) { $row_i = 0; $this->db->begin(); while (($row = $this->getRow($row_i)) !== false) { /* it's important that we iterate the mapping to preserve key order */ $mapping = $this->mapping; $headers = $this->headers; $params = new DTParams(array_reduce(array_keys($mapping), function ($out, $k) use($mapping, $headers, $row) { $i = $headers[$k]; $out[$mapping[$k]] = isset($row[$i]) ? $row[$i] : null; return $out; }, array())); $mapped = $params->allParams(); try { $proc_f($mapped, $params); } catch (Exception $e) { DTLog::debug("Failed to ingest (%s):\n%s", $e->getMessage(), $mapped); } $row_i++; if ($row_i % $this->transaction_size == 0) { if ($this->dry_run) { $this->db->rollback(); } else { $this->db->commit(); } $this->db->begin(); DTLog::debug("* ({$row_i})"); } } if ($this->dry_run) { $this->db->rollback(); } else { $this->db->commit(); } }
public function setCreators($vals) { $authors = array(); $editors = array(); foreach ($vals as $i => $c) { $params = array(); $params["name_last"] = isset($c["name"]) ? $c["name"] : ""; //start with 'name' (e.g. institutes) $params["name_first"] = isset($c["firstName"]) ? $c["firstName"] : ""; if (isset($c["lastName"])) { $params["name_last"] = $c["lastName"]; } //override if we have it switch ($c["creatorType"]) { case "editor": case "seriesEditor": $model = static::modelFor("editors"); $obj = $model::bestMatch($this->db->filter(), $params); array_push($editors, $obj["id"]); break; default: $model = static::modelFor("authors"); $obj = $model::bestMatch($this->db->filter(), $params); array_push($authors, $obj["id"]); } } $this->authors = $this->setMany("authors", array_unique($authors)); $this->editors = $this->setMany("editors", array_unique($editors)); $manifest = $this->hasManyManifest(); $model = $manifest["authors"][0]; foreach ($this->authors as $i => $a) { try { $pa = $model::upsert($this->db->filter(array("publication_id" => $this["id"], "author_id" => $a["id"])), array("publication_id" => $this["id"], "author_id" => $a["id"], "position" => $i)); } catch (Exception $e) { DTLog::debug($e->getMessage()); } } $model = $manifest["editors"][0]; foreach ($this->editors as $i => $e) { try { $pe = $model::upsert($this->db->filter(array("publication_id" => $this["id"], "editor_id" => $e["id"])), array("publication_id" => $this["id"], "editor_id" => $e["id"], "position" => $i)); } catch (Exception $e) { DTLog::debug($e->getMessage()); } } }
/** * Handle commit hook post from bitbucket or github * @return string */ public function commit_hook() { if (isset($_POST['payload'])) { // github and bitbucket use a 'payload' parameter $json = $_POST['payload']; } else { $json = file_get_contents('php://input'); } if (!$json) { DTLog::debug('ignored #1'); return 'ignored'; } $data = $json ? json_decode($json, true) : null; if (!$data || !is_array($data['commits'])) { DTLog::debug('ignored #2'); return 'ignored'; } // look through the commits $found = false; $tags = array(); foreach ($data['commits'] as $commit) { if (preg_match('/\\[deploy(:.+)?\\]/', $commit['message'], $matches)) { $found = true; if (count($matches) > 1 && $matches[1] != '') { $tags[] = substr($matches[1], 1); } else { $tags[] = 'live'; } } } if (!$found) { return 'ignored'; } if (defined('DEPLOY_TAG') && !in_array(DEPLOY_TAG, $tags)) { DTLog::debug('ignored #3'); return 'ignored'; } // create the deployment increase_time_limit_to(600); $deploy = new Deploy(BASE_PATH, array()); $deploy->post_deploy = function () use($deploy) { global $_FILE_TO_URL_MAPPING; // composer install if detected if (file_exists(BASE_PATH . DIRECTORY_SEPARATOR . 'composer.json')) { if (file_exists('/usr/local/bin/composer')) { // TODO: more flexible composer detection exec('composer install', $output); DTLog::info('Executing composer install...' . implode("\n", $output)); //Checking for composer.phar } elseif (file_exists('/usr/local/bin/composer.phar')) { exec('/usr/local/bin/composer.phar install', $output); DTLog::info('Executing composer install...' . implode("\n", $output)); } else { DTLog::info('composer.json detected but unable to locate composer.'); } } // clear cache DTLog::info('Clearing cache...'); DeployController::clear_cache(); // update database if (isset($_FILE_TO_URL_MAPPING[BASE_PATH])) { exec('php framework/cli-script.php dev/build', $output2); DTLog::info('Updating database...' . implode("\n", $output2)); } else { DTLog::info('Database not updated. $_FILE_TO_URL_MAPPING must be set for ' . BASE_PATH); } // SS_ClassLoader::instance()->getManifest()->regenerate(); // ob_start(); // DatabaseAdmin::create()->doBuild(false, true, false); // DTLog::info('dev/build complete: '.ob_get_contents()); // ob_end_clean(); }; $deploy->execute(); return 'ok'; }
/** * Delete logs */ function dt_delete_log() { global $mc, $item, $log; $lg = new DTLog($log); if ($lg->isNew()) { redirect_header(DT_URL . ($mc['permalinks'] ? '/cp/logs/' . $item->id() : '/?p=cpanel&action=logs&id=' . $item->id()), 1, __('Specified log is not valid!', 'dtransport')); } if (!$lg->delete()) { redirect_header(DT_URL . ($mc['permalinks'] ? '/cp/logs/' . $item->id() : '/?p=cpanel&action=logs&id=' . $item->id()), 1, __('Log could not be deleted! Please try again.', 'dtransport')); } redirect_header(DT_URL . ($mc['permalinks'] ? '/cp/logs/' . $item->id() : '/?p=cpanel&action=logs&id=' . $item->id()), 1, __('Log deleted successfully!', 'dtransport')); }
public function synchronizeItems(&$version, $prefix = null) { $count = 0; $prefix = empty($prefix) ? "users/{$this->user}" : $prefix; $items = $this->itemsList($version, $prefix); DTLog::info("synchronizing %s items...", count($items)); $highest_version = 0; foreach ($items as $itemKey => $item_version) { //step through the modified items $count++; if ($count % 20 == 0) { DTLog::info("> %s%%", round($count / count($items) * 100)); } $highest_version = max($highest_version, $item_version); $item = $this->item($itemKey, $prefix); if ($item == null || $item["itemType"] == "note" || $item["itemType"] == "attachment") { //well, we didn't get it, what can we do? continue; } $item["itemKey"] = $itemKey; //we keep this for the delete logic (see +synchronize()+) //DTLog::debug($item); $params = new DTParams($item); //give us the chance to clean the params (only once!) $title = strtolower($params->stringParam("title")); $itemKey = $params->stringParam("itemKey"); //$qb = $this->db->where("item_key='{$itemKey}' OR LEVENSHTEIN(LOWER(substring(title from 1 for 250)),substring('{$title}' from 1 for 250))<10"); $qb = $this->db->where("item_key='{$itemKey}' OR LEVENSHTEIN(LOWER(title),'{$title}')<6"); $this->mergePublication($qb, $params->allParams()); } return $highest_version; }
/** * Debugs are printed in yellow * See this for reference: * http://www.bashguru.com/2010/01/shell-colors-colorizing-shell-scripts.html */ protected function debugmsg($message) { DTLog::debug($message); echo "[33m{$message}[0m\n"; }
/** * @desc Almacena los datos del log en la base de datos **/ function dt_save_log($edit = 0) { global $xoopsSecurity; $query = ''; foreach ($_POST as $k => $v) { ${$k} = $v; if ($k == 'XOOPS_TOKEN_REQUEST' || ($k = 'action')) { continue; } $query = $query == '' ? $k . '=' . urlencode($v) : "&{$k}=" . urlencode($v); } //Verificamos si el software es válido if ($item <= 0) { redirectMsg('items.php', __('Download item ID not provided!', 'dtransport'), RMMSG_WARN); } //Verificamos si existe el software $sw = new DTSoftware($item); if ($sw->isNew()) { redirectMsg('items.php', __('Specified download item does not exists!', 'dtransport'), RMMSG_WARN); } if (!$xoopsSecurity->check()) { redirectMsg('logs.php?item=' . $item, __('Session token not valid!', 'dtransport'), RMMSG_ERROR); } if ($edit) { $action = 'action=edit'; // Edición del registro if ($id <= 0) { redirectMsg('logs.php?item=' . $item, __('Item log ID not provided!', 'dtransport'), 1); } $lg = new DTLog($id); if ($lg->isNew()) { redirectMsg('logs.php?item=' . $item, __('Specified log does not exists!', 'dtransport'), 1); } } else { $action = 'action=new'; $lg = new DTLog(); } $lg->setSoftware($item); $lg->setTitle($title); $lg->setLog($log); $lg->setDate(time()); if (!$lg->save()) { redirectMsg('logs.php?' . $query . '&' . $action, __('Item log could not be saved!', 'dtransport') . '<br />' . $lg->error(), RMMSG_ERROR); } else { redirectMsg('logs.php?item=' . $item, __('Database updated successfully!', 'dtransport'), RMMSG_SAVED); } }
/** * @desc Obtiene los logs del elemento * @param bool True devuelve objetos {@link DTLog} * @return array */ function logs($asobj = false) { if (empty($this->_logs) || $asobj && !is_a($this->_logs[0], 'DTLog')) { $this->_logs = array(); $sql = "SELECT * FROM " . $this->db->prefix("dtrans_logs") . " WHERE id_soft='" . $this->id() . "' ORDER BY date DESC"; $result = $this->db->query($sql); while ($row = $this->db->fetchArray($result)) { if ($asobj) { $tmp = new DTLog(); $tmp->assignVars($row); } else { $tmp = $row['id_log']; } $this->_logs[] = $tmp; } } return $this->_logs; }
/** subclasses may override this method to provide custom token classes @return returns the token associated with this connection */ public function token() { if (!isset($this->provider, $this->provider->token)) { return null; } try { return new DTOAuthToken($this->db->where("token='{$this->provider->token}'")); } catch (Exception $e) { DTLog::error("Could not find token: " . $e->getMessage()); } return null; }