public function execute(&$value, &$error) { $className = $this->getParameter('class'); $columnName = $className . '.' . $this->getParameter('column'); $primaryKeys = sfDoctrine::getTable($className)->getPrimaryKeys(); foreach ($primaryKeys as $primaryKey) { if (is_null($primaryKeyValue = $this->getContext()->getRequest()->getParameter($primaryKey))) { } break; } $query = new Doctrine_Query(); $query->from($className); $value = strtolower($value); if ($primaryKeyValue === null) { $query->where($columnName . ' = ?'); $res = $query->execute(array($value)); } else { $query->where($columnName . ' = ? AND ' . $primaryKey . ' != ?'); $res = $query->execute(array($value, $primaryKeyValue)); } if (sizeof($res)) { $error = $this->getParameterHolder()->get('unique_error'); return false; } return true; }
public static function retrieveObjects($class, $peer_method = 'findAll') { if (!$peer_method) { $peer_method = 'findAll'; } $table = sfDoctrine::getTable($class); return call_user_func(array($table, $peer_method)); }
public static function retrieveNbComments($topic_subject) { if (is_string($topic_subject)) { return Doctrine_Query::create()->select('COUNT(p.id) nb_comments')->from('PunbbComm p, p.Topic t')->where('t.forum_id = 1 AND t.id = p.topic_id AND t.subject = ?', array($topic_subject))->execute()->getFirst()->nb_comments; } else { if (is_array($topic_subject)) { $sql = 'SELECT COUNT(p.id) nb_comments, p2.subject FROM punbb_posts p LEFT JOIN punbb_topics p2 ON p.topic_id = p2.id ' . 'WHERE (p2.forum_id = 1 AND p2.id = p.topic_id AND p2.subject IN ( ' . "'" . implode($topic_subject, "', '") . "'" . ')) GROUP BY p2.subject'; return sfDoctrine::connection()->standaloneQuery($sql)->fetchAll(); } else { return null; } } }
public static function getOutOfDatePendingUserIds() { $max_pending_time = sfConfig::get('app_pending_users_lifetime'); $limit_date = time() - $max_pending_time * 24 * 60 * 60; $sql = 'SELECT a.id FROM app_users_private_data a, app_users_groups ug ' . 'WHERE a.id = ug.user_id AND ug.group_id = 4 AND a.registered < ?'; $rs = sfDoctrine::connection()->standaloneQuery($sql, array($limit_date))->fetchAll(); $expired_users = array(); if (count($rs) > 0) { foreach ($rs as $item) { $expired_users[] = $item['id']; } } return $expired_users; }
public static function doSave($msg, $culture) { $obj = sfDoctrine::getTable('Message')->find($culture); if ($obj) { $obj->set('message', $msg); try { $obj->save(); return true; } catch (Exception $e) { return false; } } else { return false; } }
/** * Adds given address to given mailing list. * @param string listname * @param string email * @return boolean status (true=success, false=failure) */ public static function subscribe($listname, $email) { $conn = sfDoctrine::Connection(); try { $conn->beginTransaction(); $sympa = new Sympa(); $sympa->list_subscriber = $listname; $sympa->user_subscriber = $email; $sympa->save(); $conn->commit(); return true; } catch (Exception $e) { // Subscription failed! For instance because email address was already registered. $conn->rollback(); c2cTools::log("Failed adding address {$email} to list {$listname}: " . $e->getMessage()); return false; } }
define('SF_ROOT_DIR', realpath(dirname(__FILE__) . '/..')); define('SF_APP', 'frontend'); define('SF_ENVIRONMENT', 'prod'); define('SF_DEBUG', false); define('GP_DIR', SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'tmp/'); require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php'; // needed for doctrine connection to work $context = sfContext::getInstance(); $zoom_levels = array('10' => 1, '20' => 2, '50' => 3, '100' => 4); $default_zoom = 5; $csv = ''; $nb_summits = 0; foreach (Doctrine_Query::create()->select('a.id')->from('Area a')->where('a.area_type = 1')->limit(3)->execute() as $area) { // summits $sql = "SELECT s.id, n.name, s.lon, s.lat, s.elevation FROM summits s, summits_i18n n, areas a " . "WHERE a.id = " . $area->id . " AND s.id = n.id AND s.redirects_to IS NULL AND summit_type = 1 AND s.geom IS NOT NULL AND n.culture = 'fr' " . "AND intersects(a.geom, s.geom) AND a.geom && s.geom " . "ORDER BY s.elevation DESC, n.name ASC"; $summits = sfDoctrine::connection()->standaloneQuery($sql)->fetchAll(); $i = 0; foreach ($summits as $summit) { $nb_summits++; $i++; $zoom = $default_zoom; foreach ($zoom_levels as $max => $level) { if ($i <= $max) { $zoom = $level; break; } } $csv .= sprintf('"%s";"%s";"%s";"http://www.camptocamp.org/summits/popup/%d/fr";"%d";"%d";"%d"' . "\n", $summit['name'], $summit['lon'], $summit['lat'], $summit['id'], $summit['elevation'], $zoom, $area->id); } } file_put_contents(GP_DIR . 'sommets_c2c.csv', $csv);
public static function find($id) { return sfDoctrine::getTable('HistoryMetadata')->find($id); }
public static function MarkTopicAsread($topic_id, $last_post_time) { // let's reproduce behaviour of mark_topic_read() from punbb // note that forum_id is always 1 for comments $user_id = sfContext::getInstance()->getUser()->getId(); $sql = "SELECT last_visit, read_topics FROM punbb_users WHERE id='{$user_id}';"; $result = sfDoctrine::connection()->standaloneQuery($sql)->fetchAll(); $last_visit = $result[0]['last_visit']; $read_topics = unserialize($result[0]['read_topics']); if ($last_visit >= $last_post_time) { return; } else { if (!empty($read_topics['f'][1]) && $read_topics['f'][1] >= $last_post_time) { return; } else { if (!empty($read_topics['t'][$topic_id]) && $read_topics['t'][$topic_id] >= $last_post_time) { return; } else { $read_topics['t'][$topic_id] = $last_post_time; $sql = "UPDATE punbb_users SET read_topics='" . pg_escape_string(serialize($read_topics)) . "' WHERE id='{$user_id}';"; sfDoctrine::connection()->standaloneQuery($sql); } } } }
/** * Changes the association order for associations of same type (eg summit-summit) * It should only be used for ss, pp and tt associations, but there is probably * no real problem if other associations are inverted */ public function executeInvertAssociation() { $user = $this->getUser(); $user_id = $user->getId(); $is_moderator = $user->hasCredential('moderator'); $type = $this->getRequestParameter('type'); $main_id = $this->getRequestParameter('main_id'); $linked_id = $this->getRequestParameter('linked_id'); // check if session timed out if (!$user_id) { return $this->setErrorAndRedirect('Session is over. Please login again.', $this->getRequest()->getReferer()); } // only moderators can perform such actions if (!$is_moderator) { return $this->setErrorAndRedirect('You do not have enough credentials to perform this operation', $this->getRequest()->getReferer()); } // we check that the association type really exists and that the two // documents are from the same model if (substr($type, 0, 1) != substr($type, -1) || !in_array($type, sfConfig::get('app_associations_types'))) { return $this->ajax_feedback('Wrong association type'); } // check that association exists in database $models = c2cTools::Type2Models($type); $model = $models['main']; $module = c2cTools::model2module($model); $a = Association::find($main_id, $linked_id, $type); // strict search if (!$a) { return $this->setErrorAndRedirect('Operation not allowed', $this->getRequest()->getReferer()); } // invert association $conn = sfDoctrine::Connection(); try { $conn->beginTransaction(); $a->main_id = $linked_id; $a->linked_id = $main_id; $a->save(); $al1 = new AssociationLog(); $al1->main_id = $main_id; $al1->linked_id = $linked_id; $al1->type = $type; $al1->user_id = $user_id; $al1->is_creation = 'false'; $al1->save(); $al1 = new AssociationLog(); $al1->main_id = $linked_id; $al1->linked_id = $main_id; $al1->type = $type; $al1->user_id = $user_id; $al1->is_creation = 'true'; $al1->save(); $conn->commit(); } catch (exception $e) { $conn->rollback(); c2cTools::log("executeInvertAssociation() : invertion failed ({$main_id}, {$linked_id}, {$type}, {$user_id}) - rollback"); return $this->ajax_feedback('Association invertion failed'); } // remove cache and force page reload $this->clearCache($module, $main_id, false, 'view'); $this->clearCache($module, $linked_id, false, 'view'); return $this->setNoticeAndRedirect('Association inverted', $this->getRequest()->getReferer()); }
public static function getBox2d($id, $module = null) { $values[] = $id; $table = !empty($module) ? $module : 'documents'; $sql = "SELECT Box2D(geom) FROM {$table} AS d WHERE d.id = ?"; $rs = sfDoctrine::connection()->standaloneQuery($sql, $values)->fetchObject(); $out = $rs->box2d; $begin = strpos($out, '(') + 1; $end = strrpos($out, ')'); return substr($out, $begin, $end - $begin); }
echo ' Create association with image ' . $image_data['id'] . "\n"; } if (!$DRY_RUN) { $asso = new Association(); $asso->doSaveWithValues($doc['id'], $image_data['id'], $association_type, $TOPO_MODERATOR_USER_ID); } $stat_associations_required++; } $image_ids[$tag[1]] = $image_data['id']; } else { // no corresponding id, the tag is incorrect and must not be modified. but a warning should be notified $stat_docs_with_invalid_references[] = $doc['id'] . ' (' . $doc['culture'] . ' - ' . $doc['name'] . ') http://' . $SERVER_NAME . '/' . strtolower($table) . 's' . '/' . $doc['id'] . '/' . $doc['culture'] . "\n"; } } // replace image tags $conn = sfDoctrine::Connection(); $db_doc = Document::find($table, $doc['id']); if (!$DRY_RUN) { $conn->beginTransaction(); $history_metadata = new HistoryMetadata(); $history_metadata->setComment('Updated image tags'); $history_metadata->set('is_minor', true); $history_metadata->set('user_id', $TOPO_MODERATOR_USER_ID); $history_metadata->save(); $db_doc->setCulture($doc['culture']); } foreach ($fields as $field) { $tag_data = $tags_for_field[$field]; $text = $doc[$field]; foreach ($tag_data as $tag_idx) { $references_to_modify++;
protected function doMerge($from_id, $document_from, $to_id, $document_to) { // fetch associated documents before doing the merging as associations will be transferred $associations = Association::findAllAssociations($from_id); parent::doMerge($from_id, $document_from, $to_id, $document_to); // search documents in which from is inserted, and replace the insertion with to foreach ($associations as $a) { $check_id = $a['main_id'] == $from_id ? $a['linked_id'] : ($check_id = $a['main_id']); $check_model = c2cTools::Letter2Model(substr($a['type'], 0, 1)); $check_module = c2cTools::Model2Module($check_model); $check_doc = Document::find($check_model, $check_id); $fields = sfConfig::get('mod_images_bbcode_fields_' . $check_module); // clear linked doc cache $this->clearCache($check_module, $check_id); $languages = $check_doc->getLanguages(); foreach ($languages as $language) { $modified = false; $conn = sfDoctrine::Connection(); $conn->beginTransaction(); $check_doc->setCulture($language); foreach ($fields as $field) { $text = $check_doc[$field]; $edited = preg_replace('#(\\[img=\\s*)' . $from_id . '([\\w\\s]*\\].*?\\[/img\\])\\n?#is', '${1}' . $to_id . '${2}', $text); $edited = preg_replace('#(\\[img=\\s*)' . $from_id . '([\\w\\s]*\\/\\])\\n?#is', '${1}' . $to_id . '${2}', $edited); if ($edited != $text) { $modified = true; $check_doc->set($field, $edited); } } if ($modified) { $history_metadata = new HistoryMetadata(); $history_metadata->setComment('Updated image tags'); $history_metadata->set('is_minor', true); $history_metadata->set('user_id', sfConfig::get('app_moderator_user_id')); $history_metadata->save(); c2cTools::log('After merge of image ' . $from_id . ' into ' . $to_id . ': update image tag for ' . strtolower($check_model) . ' ' . $check_id . ' (' . $language . ')'); $check_doc->save(); $conn->commit(); } else { $conn->rollback(); } } } // clear images lists and whatsnew cache $this->clearCache('images', 0, true); }
/** * restore cookie values from profile. Managed cookies not in the profile will be deleted */ public static function restorePrefCookies($user_id) { if (!($user_private_data = UserPrivateData::find($user_id))) { return; // silently stop } $response = sfContext::getInstance()->getResponse(); $managed_cookies = sfConfig::get('app_profile_cookies_list'); $fold_prefs = sfConfig::get('app_personalization_cookie_fold_positions'); $cookie_prefs = $user_private_data->getPref_cookies(); if (empty($cookie_prefs)) { // no saved value in profile, copy the current cookie values into profile // 'regular' cookies $cookie_values = array(); foreach ($managed_cookies as $cookie) { if (sfContext::getInstance()->getRequest()->getCookie($cookie)) { $cookie_values[$cookie] = urlencode(sfContext::getInstance()->getRequest()->getCookie($cookie)); } } // fold prefs if (sfContext::getInstance()->getRequest()->getCookie('fold')) { $fold_cookie_value = sfContext::getInstance()->getRequest()->getCookie('fold'); foreach ($fold_prefs as $pos => $pref) { if ($fold_cookie_value[$pos] == 't') { $cookie_values[$pref + '_home_status'] = 'true'; } else { if ($fold_cookie_value[$pos] == 'f') { $cookie_values[$pref + '_home_status'] = 'false'; } } } } if (!empty($cookie_values)) { $conn = sfDoctrine::Connection(); try { $user_private_data->setPref_cookies($cookie_values); $user_private_data->save(); $conn->commit(); } catch (Exception $e) { $conn->rollback(); } } } else { // set fold cookie $fold_cookie_value = $default = str_repeat('x', sfConfig::get('app_personalization_cookie_fold_size')); foreach ($fold_prefs as $pos => $pref) { if (isset($cookie_prefs[$pref . '_home_status'])) { $fold_cookie_value[$pos] = $cookie_prefs[$pref . '_home_status'] == 'true' ? 't' : 'f'; } } if ($fold_cookie_value != $default) { $response->setCookie('fold', $fold_cookie_value, time() + sfConfig::get('app_personalization_filter_timeout')); } else { $response->setCookie('fold', ''); } // erase all managed cookies or replace values with the one in profile foreach ($managed_cookies as $cookie_name) { if (array_key_exists($cookie_name, $cookie_prefs)) { $response->setCookie($cookie_name, $cookie_prefs[$cookie_name], time() + sfConfig::get('app_personalization_filter_timeout')); } else { $response->setCookie($cookie_name, ''); } } } }
/** * Retrieves an array of array(document_id, culture) of recently CREATED outings in a given mean time (in seconds). */ public static function listRecentInTime($mean_time) { $sql = 'SELECT d.document_id, d.culture, d.documents_versions_id, a.search_name FROM app_documents_versions d ' . 'LEFT JOIN outings_i18n a ON (d.document_id = a.id AND d.culture = a.culture) ' . "WHERE d.version = 1 AND (AGE(NOW(), d.created_at) < ( {$mean_time} * interval '1 second')) " . 'ORDER BY d.documents_versions_id DESC'; $outings = array(); foreach (sfDoctrine::connection()->standaloneQuery($sql)->fetchAll() as $outing) { $id = $outing['document_id']; $outings[$id] = $outing; // if outing is available in several cultures, oldest one is the one } if (!empty($outings)) { // remove outings having culture version already transmitted (older than $mean_time) $ids = implode(',', array_keys($outings)); $sql = "select distinct document_id from app_documents_versions where document_id in ({$ids}) and AGE(NOW(), created_at) > ( {$mean_time} * interval '1 second' )"; foreach (sfDoctrine::connection()->standaloneQuery($sql)->fetchAll() as $result) { $id = $result['document_id']; unset($outings[$id]); } } return $outings; }
public static function getLastDocs($summit_separator = ': ') { /* $q = Doctrine_Query::create() ->select('i.name, i.search_name, i.culture, a.id, a.module') ->from('DocumentVersion d') ->leftJoin('d.DocumentArchive a') ->leftJoin('d.DocumentI18nArchive i') ->where("d.version = 1 AND a.module != 'outings' AND a.module != 'users' AND a.module != 'images'") ->limit(20) ->orderBy('d.created_at DESC'); //return $q->execute(array(), Doctrine::FETCH_ARRAY); // FIXME: returns nothing!? $sql = $q->getSql(); */ // following query is ok, but the displayed name is the first name given to the document, should be the last one /* $sql = 'SELECT a2.id AS id, a2.module AS module, a3.name AS name, a3.search_name AS search_name, a3.culture AS culture ' . 'FROM app_documents_versions a ' . 'LEFT JOIN app_documents_archives a2 ON a.document_archive_id = a2.document_archive_id ' . 'LEFT JOIN app_documents_i18n_archives a3 ON a.document_i18n_archive_id = a3.document_i18n_archive_id ' . "WHERE (a.version = 1 AND a2.module != 'outings' AND a2.module != 'users' AND a2.module != 'images' AND a2.module != 'articles') " . 'ORDER BY a.created_at DESC LIMIT 20';*/ // this one uses last document name $sql = 'SELECT sub.id AS id, sub.module AS module, a3.name AS name, a3.search_name AS search_name, a3.culture AS culture ' . 'FROM ' . '(SELECT a2.id AS id, a2.module AS module, a.culture AS culture FROM app_documents_versions a ' . 'LEFT JOIN app_documents_archives a2 ON a.document_archive_id = a2.document_archive_id ' . "WHERE (a.version = 1 AND a2.module NOT IN ('outings', 'users', 'images', 'articles') AND a2.redirects_to IS NULL) " . 'ORDER BY a.created_at DESC LIMIT 20) AS sub ' . 'LEFT JOIN documents_i18n a3 ON a3.id = sub.id AND sub.culture = a3.culture'; $docs = sfDoctrine::connection()->standaloneQuery($sql)->fetchAll(); // get summit name for routes items $routes = Route::addBestSummitName(array_filter($docs, array('c2cTools', 'is_route')), $summit_separator); foreach ($routes as $key => $route) { $docs[$key] = $route; } return $docs; }
/** * dumpData * * @param mixed $directory_or_file * @param string $tables * @param string $connectionName * @access public * @return void */ public function dumpData($directory_or_file = null, $tables = 'all', $connectionName = 'propel') { $sameFile = true; if (is_dir($directory_or_file)) { // multi files $sameFile = false; } else { // same file // delete file } $manager = Doctrine_Manager::getInstance(); $con = $manager->getCurrentConnection(); // get tables if ('all' === $tables || null === $tables) { $modelDirectories = array(); $modelDirectories[] = sfConfig::get('sf_model_lib_dir') . '/doctrine'; $directories = sfFinder::type('dir')->maxdepth(0)->in(sfConfig::get('sf_model_lib_dir') . '/doctrine'); foreach ($directories as $directory) { if (strstr($directory, 'generated')) { continue; } $modelDirectories[] = $directory; } $tables = array(); foreach ($modelDirectories as $directory) { $dirTables = sfFinder::type('file')->name('/(?<!Table)\\.class.php$/')->maxdepth(0)->in($directory); foreach ($dirTables as $key => $table) { $table = basename($table, '.class.php'); $tables[] = $table; } } } else { if (!is_array($tables)) { $tables = array($tables); } } $dumpData = array(); foreach ($tables as $modelName) { $table = sfDoctrine::getTable($modelName, $this->connectionName); // get table name $tableName = $table->getTableName(); $relations = $table->getRelations(); // get columns $columns = $con->fetchAll('DESCRIBE ' . $tableName); // get records //$records = $con->fetchAll('SELECT * FROM '.$tableName); $query = new Doctrine_Query(); $query->from($modelName); $records = $query->execute(); $dumpData[$modelName] = array(); foreach ($records as $record) { $pk = $modelName; $values = array(); foreach ($columns as $column) { $col = strtolower($column['Field']); try { $initialValue = $record[$col]; } catch (Exception $e) { continue; } if (!$initialValue) { continue; } if ($column['Key'] == 'PRI') { $pk .= '_' . $initialValue; } else { $isForeignKey = false; foreach ($relations as $relation) { if ($relation->getLocal() == $col) { $isForeignKey = true; break; } } if ($isForeignKey) { $array = $relation->toArray(); $values[$relation->getAlias()] = $array['class'] . '_' . $initialValue; } else { $value = $initialValue; // Needed to maintain bool values if (is_bool($value)) { $value = $value ? 1 : 0; } $values[$col] = $value; } } } $dumpData[$modelName][$pk] = $values; } } // save to file(s) if ($sameFile) { $yaml = Spyc::YAMLDump($dumpData); file_put_contents($directory_or_file, $yaml); } else { foreach ($dumpData as $table => $data) { $yaml = Spyc::YAMLDump($data); file_put_contents($directory_or_file . "/{$table}.yml", $yaml); } } }
<?php /** * Batch that dumps list of ranges to be used in metaengine. * * @version $Id: dumpRangesForMetaengine.php 2231 2007-10-31 14:22:09Z alex $ */ define('SF_ROOT_DIR', realpath(dirname(__FILE__) . '/..')); define('SF_APP', 'frontend'); define('SF_ENVIRONMENT', 'prod'); define('SF_DEBUG', false); require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php'; // needed for doctrine connection to work sfContext::getInstance(); $sql = 'SELECT n.name, ST_AsText(ST_Transform(a.geom, 4326)) as geom_wkt, a.id FROM areas a, areas_i18n n ' . 'WHERE a.id = n.id AND a.area_type = ? AND n.culture = ? ORDER BY n.name ASC'; $res = sfDoctrine::connection()->standaloneQuery($sql, array(1, 'fr'))->fetchAll(); $output = ''; foreach ($res as $r) { $output .= sprintf("INSERT INTO regions (name, external_region_id, system_id, geom) VALUES ('%s', %d, %d, GeomFromEWKT('SRID=4326;%s'));\n\n", addslashes($r['name']), $r['id'], sfConfig::get('app_meta_engine_c2c_id'), $r['geom_wkt']); } $output .= "VACUUM ANALYSE;"; file_put_contents("metaengine_ranges.sql", $output);
public function executeManageimages() { if (!$this->getUser()->isConnected()) { $referer = $this->getRequest()->getReferer(); $this->setErrorAndRedirect('You need to login to access this page', $referer); } $user_id = $this->getUser()->getId(); // logged user id $this->pager = new c2cDoctrinePager('Image', c2cTools::mobileVersion() ? sfConfig::get('app_list_mobile_maxline_number') : sfConfig::get('app_list_maxline_number')); $q = $this->pager->getQuery(); $q->select('i.id, i.filename, i.image_type, ii.name, ii.culture')->from('Image i')->leftJoin('i.associations a ON i.id = a.linked_id')->leftJoin('i.ImageI18n ii')->leftJoin('i.versions v')->leftJoin('v.history_metadata hm'); $where = 'i.image_type = 2 AND v.version = 1 AND hm.user_id = ?'; $document_type = $this->getRequestParameter('dtyp'); if (!empty($document_type)) { if ($document_type <= 1) { $types = array('ai', 'mi', 'bi', 'hi', 'pi', 'ri', 'ti', 'si'); } else { $types = array('oi', 'ui'); } $where .= " AND a.type IN ( '" . implode("', '", $types) . "' )"; } else { $document_type = $this->getRequestParameter('ctyp'); if (!empty($document_type)) { $q->leftJoin('a.Article c'); if ($document_type <= 1) { $document_type = 1; } else { $document_type = 2; } $where .= " AND a.type = 'ci' AND c.article_type = {$document_type}"; } } $q->where($where, array($user_id)); $q->orderBy('i.id DESC'); $page = $this->getRequestParameter('page', 1); $this->pager->setPage($page); $this->pager->init(); $this->page = $page; if ($this->getRequest()->getMethod() == sfRequest::POST) { // images management $switch = $this->getRequestParameter('switch'); $lang = $this->getUser()->getCulture(); if (empty($switch)) { return $this->setNoticeAndRedirect('No image has been edited', "/users/manageimages?module=users&page={$page}"); } $conn = sfDoctrine::Connection(); $conn->beginTransaction(); $history_metadata = new HistoryMetadata(); $history_metadata->setComment('Switch to collaborative license'); $history_metadata->set('is_minor', true); $history_metadata->set('user_id', $user_id); $history_metadata->save(); foreach ($switch as $image_id) { // verify id corresponds to an image created by the user $img = Doctrine_Query::create()->select('i.id')->from('Image i')->leftJoin('i.versions v')->leftJoin('v.history_metadata hm')->where('v.version = 1 AND hm.user_id = ? AND i.id = ?', array($user_id, $image_id))->execute(); if (empty($img)) { $conn->rollback(); return $this->setNoticeAndRedirect('You do not have the right to change the license of theses images', "/users/manageimages?module=users&page={$page}"); } $db_doc = Document::find('Image', $image_id); $db_doc->set('image_type', 1); $db_doc->save(); // clear cache $this->clearCache('images', $image_id, false, 'view'); $associated_docs = Association::findAllAssociatedDocs($image_id, array('id', 'module')); foreach ($associated_docs as $doc) { // clear their view cache $this->clearCache($doc['module'], $doc['id'], false, 'view'); } } // apply modifications if everything went fine $conn->commit(); return $this->setNoticeAndRedirect('Your images have been successfully updated', "/users/manageimages?module=users&page={$page}"); } else { // display form $this->setPageTitle($this->__('User image management')); } }
public static function getSubSummits($id) { $query = 'SELECT m.id FROM summits m WHERE m.id IN ' . '(SELECT a.linked_id FROM app_documents_associations a WHERE a.main_id = ? AND type = ?) ' . 'ORDER BY m.id ASC'; $results = sfDoctrine::connection()->standaloneQuery($query, array($id, 'ss'))->fetchAll(); return $results; }
public function doSaveWithValues($main_id, $linked_id, $type, $user_id) { $conn = sfDoctrine::Connection(); try { $conn->beginTransaction(); // we create the association: $this->main_id = $main_id; $this->linked_id = $linked_id; $this->type = $type; $this->save(); // and we log this: $al = new AssociationLog(); $al->main_id = $main_id; $al->linked_id = $linked_id; $al->type = $type; $al->user_id = $user_id; $al->is_creation = true; $al->save(); $conn->commit(); // send an email to moderators if a picture is associated to a book if ($type == 'bi') { try { // retrieve moderators email $moderator_id = sfConfig::get('app_moderator_user_id'); // currently send to topo-fr only $conn->beginTransaction(); $rows = $conn->standaloneQuery('SELECT email FROM app_users_private_data d WHERE id = ' . $moderator_id)->fetchAll(); $conn->commit(); $email_recipient = $rows[0]['email']; $mail = new sfMail(); $mail->setCharset('utf-8'); // definition of the required parameters $mail->setSender(sfConfig::get('app_outgoing_emails_sender')); $mail->setFrom(sfConfig::get('app_outgoing_emails_from')); $mail->addReplyTo(sfConfig::get('app_outgoing_emails_reply_to')); $mail->addAddress($email_recipient); $mail->setSubject('New image associated to book'); $mail->setContentType('text/html'); $server = $_SERVER['SERVER_NAME']; $body = "<p>A <a href=\"http://{$server}/images/{$linked_id}\">new image</a> has been associated to <a href=\"http://{$server}/books/{$main_id}\">book {$main_id}</a>.</p>" . "<p>The image may require a copyright license. If so, please ensure that:</p>" . "<ul>" . "<li>the owner is correctly acknowledged in the author field;</li>" . "<li>the image is not too big (max 800px width or height).</li>" . "</ul>"; $mail->setBody($body); // send the email $mail->send(); } catch (exception $e) { $conn->rollback(); c2cTools::log("Association::doSaveWithValues({$main_id}, {$linked_id}, {$type}, {$user_id}) failed sending email for image associated to book"); } } return true; } catch (exception $e) { $conn->rollback(); c2cTools::log("Association::doSaveWithValues({$main_id}, {$linked_id}, {$type}, {$user_id}) failed - rollback"); return false; } }
public function executeAddroute() { $id = $this->getRequestParameter('document_id'); // check if a summit is already associated to hut. if not, create it $create_summit = Association::countMains($id, 'sh') == 0; if ($create_summit) { $document = Document::find('Hut', $id, array('elevation', 'geom_wkt')); $conn = sfDoctrine::Connection(); try { $conn->beginTransaction(); // create first version of document, with culture and geometry of hut document $hut_elevation = $document['elevation']; $hut_lat = $document['lat']; $hut_lon = $document['lon']; $hut_culture = $document->getCulture(); $hut_name = $document['name']; $history_metadata = new HistoryMetadata(); $history_metadata->setComment($this->__('Created summit synchronized with hut for access')); $history_metadata->set('is_minor', false); $history_metadata->set('user_id', 2); // C2C user $history_metadata->save(); $summit = new Summit(); $summit->setCulture($hut_culture); $summit->set('name', $hut_name); $summit->set('elevation', $hut_elevation); $summit->set('summit_type', 100); // set summit type to ' hut' $summit->set('lat', $hut_lat); $summit->set('lon', $hut_lon); $summit->save(); $conn->commit(); // add others culture versions foreach ($document->get('HutI18n') as $i18n) { $culture = $i18n->getCulture(); if ($culture != $hut_culture) { $conn->beginTransaction(); $hut_name = $i18n->getName(); $history_metadata = new HistoryMetadata(); $history_metadata->setComment($this->__('Created summit synchronized with hut for access')); $history_metadata->set('is_minor', false); $history_metadata->set('user_id', 2); // C2C user $history_metadata->save(); $summit->setCulture($culture); $summit->set('name', $hut_name); $summit->save(); $conn->commit(); } } } catch (Exception $e) { $conn->rollback(); return $this->setErrorAndRedirect($this->__('Failed to create synchronized summit'), "routes/edit?link={$summit_id}"); } $summit_id = $summit->get('id'); // get all associated regions (3+maps) with this hut: $associations = GeoAssociation::findAllAssociations($id, array('dr', 'dc', 'dd', 'dv', 'dm')); // replicate them with summit_id instead of id: foreach ($associations as $ea) { $a = new GeoAssociation(); $a->doSaveWithValues($summit_id, $ea->get('linked_id'), $ea->get('type')); } // associate hut to summit $asso = new Association(); $asso->doSaveWithValues($summit_id, $id, 'sh', 2); // C2C user } else { $associations = Association::findAllAssociations($id, 'sh'); $summit_id = $associations[0]->get('main_id'); } $this->clearCache('huts', $id); return $this->redirect("routes/edit?link={$summit_id}"); }
public static function getLinkedFiles($id) { $filename_rows = sfDoctrine::Connection()->standaloneQuery('SELECT DISTINCT filename FROM app_images_archives WHERE id = ?', array($id))->fetchAll(); $filenames = array(); foreach ($filename_rows as $row) { $filenames[] = $row['filename']; } return $filenames; }
public static function findWithBestName($ids, $user_prefered_langs, $types = null, $current_doc_ids = null) { if (!is_array($ids)) { $ids = array($ids); } $where_array = array(); $where = "a.main_id IN ( '" . implode($ids, "', '") . "' )"; if ($types) { $where .= ' AND ( '; if (!is_array($types)) { $types = array($types); } $where2 = array(); foreach ($types as $type) { $where2[] = 'a.type = ?'; $where_array[] = $type; } $where .= implode(' OR ', $where2) . ' )'; } if (!empty($current_doc_ids)) { if (!is_array($current_doc_ids)) { $current_doc_ids = array($current_doc_ids); } $where .= " AND a.linked_id NOT IN ( '" . implode($current_doc_ids, "', '") . "' )"; } $doc_ids = "SELECT a.linked_id FROM app_geo_associations a WHERE {$where}"; $query = 'SELECT m.module, mi.id, mi.culture, mi.name, mi.search_name ' . 'FROM documents_i18n mi LEFT JOIN documents m ON mi.id = m.id ' . 'WHERE mi.id IN ' . "({$doc_ids}) " . 'ORDER BY mi.id ASC'; $results = sfDoctrine::connection()->standaloneQuery($query, $where_array)->fetchAll(); $out = self::setBestName($results, $user_prefered_langs); return $out; }
public static function find($id) { return sfDoctrine::getTable('PortalArchive')->find($id); }
/** * Save prefered language list in user session and bdd * * @param array ordered language list * @author Mickael Kurmann **/ public function savePreferedLanguageList($language_list) { // save in session $this->saveLanguageListInSession($language_list); // save it too in database if user connected if ($this->isConnected()) { $user_private_data = sfDoctrine::getTable('UserPrivateData')->find($this->getId()); $user_private_data->setPreferedLanguageList($language_list); $user_private_data->save(); } }
public static function find($id) { return sfDoctrine::getTable('RouteI18nArchive')->find($id); }
public static function listRecentInTime2($module, $mean_time) { $sql = 'SELECT d.document_id, d.culture FROM app_documents_versions d ' . 'LEFT JOIN app_documents_archives a ON d.document_id = a.id WHERE a.id = 106987 GROUP BY d.document_id, d.culture'; return sfDoctrine::connection()->standaloneQuery($sql)->fetchAll(); }
function update_document() { global $argv, $argc, $conn, $comment, $is_map, $is_new_document, $culture, $name, $map_editor, $newgeom, $map_scale, $map_code, $region_type, $newgeomtext, $no_oldgeom, $oldgeom, $document_id, $prgmsg, $fullwipe, $keepassociations; if ($argc < 5) { usage(); } if ($argv[2] != 'area' && $argv[2] != 'map') { usage(); } $is_map = $argv[2] === 'map'; if (!file_exists($argv[3])) { info("Kml file does not exist\n\n"); usage(); } if (!is_numeric($argv[4])) { info("Invalid region or map id\n\n"); usage(); } $document_id = intval($argv[4]); $fullwipe = $argc === 6 && $argv[5] === 'fullwipe'; $keepassociations = $argc === 6 && $argv[5] === 'keepassociations'; $is_new_document = false; info("Create geometry from kml file...\n"); $newgeomtext = text_geometry_from_file($argv[3]); $newgeom = geometry_from_text($newgeomtext); info("Validating geometry...\n"); // check that the new geometry is valid if (!validate_geometry($newgeom)) { die("The new geometry is invalid. Aborting...\n"); } // we need to first delete old geometry and old geaoassociations $oldgeom = $conn->standaloneQuery('SELECT geom FROM ' . ($is_map ? 'maps' : 'areas') . ' WHERE id=?', array($document_id))->fetchAll(); // check that document exists if (!count($oldgeom)) { die("Specified {$argv[2]} ({$document_id}) does not exist\n"); } // Output warning if document has no geometry $oldgeom = $oldgeom[0]['geom']; if (is_null($oldgeom)) { $no_oldgeom = true; info("Warning: specified {$argv[2]} ({$document_id}) has no geometry...\n"); } else { $no_oldgeom = false; } // first, remove geometry in a separate transaction if we are to update it // no better way found... if (!$no_oldgeom) { info("Deleting old geometry...\n"); try { $conn->beginTransaction(); $history_metadata = new HistoryMetadata(); $history_metadata->setComment('Delete geometry before update'); $history_metadata->set('is_minor', false); $history_metadata->set('user_id', 2); // C2C user $history_metadata->save(); $area = Document::find($is_map ? 'Map' : 'Area', $document_id); $area->set('geom_wkt', null); $area->save(); $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } info("Old geometry deleted\n"); } // then delete geoassociations // We only delete geoassociations where it is needed // ie the parts of the old geometry that does not intersect with the new one // If document has no previous geometry, we make sure to delete geoassociations // rq: we only use buffer for areas, not for maps if ($keepassociations) { // do nothing } else { if ($no_oldgeom || $fullwipe) { $geoassociations = GeoAssociation::findAllAssociations($document_id, null, 'both'); $prgmsg = "Delete all old geoassociations..."; info($prgmsg); try { $conn->beginTransaction(); $tot = count($geoassociations); foreach ($geoassociations as $i => $geoassociation) { progression($i, $tot); $geoassociation->delete(); } $conn->commit(); if (isset($deleted)) { associations_result($deleted, false); } } catch (exception $e) { $conn->rollback(); throw $e; } info("\n"); } else { $deletegeom = $conn->standaloneQuery("SELECT ST_Difference('{$oldgeom}', '{$newgeom}')")->fetchAll(); $deletegeomb = $conn->standaloneQuery("SELECT ST_Difference(buffer('{$oldgeom}', 200), buffer('{$newgeom}', 200))")->fetchAll(); $deletegeom = $deletegeom[0]['st_difference']; $deletegeomb = $deletegeomb[0]['st_difference']; // for maps, we don't use buffer at all if ($is_map) { $deletegeomb = $deletegeom; } $queries = array(); // point geometry $queries[] = array("SELECT id, module FROM documents WHERE geom && '{$deletegeomb}' " . "AND ST_Within(geom, '{$deletegeomb}') " . "AND module IN('summits', 'huts', 'sites', 'parkings', 'products', 'portals', 'images'" . ($is_map ? '' : ", 'users'") . ')', array()); $queries[] = array("SELECT id, module FROM documents WHERE geom && '{$deletegeomb}' " . "AND ST_Intersects(geom, '{$deletegeomb}') AND module" . ($is_map ? "='routes'" : " IN('routes', 'outings')"), array()); // for maps areas associations, we always compute 'full wipe', without buffer $queries[] = array("SELECT id, module FROM documents WHERE geom && '{$oldgeom}' " . "AND ST_Intersects(geom, '{$oldgeom}') AND module='" . ($is_map ? 'areas' : 'maps') . "'", array($document_id, $document_id)); $results_a = array(); foreach ($queries as $query) { $results_a[] = sfDoctrine::connection()->standaloneQuery($query[0], $query[1])->fetchAll(); } $results = array(); foreach ($results_a as $results_set) { foreach ($results_set as $d) { $results[] = $d; } } $tot = count($results); $prgmsg = "Delete obsolete geoassociations..."; info($prgmsg); try { $conn->beginTransaction(); foreach ($results as $i => $d) { progression($i, $tot); $geoassociation = GeoAssociation::find($document_id, $d['id'], null, false); if ($geoassociation !== false) { $geoassociation->delete(); $deleted[$d['module']] = isset($deleted[$d['module']]) ? $deleted[$d['module']] + 1 : 1; } // for routes and outings, we need to check that they are not intersecting the new geom // because they shouldn't be unlinked in that case // (it's quite unconvenient, but no best way found) if (in_array($d['module'], array('outings', 'routes'))) { $query = "SELECT ST_Intersects(geom, ST_Buffer('{$newgeom}', 200)) FROM " . $d['module'] . " WHERE id=?"; $result = sfDoctrine::connection()->standaloneQuery($query, array($d['id']))->fetchAll(); $result = $result[0]['st_intersects']; if ($result) { continue; } } // inherited docs: we delete geoassociations for the 'inherited docs' from sites, routes and summits // but not if they already have a geometry (gps track) switch ($d['module']) { case 'sites': case 'routes': if ($is_map) { break; } // maps are not linked to outings $associated_outings = Association::findAllAssociatedDocs($d['id'], array('id', 'geom_wkt'), $d['module'] === 'routes' ? 'ro' : 'to'); if (count($associated_outings)) { foreach ($associated_outings as $outing) { if (!$outing['geom_wkt']) { $geoassociation = GeoAssociation::find($document_id, $outing['id'], null, false); if ($geoassociation !== false) { $geoassociation->delete(); $deleted['outings'] = isset($deleted['outings']) ? $deleted['outings'] + 1 : 1; } } } } break; case 'summits': // if summit is of type raid, we should not try to update its routes and outings summit_type=5 $summit = Document::find('Summit', $d['id']); if ($summit->get('summit_type') == 5) { break; } $associated_routes = Association::findAllAssociatedDocs($d['id'], array('id', 'geom_wkt'), 'sr'); if (count($associated_routes)) { foreach ($associated_routes as $route) { $i = $route['id']; if (!$route['geom_wkt']) { $geoassociation = GeoAssociation::find($i, $document_id, null, false); if ($geoassociation !== false) { $geoassociation->delete(); $deleted['routes'] = isset($deleted['routes']) ? $deleted['routes'] + 1 : 1; } if (!$is_map) { $associated_outings = Association::findAllAssociatedDocs($i, array('id', 'geom_wkt'), 'ro'); if (count($associated_outings)) { foreach ($associated_outings as $outing) { $j = $outing['id']; if (!$outing['geom_wkt']) { $geoassociation = GeoAssociation::find($j, $document_id, null, false); if ($geoassociation !== false) { $geoassociation->delete(); $deleted['outings'] = isset($deleted['outings']) ? $deleted['outings'] + 1 : 1; } } } } } } } } break; } } info("\n"); $conn->commit(); if (isset($deleted)) { associations_result($deleted, false); } } catch (exception $e) { $conn->rollback(); throw $e; } } } // import new geometry into database and create geoassociations import_new_geometry(); }
public static function find($id) { return sfDoctrine::getTable('UserPrivateData')->find($id); }